Skip to content

Commit bed8bc9

Browse files
committed
feat(desktop): add native server port editor
1 parent 126bddd commit bed8bc9

13 files changed

Lines changed: 512 additions & 17 deletions

File tree

‎desktop/README.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,12 @@ macOS 12+ and Windows 10/11 (x64 / arm64).
2828

2929
1. Starts the existing server (reusing the boot order of `cmd/server`: config → settings
3030
→ logger → i18n → db → signing → secrets → tasks → device manager) on
31-
`127.0.0.1:<random free port>`;
31+
`127.0.0.1:5533` by default;
3232
2. Keeps an icon in the menu bar / notification area, with a menu holding "Open in
33-
Browser", "Open Log File" and "Quit" (localized in the UI language);
33+
Browser", "Open Log File", a MyGo-native "Change Server Port" window and "Quit" (localized in the UI language);
3434
3. Opens `http://127.0.0.1:<port>/` in the default browser once started, and shuts
35-
down gracefully on quit.
35+
down gracefully on quit. The port is stored in `server.port` in the app data
36+
directory's `config.yaml`; restart the app for changes to take effect.
3637

3738
There is no main window: the app stays out of the Dock on macOS (`LSUIElement`) and
3839
shows no taskbar button on Windows. It does not use `mygo.Bind` typed IPC — the
@@ -48,6 +49,7 @@ desktop/
4849
└── app/
4950
├── go.mod # separate module (mygo needs Go 1.27+, see decision #2)
5051
├── main.go # shell entry: starts the server, tray icon, single instance, opens the browser
52+
├── port.go # initializes and validates config.yaml server.port (default 5533)
5153
├── locales.go # embeds the server catalogs (copied from the root locales/ at build time)
5254
├── plumesign.go # resolves the plumesign resource path (PathResources first, PATH fallback)
5355
├── mygo.config.ts # mygo CLI config (LSUIElement, macOS signing, resources)
@@ -68,7 +70,7 @@ desktop/
6870
|---|----------|-----------|
6971
| 1 | **Shell + embedded server, not a Bind IPC rewrite** | `internal/*` (install manager, device manager, WS login/pair/progress) is reused whole, the frontend needs no changes, and the risk stays low |
7072
| 2 | **A separate `desktop/app/go.mod`** | The root module is go 1.25 and mygo needs Go 1.27+; isolating it keeps the main service build and CI untouched, while server code is reused by importing the root packages (see "How the server is reused") |
71-
| 3 | **Random port + 127.0.0.1 loopback** | Never collides with a port the user already uses; the desktop build serves nothing to the network |
73+
| 3 | **Port 5533 + 127.0.0.1 loopback** | Predictable local URL; users can set `server.port` through the MyGo-native tray window; the desktop build serves nothing to the network |
7274
| 4 | **plumesign packed into resources** | mygo's platform resources mechanism packages it per platform, and `mygo build` signs the executables along with the app, which is what lets macOS Gatekeeper / Windows SmartScreen through |
7375
| 5 | **Config and data in the user directory** | A desktop app has no container `/data`; defaults to `~/Library/Application Support/atvloadly` (macOS) / `%APPDATA%\atvloadly` (Windows), with `server.work_dir` injected at startup |
7476

@@ -89,7 +91,7 @@ Two approaches:
8991
`desktop/app` call it, so the shell's footprint is one refactor plus one new package.
9092
- The tricky part: `web.Run` used to call `fiber.Listen(addr:port)` itself. It now has
9193
an entry point that takes a `net.Listener` (fiber supports `app.Listener(ln)`), so
92-
the shell can bind a random port.
94+
the shell can bind the configured loopback port.
9395
- **Option B (fallback): copy the boot sequence.** Write a slim bootstrap inside the
9496
desktop module. It duplicates code and the two boot paths drift apart; only fall back
9597
to it if Option A hits a cross-module compile problem.

‎desktop/app/go.mod‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.27.1
55
require (
66
github.com/bitxeno/atvloadly v0.0.0
77
github.com/egoist/mygo v0.6.3
8+
gopkg.in/yaml.v3 v3.0.1
89
)
910

1011
require (
@@ -28,6 +29,7 @@ require (
2829
github.com/go-redis/redis/v8 v8.11.6-0.20220405070650-99c79f7041fc // indirect
2930
github.com/go-resty/resty/v2 v2.6.0 // indirect
3031
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible // indirect
32+
github.com/go-text/typesetting v0.3.5 // indirect
3133
github.com/godbus/dbus/v5 v5.0.4 // indirect
3234
github.com/gofiber/contrib/websocket v1.0.0 // indirect
3335
github.com/gofiber/fiber/v2 v2.52.5 // indirect
@@ -77,7 +79,6 @@ require (
7779
golang.org/x/text v0.43.0 // indirect
7880
golang.org/x/tools v0.51.0 // indirect
7981
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
80-
gopkg.in/yaml.v3 v3.0.1 // indirect
8182
gorm.io/gorm v1.25.7 // indirect
8283
howett.net/plist v1.0.1 // indirect
8384
modernc.org/libc v1.22.5 // indirect

‎desktop/app/go.sum‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf
156156
github.com/go-test/deep v1.0.2-0.20181118220953-042da051cf31/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
157157
github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
158158
github.com/go-text/typesetting v0.3.5/go.mod h1:XZO1hD+nQVyvVa5IicQk7FsCa4PFQaJ2soWAP1f//68=
159+
github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc h1:8FGo2It5K75XkavhTiCKExUfVaVDS1feBnLCru5qeoY=
160+
github.com/go-text/typesetting-utils v0.0.0-20260419141703-4ffe8874dabc/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
159161
github.com/godbus/dbus/v5 v5.0.4 h1:9349emZab16e7zQvpmsbtjc18ykshndd8y2PG3sgJbA=
160162
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
161163
github.com/gofiber/contrib/websocket v1.0.0 h1:y9bbY5/KOvR84SrwPm/3+Q8/M4rxoJlz/eGQaezVrTk=

‎desktop/app/main.go‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,14 @@ func run() error {
5656
initI18n()
5757

5858
// The service shares the desktop app's identity: data lives in the app's
59-
// user data directory instead of ~/.config/<binary name>.
60-
app.SetAppDataDir(dataDir())
59+
// user data directory instead of ~/.config/<binary name>. Its existing
60+
// config.yaml stores server.port alongside the other server settings.
61+
appDataDir := dataDir()
62+
app.SetAppDataDir(appDataDir)
63+
configPath := desktopConfigPath(appDataDir)
64+
if err := ensureDesktopConfig(configPath); err != nil {
65+
return err
66+
}
6167

6268
// Plumesign ships inside the app bundle; make it the plumesign the
6369
// managers exec.
@@ -67,7 +73,7 @@ func run() error {
6773
_ = os.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
6874
}
6975

70-
url, stop, err := startService()
76+
url, stop, err := startService(configPath)
7177
if err != nil {
7278
return err
7379
}
@@ -105,23 +111,26 @@ func run() error {
105111
Icon: trayIcon(),
106112
IconIsTemplate: runtime.GOOS == "darwin",
107113
ToolTip: appName,
108-
Menu: trayMenu(url, logPath),
114+
Menu: trayMenu(url, logPath, configPath),
109115
})
110116
if err != nil {
111117
fatal(fmt.Errorf("no menu bar icon: %w", err))
112118
}
113119
// The web UI saves the language it shows; relabel the menu as it
114120
// changes.
115121
i18n.OnLanguageChanged(func(string) {
116-
tray.SetMenu(trayMenu(url, logPath))
122+
tray.SetMenu(trayMenu(url, logPath, configPath))
117123
})
118124
if runtime.GOOS == "windows" {
119125
// The notification area opens TrayOptions.Menu on right-click;
120126
// the taskbar icon's primary click opens it too, as people
121127
// click a taskbar icon.
122128
tray.OnClick(func() { tray.PopUpMenu() })
123129
}
124-
mygo.App.OnWillQuit(func(*mygo.QuitEvent) { tray.Destroy() })
130+
mygo.App.OnWillQuit(func(*mygo.QuitEvent) {
131+
closePortDialog()
132+
tray.Destroy()
133+
})
125134

126135
// The service is up: the launch lands in the browser.
127136
openBrowser(url)
@@ -130,10 +139,11 @@ func run() error {
130139
}
131140

132141
// trayMenu builds the menu bar menu in the language the app shows.
133-
func trayMenu(url, logPath string) *mygo.Menu {
142+
func trayMenu(url, logPath, configPath string) *mygo.Menu {
134143
return mygo.NewMenu([]*mygo.MenuItem{
135144
{Label: i18n.Localize("tray.open_browser"), Click: func(*mygo.MenuItem, *mygo.Window) { openBrowser(url) }},
136145
{Label: i18n.Localize("tray.open_log"), Click: func(*mygo.MenuItem, *mygo.Window) { openLogFile(logPath) }},
146+
{Label: i18n.Localize("tray.server_port"), Click: func(*mygo.MenuItem, *mygo.Window) { openPortDialog(configPath) }},
137147
mygo.Separator(),
138148
{Role: mygo.RoleQuit, Label: i18n.Localize("tray.quit")},
139149
})
@@ -156,10 +166,10 @@ func openLogFile(path string) {
156166
}
157167
}
158168

159-
// startService starts the atvloadly service on a random loopback port and
169+
// startService starts the atvloadly service on the given loopback port and
160170
// returns its URL. stop releases the port and stops the background jobs.
161-
func startService() (url string, stop func(), err error) {
162-
addr, stop, err := bootstrap.Run(bootstrap.Options{Port: -1})
171+
func startService(configPath string) (url string, stop func(), err error) {
172+
addr, stop, err := bootstrap.Run(bootstrap.Options{ConfigFile: configPath, ListenAddr: "127.0.0.1"})
163173
if err != nil {
164174
return "", nil, err
165175
}

‎desktop/app/port.go‎

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"os"
7+
"path/filepath"
8+
"strconv"
9+
"strings"
10+
11+
"gopkg.in/yaml.v3"
12+
)
13+
14+
const defaultServerPort = 5533
15+
16+
var errInvalidServerPort = errors.New("server port must be between 1 and 65535")
17+
18+
func validateServerPort(port int) error {
19+
if port < 1 || port > 65535 {
20+
return fmt.Errorf("%w: %d", errInvalidServerPort, port)
21+
}
22+
return nil
23+
}
24+
25+
// desktopConfigPath returns the service config file in the app data directory.
26+
func desktopConfigPath(dataDir string) string {
27+
return filepath.Join(dataDir, "config.yaml")
28+
}
29+
30+
// ensureDesktopConfig creates the config with the desktop default port, or
31+
// adds server.port when an existing config does not specify it. Existing
32+
// settings and YAML comments are retained through the YAML node representation.
33+
func ensureDesktopConfig(path string) error {
34+
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
35+
return fmt.Errorf("create config directory: %w", err)
36+
}
37+
38+
data, err := os.ReadFile(path)
39+
if errors.Is(err, os.ErrNotExist) {
40+
data = []byte("server:\n port: " + strconv.Itoa(defaultServerPort) + "\n")
41+
if err := os.WriteFile(path, data, 0o600); err != nil {
42+
return fmt.Errorf("write default config: %w", err)
43+
}
44+
return nil
45+
}
46+
if err != nil {
47+
return fmt.Errorf("read config: %w", err)
48+
}
49+
50+
var document yaml.Node
51+
if err := yaml.Unmarshal(data, &document); err != nil {
52+
return fmt.Errorf("parse config %s: %w", path, err)
53+
}
54+
if len(document.Content) == 0 {
55+
document.Content = []*yaml.Node{{Kind: yaml.MappingNode, Tag: "!!map"}}
56+
}
57+
root := document.Content[0]
58+
if root.Kind != yaml.MappingNode {
59+
return fmt.Errorf("invalid config %s: top level must be a mapping", path)
60+
}
61+
62+
server := mappingValue(root, "server")
63+
if server == nil {
64+
server = &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
65+
appendMappingPair(root, "server", server)
66+
}
67+
if server.Kind != yaml.MappingNode {
68+
return fmt.Errorf("invalid config %s: server must be a mapping", path)
69+
}
70+
71+
port := mappingValue(server, "port")
72+
if port != nil {
73+
if port.Kind != yaml.ScalarNode || port.Tag != "!!int" {
74+
return fmt.Errorf("invalid server.port in %s: must be an integer", path)
75+
}
76+
value, err := strconv.Atoi(strings.TrimSpace(port.Value))
77+
if err != nil {
78+
return fmt.Errorf("invalid server.port in %s: %w", path, err)
79+
}
80+
if err := validateServerPort(value); err != nil {
81+
return fmt.Errorf("invalid server.port in %s: %w", path, err)
82+
}
83+
return nil
84+
}
85+
86+
appendMappingPair(server, "port", &yaml.Node{
87+
Kind: yaml.ScalarNode,
88+
Tag: "!!int",
89+
Value: strconv.Itoa(defaultServerPort),
90+
})
91+
updated, err := yaml.Marshal(&document)
92+
if err != nil {
93+
return fmt.Errorf("encode config %s: %w", path, err)
94+
}
95+
if err := os.WriteFile(path, updated, 0o600); err != nil {
96+
return fmt.Errorf("save config %s: %w", path, err)
97+
}
98+
return nil
99+
}
100+
101+
// setServerPort writes a validated port into the existing server.port field,
102+
// preserving other YAML configuration and comments.
103+
func setServerPort(path string, port int) error {
104+
if err := validateServerPort(port); err != nil {
105+
return err
106+
}
107+
108+
if err := ensureDesktopConfig(path); err != nil {
109+
return err
110+
}
111+
data, err := os.ReadFile(path)
112+
if err != nil {
113+
return fmt.Errorf("read config: %w", err)
114+
}
115+
116+
var document yaml.Node
117+
if err := yaml.Unmarshal(data, &document); err != nil {
118+
return fmt.Errorf("parse config %s: %w", path, err)
119+
}
120+
if len(document.Content) == 0 || document.Content[0].Kind != yaml.MappingNode {
121+
return fmt.Errorf("invalid config %s: top level must be a mapping", path)
122+
}
123+
server := mappingValue(document.Content[0], "server")
124+
if server == nil || server.Kind != yaml.MappingNode {
125+
return fmt.Errorf("invalid config %s: server must be a mapping", path)
126+
}
127+
portNode := mappingValue(server, "port")
128+
if portNode == nil {
129+
appendMappingPair(server, "port", &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: strconv.Itoa(port)})
130+
} else {
131+
portNode.Kind = yaml.ScalarNode
132+
portNode.Tag = "!!int"
133+
portNode.Value = strconv.Itoa(port)
134+
portNode.Style = 0
135+
}
136+
137+
updated, err := yaml.Marshal(&document)
138+
if err != nil {
139+
return fmt.Errorf("encode config %s: %w", path, err)
140+
}
141+
if err := os.WriteFile(path, updated, 0o600); err != nil {
142+
return fmt.Errorf("save config %s: %w", path, err)
143+
}
144+
return nil
145+
}
146+
147+
func mappingValue(mapping *yaml.Node, key string) *yaml.Node {
148+
for i := 0; i+1 < len(mapping.Content); i += 2 {
149+
if mapping.Content[i].Value == key {
150+
return mapping.Content[i+1]
151+
}
152+
}
153+
return nil
154+
}
155+
156+
func appendMappingPair(mapping *yaml.Node, key string, value *yaml.Node) {
157+
mapping.Content = append(mapping.Content,
158+
&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key},
159+
value,
160+
)
161+
}

0 commit comments

Comments
 (0)
⌂ 换网址