diff --git a/internal/cli/game_import.go b/internal/cli/game_import.go index 5e02cb2..b82c607 100644 --- a/internal/cli/game_import.go +++ b/internal/cli/game_import.go @@ -46,6 +46,10 @@ func humanGameImport(w io.Writer, data any) { switch r := data.(type) { case []gamesource.Player: for _, p := range r { + if p.Message != "" { + fmt.Fprintf(w, "%s\t-\t%s\n", p.Kind, p.Message) + continue + } fmt.Fprintf(w, "%s\t%d\t%s\n", p.Kind, p.Index, p.Name) } case []string: diff --git a/internal/emu/game_import.go b/internal/emu/game_import.go index 0d5aa22..6ca8a74 100644 --- a/internal/emu/game_import.go +++ b/internal/emu/game_import.go @@ -83,7 +83,7 @@ func copyAPKs(ctx context.Context, src, dst importDevice, pkg string, files []st args := []string{"pm install -R --user 0 --pkg", pkg} for _, f := range files { target := importQuote(path.Join(dir, path.Base(f))) - err := importStream(ctx, src, dst, "cat "+importQuote(f), "cat > "+target, func(w io.Writer, r io.Reader) error { _, err := io.Copy(io.MultiWriter(w, p), r); return err }) + err := importStreamFunc(ctx, src, dst, "cat "+importQuote(f), "cat > "+target, func(w io.Writer, r io.Reader) error { _, err := io.Copy(io.MultiWriter(w, p), r); return err }) if err != nil { return err } @@ -174,6 +174,24 @@ func checkImportSpace(ctx context.Context, dst importDevice, need int64) error { return nil } +// appIdentity is the su argument that runs a command as the app's UID, with AID_EVERYBODY so it can traverse /storage. +func appIdentity(ctx context.Context, dst importDevice, pkg string) (string, error) { + out, err := dst.shell(ctx, "pm list packages -U --user 0 "+pkg) + if err != nil { + return "", err + } + for line := range strings.SplitSeq(out, "\n") { + f := strings.Fields(line) + if len(f) == 2 && f[0] == "package:"+pkg { + uid, e := strconv.Atoi(strings.TrimPrefix(f[1], "uid:")) + if e == nil && uid >= 10000 && uid < 100000 { + return fmt.Sprintf("%d,%d,9997", uid, uid), nil + } + } + } + return "", errs.Newf(errs.NotReady, "无法确认 %s 的应用 UID", pkg) +} + func importGame(ctx context.Context, src, dst importDevice, g ImportGame, progress func(Progress)) (GameImportResult, error) { result := GameImportResult{Package: g.Package} apks, err := apkPaths(ctx, src, g.Package) @@ -220,6 +238,20 @@ func importGame(ctx context.Context, src, dst importDevice, g ImportGame, progre sizes[f] = n result.ResourceBytes += n } + // Staging directories left by an interrupted import still hold their data. Remove them before the space check. + // The package's own directories belong to its app UID, so they wait for the UID unless the app is installed. + if err := removeStaleImportDirs(ctx, dst, []string{"/data/local/tmp"}); err != nil { + return result, err + } + var identity string + if reuse && len(resources) > 0 { + if identity, err = appIdentity(ctx, dst, g.Package); err != nil { + return result, err + } + if err := removeStaleImportDirs(ctx, dst.as(identity), resourceParents(resources)); err != nil { + return result, err + } + } // pm holds its own copy of the APKs while installing them. Allow space for small files and dex optimization. if err := checkImportSpace(ctx, dst, 2*result.APKBytes+result.ResourceBytes+(64<<20)); err != nil { return result, err @@ -232,28 +264,21 @@ func importGame(ctx context.Context, src, dst importDevice, g ImportGame, progre } } if len(resources) > 0 { - out, err := dst.shell(ctx, "pm list packages -U --user 0 "+g.Package) - if err != nil { - return result, err - } - for line := range strings.SplitSeq(out, "\n") { - f := strings.Fields(line) - if len(f) == 2 && f[0] == "package:"+g.Package { - uid, e := strconv.Atoi(strings.TrimPrefix(f[1], "uid:")) - if e == nil && uid >= 10000 && uid < 100000 { - dst.identity = fmt.Sprintf("%d,%d,9997", uid, uid) // AID_EVERYBODY can traverse /storage. - } + if identity == "" { + if identity, err = appIdentity(ctx, dst, g.Package); err != nil { + return result, err + } + if err := removeStaleImportDirs(ctx, dst.as(identity), resourceParents(resources)); err != nil { + return result, err } } - if dst.identity == "" { - return result, errs.Newf(errs.NotReady, "无法确认 %s 的应用 UID", g.Package) - } + dst.identity = identity } for _, f := range resources { if err := checkGuestSpace(ctx, dst, f, sizes[f]); err != nil { return result, err } - if err := copyResource(ctx, src, dst, f, &p); err != nil { + if err := copyResource(ctx, src, dst, f, sizes[f], &p); err != nil { return result, errs.Newf(errs.CodeOf(err), "导入 %s 失败:%v", f, err) } } @@ -314,6 +339,9 @@ func (m *Manager) ImportGames(ctx context.Context, target int, source gamesource return nil, errs.New(errs.InvalidArgument, "请选择第三方应用") } } + if err := checkGamesStopped(ctx, src, dst, games); err != nil { + return nil, err + } results := make([]GameImportResult, 0, len(games)) for _, g := range games { r, err := importGame(ctx, src, dst, g, progress) diff --git a/internal/emu/game_import_device.go b/internal/emu/game_import_device.go index 86ad89b..9e970d1 100644 --- a/internal/emu/game_import_device.go +++ b/internal/emu/game_import_device.go @@ -27,6 +27,7 @@ type importDevice struct { serial string bootID string identity string + exec func(ctx context.Context, args ...string) (string, error) // replaces adb in tests } func (d importDevice) command(ctx context.Context, args ...string) *exec.Cmd { @@ -42,6 +43,9 @@ func (d importDevice) command(ctx context.Context, args ...string) *exec.Cmd { } func (d importDevice) output(ctx context.Context, args ...string) (string, error) { + if d.exec != nil { + return d.exec(ctx, args...) + } ctx, cancel := context.WithTimeout(ctx, 15*time.Minute) defer cancel() cmd := d.command(ctx, args...) @@ -184,6 +188,54 @@ func packageList(ctx context.Context, d importDevice, flags string) ([]string, e return pkgs, nil } +// appRunning asks the guest, read-only, for the names of its processes (Toybox ps; NAME is argv[0], so a service of +// the app is ":"). The app runs when one of them is the package or starts with ":". An +// answer that is not a process list (no ps -A, adb trouble) is an error rather than a guess. +func appRunning(ctx context.Context, d importDevice, pkg string) (bool, error) { + out, err := d.shell(ctx, "ps -A -o NAME; echo exit:$?") + if err != nil { + return false, err + } + var names []string + for line := range strings.SplitSeq(out, "\n") { + if line = strings.TrimSpace(line); line != "" && line != "NAME" { + names = append(names, line) + } + } + if n := len(names); n < 2 || names[n-1] != "exit:0" { + return false, fmt.Errorf("ps: %q", tail(out, 200)) + } + for _, name := range names { + if name == pkg || strings.HasPrefix(name, pkg+":") { + return true, nil + } + } + return false, nil +} + +// checkGamesStopped refuses to start while any of the games is running on the target (it would be writing the +// resources being merged) or on the source (its files would change during the copy). It never stops a game. +func checkGamesStopped(ctx context.Context, src, dst importDevice, games []ImportGame) error { + for _, g := range games { + running, err := appRunning(ctx, dst, g.Package) + if err != nil { + return err + } + if running { + return errs.Newf(errs.PrecheckFailed, "目标实例上的 %s 正在运行,请先退出游戏再导入", g.Package) + } + } + for _, g := range games { + running, err := appRunning(ctx, src, g.Package) + if err != nil { + return err + } + if running { + return errs.Newf(errs.PrecheckFailed, "源模拟器上的 %s 正在运行,请先退出游戏再导入", g.Package) + } + } + return nil +} func (m *Manager) SourcePackages(ctx context.Context, source gamesource.Source) ([]string, error) { d, err := m.gameSource(ctx, source) if err != nil { diff --git a/internal/emu/game_import_flow_windows_test.go b/internal/emu/game_import_flow_windows_test.go new file mode 100644 index 0000000..9226268 --- /dev/null +++ b/internal/emu/game_import_flow_windows_test.go @@ -0,0 +1,124 @@ +//go:build windows + +// Copyright 2026 jinghero. SPDX-License-Identifier: AGPL-3.0-or-later +package emu + +import ( + "context" + "slices" + "strings" + "testing" + + "modavd/internal/logx" +) + +const ( + flowSum = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + flowDF = "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/block 100000000 1 99999999 1% /data\n" +) + +// flowGuests are a source and a target answering importGame's queries. The target holds the app already when +// installed is true. +func flowGuests(t *testing.T, installed bool) (src, dst *scriptedGuest) { + t.Helper() + m := &Manager{Root: managerTestRoot(t, 1), Log: logx.Nop()} + apk := "package:/data/app/~~x/example.game-1/base.apk\n" + common := func(script string) (string, bool) { + switch { + case strings.Contains(script, "pm path --user 0"): + return apk, true + case strings.Contains(script, "sha256sum"): + return flowSum + " /data/app/~~x/example.game-1/base.apk\n", true + } + return "", false + } + src = &scriptedGuest{reply: func(script string) (string, error) { + if out, ok := common(script); ok { + return out, nil + } + switch { + case strings.Contains(script, "-printf '%s"): + if strings.Contains(script, "/sdcard/") { + return "200", nil + } + return "100", nil + } + return "", nil + }} + dst = &scriptedGuest{reply: func(script string) (string, error) { + if out, ok := common(script); ok { + return out, nil + } + switch { + case strings.Contains(script, "pm list packages -u"): + if installed { + return "package:example.game\n", nil + } + return "", nil + case strings.Contains(script, "pm list packages -U"): + return "package:example.game uid:10123\n", nil + case strings.Contains(script, "df -Pk"): + return flowDF, nil + case strings.Contains(script, "pm install"): + return "Success\n", nil + } + return "", nil + }} + src.m, dst.m = m, m + return src, dst +} + +func (g *scriptedGuest) index(sub string) int { + g.mu.Lock() + defer g.mu.Unlock() + return slices.IndexFunc(g.scripts, func(s string) bool { return strings.Contains(s, sub) }) +} + +// ModAVD/ModAVD#272: the leftovers are gone before the space check, whether or not the app is installed yet, and +// the ones in the package's own directories are removed as the app's UID. +func TestImportGameRemovesStaleDirsBeforeCopying(t *testing.T) { + for _, installed := range []bool{false, true} { + name := "installing" + if installed { + name = "already installed" + } + t.Run(name, func(t *testing.T) { + fakeStream(t, func(read, write string) int { + if strings.HasPrefix(write, "cat > ") { + return 100 + } + return 200 + }) + src, dst := flowGuests(t, installed) + sd, dd := src.device(), dst.device() + g := ImportGame{Package: "example.game", Data: []string{"files/assets"}} + res, err := importGame(context.Background(), sd, dd, g, nil) + if err != nil { + t.Fatal(err) + } + if res.ResourceBytes != 200 { + t.Fatalf("result=%+v", res) + } + tmp := dst.index("-exec rm -rf") + df := dst.index("df -Pk") + if tmp < 0 || df < 0 || tmp > df || !strings.Contains(dst.scripts[tmp], "/data/local/tmp") || strings.Contains(dst.scripts[tmp], "su 10123") { + t.Fatalf("/data/local/tmp cleanup at %d, space check at %d: %q", tmp, df, dst.scripts) + } + app := "/sdcard/Android/data/example.game/files" + appClean := -1 + for i, s := range dst.scripts { + if strings.Contains(s, "-exec rm -rf") && strings.Contains(s, app) && strings.Contains(s, "su 10123,10123,9997") { + appClean = i + break + } + } + stage := dst.index(app + "/.modavd-import.XXXXXXXX") // the first staging directory in the app's directory + if appClean < 0 || stage < 0 || appClean > stage { + t.Fatalf("app directory cleanup at %d, staging at %d: %q", appClean, stage, dst.scripts) + } + if installed && appClean > df { + t.Fatalf("an installed app's directories must be cleaned before the space check: %d > %d", appClean, df) + } + }) + } +} diff --git a/internal/emu/game_import_test.go b/internal/emu/game_import_test.go new file mode 100644 index 0000000..996eb4b --- /dev/null +++ b/internal/emu/game_import_test.go @@ -0,0 +1,309 @@ +// Copyright 2026 jinghero. SPDX-License-Identifier: AGPL-3.0-or-later +package emu + +import ( + "archive/tar" + "bytes" + "context" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "testing" + + "modavd/internal/errs" + "modavd/internal/logx" +) + +// scriptedGuest answers the shell commands of the import code the way a guest would, and records every script. +// Nothing here starts adb: importDevice.exec stands in for it. +type scriptedGuest struct { + m *Manager // for tests that need a root + mu sync.Mutex + scripts []string + reply func(script string) (string, error) +} + +var mktempParent = regexp.MustCompile(`(/[^'"\s]+)/\.modavd-import\.XXXXXXXX`) + +func (g *scriptedGuest) device() importDevice { + m := g.m + if m == nil { + m = &Manager{Log: logx.Nop()} + } + return importDevice{m: m, exec: func(_ context.Context, args ...string) (string, error) { + script := args[len(args)-1] + g.mu.Lock() + g.scripts = append(g.scripts, script) + g.mu.Unlock() + if strings.Contains(script, "mktemp -d") { + // mktemp -d '/.modavd-import.XXXXXXXX', possibly inside the su wrapper's extra quoting + parent := mktempParent.FindStringSubmatch(script)[1] + return parent + "/.modavd-import.AbCd1234\n", nil + } + if g.reply != nil { + return g.reply(script) + } + return "", nil + }} +} + +func (g *scriptedGuest) ran(sub string) bool { + g.mu.Lock() + defer g.mu.Unlock() + for _, s := range g.scripts { + if strings.Contains(s, sub) { + return true + } + } + return false +} + +// fakeStream replaces the adb transfer: size gives the number of bytes the source delivers for a read/write pair. +// An APK goes through as raw bytes, a resource as a tar holding one file named like the item. +func fakeStream(t *testing.T, size func(read, write string) int) { + t.Helper() + saved := importStreamFunc + t.Cleanup(func() { importStreamFunc = saved }) + importStreamFunc = func(_ context.Context, _, _ importDevice, read, write string, copyData func(io.Writer, io.Reader) error) error { + n := size(read, write) + if strings.HasPrefix(write, "cat > ") { + return copyData(io.Discard, bytes.NewReader(make([]byte, n))) + } + name := strings.TrimSuffix(read[strings.Index(read, "tar -cf - './")+len("tar -cf - './"):], "'") + var buf bytes.Buffer + w := tar.NewWriter(&buf) + if err := w.WriteHeader(&tar.Header{Name: name, Size: int64(n), Mode: 0660, Typeflag: tar.TypeReg}); err != nil { + return err + } + if _, err := w.Write(make([]byte, n)); err != nil { + return err + } + if err := w.Close(); err != nil { + return err + } + return copyData(io.Discard, &buf) + } +} + +// ModAVD/ModAVD#271: an item whose transferred size differs from the size counted at the start is not published. +func TestCopyResourceDoesNotPublishChangedSource(t *testing.T) { + const full = "/sdcard/Android/data/example.game/files/assets" + for _, tc := range []struct { + name string + got, want int + publish bool + }{ + {"shorter than counted", 150, 200, false}, + {"longer than counted", 250, 200, false}, + {"as counted", 200, 200, true}, + } { + t.Run(tc.name, func(t *testing.T) { + p := &importProgress{done: 1000} // earlier items of the same import + fakeStream(t, func(string, string) int { return tc.got }) + g := &scriptedGuest{} + dev := g.device() + err := copyResource(context.Background(), dev, dev, full, int64(tc.want), p) + if tc.publish { + if err != nil { + t.Fatal(err) + } + } else if errs.CodeOf(err) != errs.Internal || !strings.Contains(err.Error(), "源文件大小在导入期间发生变化") { + t.Fatalf("err=%v", err) + } + if g.ran("publish()") != tc.publish { + t.Fatalf("published=%v scripts=%q", g.ran("publish()"), g.scripts) + } + // Only this item's staging directory is removed, whatever happened. + if !g.ran("rm -rf '/sdcard/Android/data/example.game/files/.modavd-import.AbCd1234'") { + t.Fatalf("staging directory was not removed: %q", g.scripts) + } + if g.ran("rm -rf '" + full) { + t.Fatalf("removed the final directory: %q", g.scripts) + } + }) + } +} + +// ModAVD/ModAVD#272: staging directories an interrupted import left behind are removed from the parents of the +// resources and from /data/local/tmp, and only those whose name is exactly .modavd-import. plus eight characters. +func TestRemoveStaleImportDirsScript(t *testing.T) { + g := &scriptedGuest{} + dev := g.device().as("10123,10123,9997") + parents := resourceParents([]string{ + "/sdcard/Android/data/example.game/files/a", "/sdcard/Android/data/example.game/files/b", + "/sdcard/Android/obb/example.game/main.1.example.game.obb", + }) + want := []string{"/sdcard/Android/data/example.game/files", "/sdcard/Android/obb/example.game"} + if !slices.Equal(parents, want) { + t.Fatalf("parents=%q", parents) + } + if err := removeStaleImportDirs(context.Background(), dev, append(parents, "/data/local/tmp")); err != nil { + t.Fatal(err) + } + if len(g.scripts) != 3 { + t.Fatalf("scripts=%q", g.scripts) + } + for i, parent := range append(want, "/data/local/tmp") { + s := g.scripts[i] + for _, sub := range []string{"su 10123,10123,9997", "find '\"'\"'" + parent + "'\"'\"' -mindepth 1 -maxdepth 1 -type d", ".modavd-import.????????", "rm -rf"} { + if !strings.Contains(s, sub) { + t.Fatalf("script %d lacks %q: %s", i, sub, s) + } + } + } +} + +func TestRemoveStaleImportDirsKeepsGoingAfterAFailure(t *testing.T) { + g := &scriptedGuest{reply: func(string) (string, error) { return "", errors.New("permission denied") }} + if err := removeStaleImportDirs(context.Background(), g.device(), []string{"/a", "/b"}); err != nil || len(g.scripts) != 2 { + t.Fatalf("err=%v scripts=%d", err, len(g.scripts)) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := removeStaleImportDirs(ctx, g.device(), []string{"/a"}); errs.CodeOf(err) != errs.Canceled { + t.Fatalf("err=%v", err) + } +} + +// Runs the generated command with a real POSIX shell (skipped without one) on a temporary directory. +func TestRemoveStaleImportDirsOnDisk(t *testing.T) { + sh, err := exec.LookPath("sh") + if err != nil { + t.Skip("no sh") + } + parent := filepath.ToSlash(t.TempDir()) + mkdir := func(name string) { + if err := os.MkdirAll(parent+"/"+name, 0o755); err != nil { + t.Fatal(err) + } + } + for _, name := range []string{ + ".modavd-import.AbCd1234/data", ".modavd-import.ZZZZ9999", + ".modavd-import.short", ".modavd-import.AbCd12345", "modavd-import.AbCd1234", "keep/.modavd-import.AbCd1234", + } { + mkdir(name) + } + if err := os.WriteFile(parent+"/.modavd-import.FileFile", []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(parent+"/.modavd-import.AbCd1234/data/big", []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + // Git for Windows keeps find in ..\usr\bin; Windows' own find.exe must not be the one that runs. + posix := func(script string) (string, error) { + cmd := exec.Command(sh, "-c", script) + bin := filepath.Dir(sh) + cmd.Env = append(os.Environ(), "PATH="+bin+string(os.PathListSeparator)+filepath.Join(bin, "..", "usr", "bin")+string(os.PathListSeparator)+os.Getenv("PATH")) + out, err := cmd.CombinedOutput() + return string(out), err + } + if _, err := posix("find '" + parent + "' -mindepth 1 -maxdepth 1 -type d -name 'nothing' -exec rm -rf {} +"); err != nil { + t.Skip("sh has no POSIX find: ", err) + } + g := &scriptedGuest{reply: posix} + dev := g.device() + if err := removeStaleImportDirs(context.Background(), dev, []string{parent, parent + "/missing"}); err != nil { + t.Fatal(err) + } + entries, err := os.ReadDir(parent) + if err != nil { + t.Fatal(err) + } + var left []string + for _, e := range entries { + left = append(left, e.Name()) + } + want := []string{".modavd-import.AbCd12345", ".modavd-import.FileFile", ".modavd-import.short", "keep", "modavd-import.AbCd1234"} + if !slices.Equal(left, want) { + t.Fatalf("left %q, want %q", left, want) + } + if _, err := os.Stat(parent + "/keep/.modavd-import.AbCd1234"); err != nil { + t.Fatal("removed a nested directory") + } +} + +// ModAVD/ModAVD#273: a game running on either side stops the import before anything is touched. +func TestAppRunningReadsProcessNames(t *testing.T) { + list := func(names ...string) string { + return "NAME\ninit\nzygote64\n" + strings.Join(names, "\n") + "\nsystem_server\nexit:0\n" + } + for _, tc := range []struct { + name, out string + running bool + fail bool + }{ + {"main process", list("example.game"), true, false}, + {"only a service", list("example.game:download"), true, false}, + {"main process and service", list("example.game", "example.game:push"), true, false}, + {"CRLF", strings.ReplaceAll(list("example.game:download"), "\n", "\r\n"), true, false}, + {"no header", "init\nexample.game\nexit:0\n", true, false}, + {"padded names", "NAME \ninit \nexample.game \nexit:0\n", true, false}, + {"not running", list(), false, false}, + {"longer package name", list("example.gamex", "example.game.extra"), false, false}, + {"other package's service named like the game", list("other.app:example.game"), false, false}, + {"suffix only", list("my.example.game", "my.example.game:svc"), false, false}, + {"no ps", "/system/bin/sh: ps: inaccessible or not found\nexit:127\n", false, true}, + {"ps failed after a partial list", "NAME\ninit\nexit:1\n", false, true}, + {"no process list", "NAME\nexit:0\n", false, true}, + {"no output", "", false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + g := &scriptedGuest{reply: func(string) (string, error) { return tc.out, nil }} + running, err := appRunning(context.Background(), g.device(), "example.game") + if running != tc.running || (err != nil) != tc.fail { + t.Fatalf("running=%v err=%v", running, err) + } + if len(g.scripts) != 1 || !strings.Contains(g.scripts[0], "ps -A -o NAME") { + t.Fatalf("scripts=%q", g.scripts) + } + }) + } +} + +func TestCheckGamesStopped(t *testing.T) { + games := []ImportGame{{Package: "example.one"}, {Package: "example.two"}} + answer := func(names ...string) func(string) (string, error) { + return func(string) (string, error) { + return "NAME\ninit\n" + strings.Join(names, "\n") + "\nexit:0\n", nil + } + } + for _, tc := range []struct { + name string + dst, src []string + wantErr string + srcAsked bool + }{ + {"both stopped", nil, nil, "", true}, + {"target running", []string{"example.two"}, nil, "目标实例上的 example.two 正在运行", false}, + {"target service only", []string{"example.two:download"}, nil, "目标实例上的 example.two 正在运行", false}, + {"source running", nil, []string{"example.one"}, "源模拟器上的 example.one 正在运行", true}, + {"source service only", nil, []string{"example.one:download"}, "源模拟器上的 example.one 正在运行", true}, + {"both running", []string{"example.one"}, []string{"example.one"}, "目标实例上的 example.one 正在运行", false}, + {"similar names are not the game", []string{"example.onex", "other:example.one"}, []string{"example.two.x"}, "", true}, + } { + t.Run(tc.name, func(t *testing.T) { + dst, src := &scriptedGuest{reply: answer(tc.dst...)}, &scriptedGuest{reply: answer(tc.src...)} + err := checkGamesStopped(context.Background(), src.device(), dst.device(), games) + if tc.wantErr == "" && err != nil { + t.Fatal(err) + } + if tc.wantErr != "" && (errs.CodeOf(err) != errs.PrecheckFailed || !strings.Contains(err.Error(), tc.wantErr)) { + t.Fatalf("err=%v", err) + } + if (len(src.scripts) > 0) != tc.srcAsked { + t.Fatalf("source asked=%v", len(src.scripts) > 0) + } + for _, s := range append(slices.Clone(src.scripts), dst.scripts...) { + if strings.Contains(s, "kill") || strings.Contains(s, "force-stop") || strings.Contains(s, "am ") { + t.Fatalf("not read-only: %q", s) + } + } + }) + } +} diff --git a/internal/emu/game_import_transfer.go b/internal/emu/game_import_transfer.go index 40ba980..b28eb14 100644 --- a/internal/emu/game_import_transfer.go +++ b/internal/emu/game_import_transfer.go @@ -9,6 +9,7 @@ import ( "io" "os/exec" "path" + "slices" "strings" "time" @@ -154,6 +155,41 @@ func (d importDevice) stage(ctx context.Context, parent string) (string, func(), }, nil } +// as returns the device running its commands as the given su identity. +func (d importDevice) as(identity string) importDevice { + d.identity = identity + return d +} + +// resourceParents lists, without repeats, the directories the staging directories of resources are made in. +func resourceParents(resources []string) []string { + var parents []string + for _, f := range resources { + if dir := path.Dir(f); !slices.Contains(parents, dir) { + parents = append(parents, dir) + } + } + return parents +} + +// removeStaleImportDirs deletes the staging directories (see stage) an interrupted import left in parents. It runs +// under the instance lock, so no other import can own one. Only directories directly in a parent whose name is +// exactly .modavd-import. and eight more characters are removed. Failing to remove them only wastes space, so it is +// logged and the import goes on. +func removeStaleImportDirs(ctx context.Context, d importDevice, parents []string) error { + for _, parent := range parents { + p := importQuote(parent) + _, err := d.shell(ctx, "[ ! -d "+p+" ] || find "+p+" -mindepth 1 -maxdepth 1 -type d -name '.modavd-import.????????' -exec rm -rf {} +") + if e := ctxErr(ctx); e != nil { + return e + } + if err != nil { + d.m.Log.Warnf("清理上次导入留下的临时目录失败:%v", err) + } + } + return nil +} + // An existing directory may already hold settings or completed items from an // earlier attempt. Add missing items atomically and compare collisions byte for byte. const publishResources = `publish() { @@ -187,7 +223,12 @@ const publishResources = `publish() { fi }` -func copyResource(ctx context.Context, src, dst importDevice, full string, p *importProgress) error { +// importStreamFunc is replaced in tests. +var importStreamFunc = importStream + +// copyResource transfers one selected resource into a staging directory next to its destination and publishes it. +// want is the size counted before the transfer: an item whose transferred bytes differ is not published. +func copyResource(ctx context.Context, src, dst importDevice, full string, want int64, p *importProgress) error { parent, name := path.Split(full) parent = strings.TrimSuffix(parent, "/") // pkgRoot is exactly /sdcard/Android/{data,obb}/. @@ -218,9 +259,15 @@ func copyResource(ctx context.Context, src, dst importDevice, full string, p *im defer cleanup() read := importPublicCD(parent) + " && tar -cf - " + importQuote("./"+name) write := "tar -xomf - -C " + importQuote(dir) - if err := importStream(ctx, src, dst, read, write, func(w io.Writer, r io.Reader) error { return copyImportTar(w, r, name, p) }); err != nil { + before := p.done + if err := importStreamFunc(ctx, src, dst, read, write, func(w io.Writer, r io.Reader) error { return copyImportTar(w, r, name, p) }); err != nil { return err } + // A source that changed while it was copied must not reach the final directory: a retry would find it there + // with other content and stop at already_exists. The deferred cleanup removes only this item's staging directory. + if got := p.done - before; got != want { + return errs.New(errs.Internal, "源文件大小在导入期间发生变化,请退出游戏后重试") + } // Stage and destination share a filesystem, so each newly published file arrives whole. staged, final := importQuote(path.Join(dir, name)), importQuote(full) _, err = dst.shell(ctx, publishResources+"\npublish "+staged+" "+final) diff --git a/internal/gamesource/manager.go b/internal/gamesource/manager.go index c11a7c3..bccf5eb 100644 --- a/internal/gamesource/manager.go +++ b/internal/gamesource/manager.go @@ -32,10 +32,30 @@ type Player struct { Ready bool `json:"ready"` Port int `json:"adb_port,omitempty"` Error int `json:"error_code,omitempty"` + Message string `json:"error,omitempty"` // only on the placeholder row of a player that could not be read (Index -1) enginePID uint32 } -type installation struct{ kind, exe, data string } +// run replaces the control program in tests. +type installation struct { + kind, exe, data string + run func(ctx context.Context, args ...string) ([]byte, error) +} + +// mumuExe finds the control program in the first install directory that has one. Older versions keep it in shell\. +func mumuExe(dirs []string) string { + for _, dir := range dirs { + if !filepath.IsAbs(dir) { + continue + } + for _, sub := range []string{"nx_main", "shell"} { + if exe := filepath.Join(dir, sub, "MuMuManager.exe"); isFile(exe) { + return exe + } + } + } + return "" +} func locate(kind string) (installation, error) { if runtime.GOOS != "windows" { @@ -43,11 +63,8 @@ func locate(kind string) (installation, error) { } pf := os.Getenv("ProgramFiles") if kind == "mumu" { - for _, dir := range append(mumuDirs(), filepath.Join(pf, "NetEase", "MuMu Player 12"), filepath.Join(pf, "NetEase", "MuMuPlayer")) { - exe := filepath.Join(dir, "nx_main", "MuMuManager.exe") - if filepath.IsAbs(dir) && isFile(exe) { - return installation{kind: kind, exe: exe}, nil - } + if exe := mumuExe(append(mumuDirs(), filepath.Join(pf, "NetEase", "MuMu Player 12"), filepath.Join(pf, "NetEase", "MuMuPlayer"))); exe != "" { + return installation{kind: kind, exe: exe}, nil } } else if kind == "ldplayer" { for _, i := range ldInstallations() { @@ -63,6 +80,9 @@ func locate(kind string) (installation, error) { func isFile(name string) bool { s, err := os.Stat(name); return err == nil && s.Mode().IsRegular() } func (i installation) command(ctx context.Context, args ...string) ([]byte, error) { + if i.run != nil { + return i.run(ctx, args...) + } ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() cmd := exec.CommandContext(ctx, i.exe, args...) @@ -82,8 +102,10 @@ func (i installation) command(ctx context.Context, args ...string) ([]byte, erro return out, nil } +// List returns the instances of every installed player. A player that cannot be read gets one placeholder row +// (Index -1, Error and Message set), so the other players are still listed. func List(ctx context.Context) ([]Player, error) { - players := []Player{} + var found []installation for _, kind := range []string{"mumu", "ldplayer"} { i, err := locate(kind) if errs.CodeOf(err) == errs.NotFound { @@ -92,11 +114,23 @@ func List(ctx context.Context) ([]Player, error) { if err != nil { return nil, err } + found = append(found, i) + } + return listAll(ctx, found) +} + +func listAll(ctx context.Context, found []installation) ([]Player, error) { + players := []Player{} + for _, i := range found { list, err := i.list(ctx) if err != nil { - return nil, err + if errs.CodeOf(err) == errs.Canceled { + return nil, err + } + players = append(players, Player{Source: Source{Kind: i.kind, Index: -1}, Error: -1, Message: err.Error()}) + continue } - if kind == "ldplayer" { + if i.kind == "ldplayer" { for pos, p := range list { if p.Ready { list[pos].Port = ldPort(i.data, p) @@ -120,28 +154,8 @@ func (i installation) list(ctx context.Context) ([]Player, error) { if err != nil { return nil, err } - var rows map[string]struct { - Index int `json:"index,string"` - Name string `json:"name"` - Running bool `json:"is_process_started"` - Ready bool `json:"is_android_started"` - Port int `json:"adb_port"` - Error int `json:"error_code"` - } - if err = json.Unmarshal(out, &rows); err != nil { - return nil, err - } - result := make([]Player, 0, len(rows)) - for key, r := range rows { - if key != strconv.Itoa(r.Index) || r.Index < 0 { - return nil, fmt.Errorf("MuMu info: %q", key) - } - result = append(result, Player{Source: Source{i.kind, r.Index}, Name: r.Name, Ready: r.Ready, Running: r.Running, Port: r.Port, Error: r.Error}) - } - sort.Slice(result, func(a, b int) bool { return result[a].Index < result[b].Index }) - return result, nil + return parseMuMuPlayers(out) } - func (i installation) launch(ctx context.Context, index int) error { n := strconv.Itoa(index) if i.kind == "ldplayer" { @@ -173,6 +187,10 @@ func Ready(ctx context.Context, s Source) (Player, error) { if err != nil { return Player{}, err } + return i.ready(ctx, s) +} + +func (i installation) ready(ctx context.Context, s Source) (Player, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Minute) defer cancel() launched := false diff --git a/internal/gamesource/mumu.go b/internal/gamesource/mumu.go new file mode 100644 index 0000000..f3184c3 --- /dev/null +++ b/internal/gamesource/mumu.go @@ -0,0 +1,109 @@ +// Copyright 2026 jinghero. SPDX-License-Identifier: AGPL-3.0-or-later +package gamesource + +import ( + "bytes" + "encoding/json" + "sort" + "strconv" + "strings" + + "modavd/internal/errs" +) + +// mumuInt reads a number the control program writes either as a JSON number or as a string. +type mumuInt int + +func (n *mumuInt) UnmarshalJSON(b []byte) error { + s := strings.Trim(strings.TrimSpace(string(b)), `"`) + if s == "" || s == "null" { + *n = 0 + return nil + } + v, err := strconv.Atoi(s) + *n = mumuInt(v) + return err +} + +type mumuRow struct { + Index *mumuInt `json:"index"` + Name *string `json:"name"` + Running bool `json:"is_process_started"` + Android bool `json:"is_android_started"` + State string `json:"player_state"` + LaunchErr mumuInt `json:"launch_err_code"` + Port mumuInt `json:"adb_port"` + Error mumuInt `json:"error_code"` +} + +func (r mumuRow) player() (Player, bool) { + if r.Index == nil || r.Name == nil || *r.Index < 0 { + return Player{}, false + } + // Without administrator rights is_android_started stays false for a running instance. + ready := r.Android || (r.Running && r.State == "start_finished" && r.LaunchErr == 0) + return Player{Source: Source{"mumu", int(*r.Index)}, Name: *r.Name, Ready: ready, Running: r.Running, Port: int(r.Port), Error: int(r.Error)}, true +} + +func mumuRowOf(raw json.RawMessage) (Player, bool) { + var r mumuRow + if json.Unmarshal(raw, &r) != nil { + return Player{}, false + } + return r.player() +} + +// parseMuMuPlayers reads the output of `info -v all`. Besides the usual object keyed by instance number the +// output can hold a single instance object, and tracking records or log lines around it. Every top-level JSON +// value in the output is looked at, and only the instance rows (those with an index and a name) are used. +func parseMuMuPlayers(out []byte) ([]Player, error) { + var found []Player + values := 0 + for pos := 0; ; { + n := bytes.IndexByte(out[pos:], '{') + if n < 0 { + break + } + pos += n + dec := json.NewDecoder(bytes.NewReader(out[pos:])) + var raw json.RawMessage + if err := dec.Decode(&raw); err != nil { + pos++ + continue + } + pos += int(dec.InputOffset()) + values++ + if p, ok := mumuRowOf(raw); ok { + found = append(found, p) + continue + } + var keyed map[string]json.RawMessage + if json.Unmarshal(raw, &keyed) != nil { + continue + } + for _, v := range keyed { + if p, ok := mumuRowOf(v); ok { + found = append(found, p) + } + } + } + if values == 0 { + return nil, errs.Newf(errs.Internal, "MuMu info:输出里没有可读的实例信息:%s", snippet(out)) + } + sort.SliceStable(found, func(a, b int) bool { return found[a].Index < found[b].Index }) + result := make([]Player, 0, len(found)) + for _, p := range found { + if len(result) == 0 || result[len(result)-1].Index != p.Index { + result = append(result, p) + } + } + return result, nil +} + +func snippet(out []byte) string { + s := strings.TrimSpace(string(out)) + if len(s) > 200 { + s = s[:200] + "…" + } + return s +} diff --git a/internal/gamesource/mumu_test.go b/internal/gamesource/mumu_test.go new file mode 100644 index 0000000..20777f6 --- /dev/null +++ b/internal/gamesource/mumu_test.go @@ -0,0 +1,171 @@ +// Copyright 2026 jinghero. SPDX-License-Identifier: AGPL-3.0-or-later +package gamesource + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "modavd/internal/errs" +) + +const mumuDict = `{"0":{"adb_port":16384,"error_code":0,"index":"0","is_android_started":true,"is_process_started":true,"name":"MuMu","player_state":"start_finished"},` + + `"1":{"index":"1","is_android_started":false,"is_process_started":false,"name":"MuMu-1"}}` + +func TestParseMuMuCleanDict(t *testing.T) { + rows, err := parseMuMuPlayers([]byte(mumuDict)) + if err != nil || len(rows) != 2 { + t.Fatalf("rows=%v err=%v", rows, err) + } + if r := rows[0]; r.Source != (Source{"mumu", 0}) || r.Name != "MuMu" || !r.Ready || !r.Running || r.Port != 16384 { + t.Fatal(r) + } + if r := rows[1]; r.Index != 1 || r.Running || r.Ready || r.Port != 0 { + t.Fatal(r) + } + if rows, err := parseMuMuPlayers([]byte("{}")); err != nil || rows == nil || len(rows) != 0 { + t.Fatalf("empty: %v %v", rows, err) + } +} + +// Tracking records and log lines around the JSON must not hide the instances. +func TestParseMuMuMixedWithTrackingAndLogs(t *testing.T) { + out := "[2026-11-27 12:00:01] MuMuManager start\r\n" + + `add record:{"event":"info","count":1,"nested":{"index":"7"}}` + "\r\n" + + mumuDict + "\r\n" + + "[WARN] unfinished {not json\r\n" + + `add record:{"event":"exit"}` + "\r\n" + rows, err := parseMuMuPlayers([]byte(out)) + if err != nil || len(rows) != 2 || rows[0].Index != 0 || rows[1].Index != 1 || rows[0].Name != "MuMu" || !rows[0].Ready { + t.Fatalf("rows=%v err=%v", rows, err) + } +} + +func TestParseMuMuSingleInstanceObject(t *testing.T) { + out := `add record:{"event":"info"}` + "\n" + + `{"adb_port":16416,"index":"2","is_android_started":true,"is_process_started":true,"name":"MuMu-2","player_state":"start_finished"}` + rows, err := parseMuMuPlayers([]byte(out)) + if err != nil || len(rows) != 1 { + t.Fatalf("rows=%v err=%v", rows, err) + } + if r := rows[0]; r.Source != (Source{"mumu", 2}) || r.Name != "MuMu-2" || !r.Ready || r.Port != 16416 { + t.Fatal(r) + } + // The index can also be a JSON number. + rows, err = parseMuMuPlayers([]byte(`{"index":3,"name":"n"}`)) + if err != nil || len(rows) != 1 || rows[0].Index != 3 { + t.Fatalf("numeric index: %v %v", rows, err) + } +} + +// Without administrator rights is_android_started stays false for a running instance. +func TestParseMuMuReadyWithoutAdministrator(t *testing.T) { + row := func(extra string) string { + return `{"index":"0","name":"MuMu","adb_port":16384,"is_android_started":false,"is_process_started":true` + extra + `}` + } + for _, tc := range []struct { + name, out string + ready bool + }{ + {"start_finished", row(`,"player_state":"start_finished"`), true}, + {"start_finished with zero launch error", row(`,"player_state":"start_finished","launch_err_code":0`), true}, + {"launch error", row(`,"player_state":"start_finished","launch_err_code":-5`), false}, + {"still starting", row(`,"player_state":"starting"`), false}, + {"no state", row(``), false}, + {"process gone", strings.Replace(row(`,"player_state":"start_finished"`), `"is_process_started":true`, `"is_process_started":false`, 1), false}, + } { + t.Run(tc.name, func(t *testing.T) { + rows, err := parseMuMuPlayers([]byte(tc.out)) + if err != nil || len(rows) != 1 || rows[0].Ready != tc.ready { + t.Fatalf("rows=%v err=%v", rows, err) + } + }) + } +} + +func TestParseMuMuRejectsOutputWithoutJSON(t *testing.T) { + if _, err := parseMuMuPlayers([]byte("access denied")); err == nil { + t.Fatal("accepted output without JSON") + } +} + +// The wait for a running instance ends at once with the fallback; it does not wait for is_android_started. +func TestReadyUsesPlayerStateFallback(t *testing.T) { + calls := 0 + i := installation{kind: "mumu", run: func(_ context.Context, args ...string) ([]byte, error) { + calls++ + if args[0] != "info" { + t.Errorf("unexpected command %v", args) + } + return []byte(`add record:{"event":"info"}` + "\n" + `{"0":{"index":"0","name":"MuMu","adb_port":16384,"is_android_started":false,"is_process_started":true,"player_state":"start_finished"}}`), nil + }} + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + p, err := i.ready(ctx, Source{"mumu", 0}) + if err != nil || p.Port != 16384 || !p.Ready || calls != 1 { + t.Fatalf("player=%+v err=%v calls=%d", p, err, calls) + } +} + +func TestMuMuExeFindsOldShellDirectory(t *testing.T) { + root := t.TempDir() + touch := func(parts ...string) string { + p := filepath.Join(append([]string{root}, parts...)...) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, nil, 0o644); err != nil { + t.Fatal(err) + } + return p + } + oldOnly, both := filepath.Join(root, "old"), filepath.Join(root, "both") + wantOld := touch("old", "shell", "MuMuManager.exe") + touch("both", "shell", "MuMuManager.exe") + wantNew := touch("both", "nx_main", "MuMuManager.exe") + if got := mumuExe([]string{"relative", filepath.Join(root, "none"), oldOnly}); got != wantOld { + t.Fatalf("old layout: %q", got) + } + if got := mumuExe([]string{both}); got != wantNew { + t.Fatalf("nx_main must win: %q", got) + } + if got := mumuExe([]string{"", "relative", filepath.Join(root, "none")}); got != "" { + t.Fatalf("found %q", got) + } +} + +// One player that cannot be read is marked on its own row; the other players are still listed. +func TestListKeepsOtherSourcesWhenOneFails(t *testing.T) { + mumu := installation{kind: "mumu", run: func(context.Context, ...string) ([]byte, error) { + return nil, errors.New("MuMuManager.exe info: exit status 1") + }} + ld := installation{kind: "ldplayer", run: func(_ context.Context, args ...string) ([]byte, error) { + if args[0] != "list2" { + t.Errorf("unexpected command %v", args) + } + return []byte("0,Offline,0,0,0,-1,-1\r\n"), nil + }} + rows, err := listAll(context.Background(), []installation{mumu, ld}) + if err != nil || len(rows) != 2 { + t.Fatalf("rows=%v err=%v", rows, err) + } + if r := rows[0]; r.Kind != "mumu" || r.Index != -1 || r.Error == 0 || !strings.Contains(r.Message, "exit status 1") || r.Valid() { + t.Fatal(r) + } + if r := rows[1]; r.Source != (Source{"ldplayer", 0}) || r.Name != "Offline" || r.Error != 0 { + t.Fatal(r) + } +} + +func TestListStopsWhenCanceled(t *testing.T) { + mumu := installation{kind: "mumu", run: func(context.Context, ...string) ([]byte, error) { + return nil, errs.New(errs.Canceled, "已取消") + }} + if _, err := listAll(context.Background(), []installation{mumu}); errs.CodeOf(err) != errs.Canceled { + t.Fatalf("err=%v", err) + } +} diff --git a/internal/i18n/locales/en/emu.json b/internal/i18n/locales/en/emu.json index 731b9a8..634f57d 100644 --- a/internal/i18n/locales/en/emu.json +++ b/internal/i18n/locales/en/emu.json @@ -695,12 +695,14 @@ "没认出是哪个程序,多半是 MAA 这类用 ModAVD 截图的工具": "Cannot tell which program it is; most likely a tool such as MAA that takes screenshots through ModAVD", "没设": "not set", "清理 %s 的空间,或把 ModAVD 根目录放到空间更大的盘": "Free up space on %s, or put the ModAVD root folder on a drive with more space", + "清理上次导入留下的临时目录失败:%v": "Could not remove the temporary folders a previous import left behind: %v", "清理导入临时目录失败:%v": "Could not clean up the import folder: %v", "清理新建取消标记失败": "Failed to clear the create-cancel marker", "游戏开着,等它退出后再写": "The game is open; wait for it to exit, then write", "游戏开着,等它退出后再挂": "The game is open; wait for it to exit, then mount", "源实例端口 %d 与 ModAVD 冲突": "Source port %d conflicts with ModAVD", "源文件大小在导入期间发生变化,请退出游戏后重试": "Source file sizes changed during import. Exit the game and retry", + "源模拟器上的 %s 正在运行,请先退出游戏再导入": "%s is running on the source emulator. Quit the game, then import again.", "版本未知": "version unknown", "独立显卡": "discrete GPU", "现在连不上这个代理,名单里的应用会断网:%v": "Cannot connect to this proxy right now; apps on the list will lose network: %v", @@ -711,6 +713,7 @@ "用完整的新包覆盖解压一次": "Extract the complete new package over it once", "目录路径": "Folder path", "目标 %s 空间不足,需要 %d MiB": "%s has insufficient space. The transfer needs %d MiB", + "目标实例上的 %s 正在运行,请先退出游戏再导入": "%s is running on the target instance. Quit the game, then import again.", "目标实例未就绪或设备编号不符": "The target is not ready or its device name does not match", "目标已有不同内容,请另选实例或资源:%v": "The target contains a different file. Choose another instance or resource: %v", "目标已有不同的 %s 安装包,请选另一台实例": "The target already has a different build of %s. Choose another instance", diff --git a/internal/i18n/locales/en/gamesource.json b/internal/i18n/locales/en/gamesource.json index 77d1529..329a8db 100644 --- a/internal/i18n/locales/en/gamesource.json +++ b/internal/i18n/locales/en/gamesource.json @@ -1,5 +1,6 @@ { "%s 命令超时": "The %s command timed out", + "MuMu info:输出里没有可读的实例信息:%s": "MuMu info: no readable instance information in the output: %s", "MuMu 实例 %d 启动失败:%s": "Could not start MuMu instance %d: %s", "从模拟器导入游戏需要 Windows": "Importing games from an emulator requires Windows", "已取消": "Canceled", diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md index 3d2a8e0..7e1699e 100644 --- a/internal/ui/API.en.md +++ b/internal/ui/API.en.md @@ -48,7 +48,7 @@ HTTP 4xx / 5xx with the body `{"error":{"code":"…","message":"…","advice":" | DELETE | `/api/instances/{i}?confirm=1` | without `confirm=1` the server returns 400 `usage` | `DeleteResult` | | POST | `/api/instances/{i}/start` | `{}` | 202 `Job`: always boots with a window (the manager never boots headless; headless boot is command line only). If the instance is already running headless, the job fails with code `busy` (no switching while running) | | POST | `/api/instances/{i}/stop` | `{force?: bool, cancel_create?: bool}` | 202 `Job`; while the instance is being created this returns busy by default, and only an explicit `cancel_create: true` cancels; `force` only controls whether Android's normal shutdown is skipped. A canceled creation is marked `interrupted_create: true` in the result | -| GET | `/api/game-sources` | | Local MuMu and LDPlayer instances with kind, index, name and running state | +| GET | `/api/game-sources` | | Local MuMu and LDPlayer instances with kind, index, name and running state. A player that cannot be read adds one row with `index` -1 and an `error` message; the others are still listed | | POST | `/api/game-sources/browse` | `player` (`mumu` or `ldplayer`), `source` index, optional `package` and `path` | Starts the selected player if needed. Returns third-party package names, or the immediate children (`name`, `directory`) of a public game directory. | | POST | `/api/instances/{i}/import-game` | `player`, `source`, `games` (each with `package` and an optional array of relative resource paths in `data`) | 202 `Job` on a running target. Per-game results contain `package`, `apk_bytes` and `resource_bytes`. | | POST | `/api/instances/{i}/install` | `multipart/form-data`, file field `apk` | 202 `Job` (the server stores the file in a temporary file and deletes it when the job ends) | diff --git a/internal/ui/API.md b/internal/ui/API.md index 14e5929..e019e11 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -48,7 +48,7 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"," | DELETE | `/api/instances/{i}?confirm=1` | 不带 `confirm=1` 回 400 `usage` | `DeleteResult` | | POST | `/api/instances/{i}/start` | `{}` | 202 `Job`:一律带窗口开机(管理器不开无头的,无头开机只走命令行);实例要先装执行桥时,装桥这几次准备用的开机都无头,装好后正常关机,最后一次带窗口开机(同 `modavd start --window`);实例已经以无头方式在运行时,任务失败,code 是 `busy`(运行中不切换) | | POST | `/api/instances/{i}/stop` | `{force?: bool, cancel_create?: bool}` | 202 `Job`;新建中默认 busy,显式 `cancel_create: true` 才取消;`force` 只管是否跳过 Android 正常关机。被取消的新建在结果里标记 `interrupted_create: true` | -| GET | `/api/game-sources` | | 本机 MuMu 和雷电实例的类型 `kind`、编号、名称和运行状态 | +| GET | `/api/game-sources` | | 本机 MuMu 和雷电实例的类型 `kind`、编号、名称和运行状态;某个模拟器读不出来时,只多一行 `index` 为 -1、带 `error` 说明的记录,其余照常列出 | | POST | `/api/game-sources/browse` | `player`(`mumu` 或 `ldplayer`)、源编号 `source`,可选 `package`、`path` | 按需启动源实例。返回第三方包名,指定包名时返回公开数据目录下一级的 `name`、`directory`。 | | POST | `/api/instances/{i}/import-game` | `player`、`source`、`games`(每项含 `package` 和可选的相对资源路径数组 `data`) | 202 `Job`,目标为开机的实例。结果按游戏列出 `package`、`apk_bytes`、`resource_bytes`。 | | POST | `/api/instances/{i}/install` | `multipart/form-data`,文件字段 `apk` | 202 `Job`(服务端存到临时文件,任务结束删掉) | diff --git a/internal/ui/web/js/game-import.js b/internal/ui/web/js/game-import.js index 9825395..7d8c214 100644 --- a/internal/ui/web/js/game-import.js +++ b/internal/ui/web/js/game-import.js @@ -43,7 +43,7 @@ export async function openGameImport(i) { try { players = await api.get('/api/game-sources'); } catch (e) { toastError(e); return; } const source = h('select', { 'aria-label': t('源模拟器实例') }, h('option', { value: '', text: t('选择源模拟器实例') }), - players.map((p, i) => h('option', { value: String(i), disabled: !!p.error_code, text: (p.kind === 'mumu' ? 'MuMu' : t('雷电')) + ' ' + p.index + ' · ' + p.name }))); + players.map((p, i) => h('option', { value: String(i), disabled: !!p.error_code, text: p.index < 0 ? (p.kind === 'mumu' ? 'MuMu' : t('雷电')) + ' · ' + p.error : (p.kind === 'mumu' ? 'MuMu' : t('雷电')) + ' ' + p.index + ' · ' + p.name }))); const list = h('div'); const error = h('div', { class: 'form-error', hidden: true }); const ok = h('button', { class: 'btn btn-primary', type: 'submit', disabled: true, text: t('导入') });