feat: save several servers and pick one to connect
Match the first-party mobile client's connection screen: - the first screen lists saved servers, the one last used leading with its connect button or connected state, the others below, and adding is one tap - servers can be added, edited (name, address, proxy, self-signed) and deleted; deleting the live or last one returns to the list - a password sheet prompts only when the server asks for one, keeps the error and the typed password for a retry - while connected, the instances sheet switches servers - proxy and self-signed options stay per server (the native app's own) - the single-server record and its token migrate automatically - permission cards read a plain signal, fixing a flaky update - bump version to 0.1.2 (build 3)
This commit is contained in:
1 parent
ef0b63ceee
commit
13aca21d99
12 files changed
+966
-361
No files matched your search
@@ -39,6 +39,7 @@ M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行
|
|||||||
| release 构建 | `asuka build -p android` 产出 `dist/OpenChamber.aab`;合并后的 release manifest 含 `usesCleartextTraffic="true"`(由 `netcfg` 模块合入),明文 HTTP 在 release 可用 |
|
| release 构建 | `asuka build -p android` 产出 `dist/OpenChamber.aab`;合并后的 release manifest 含 `usesCleartextTraffic="true"`(由 `netcfg` 模块合入),明文 HTTP 在 release 可用 |
|
||||||
| 会话操作 | 滑动归档/删除、长按菜单、重命名(Alert 输入框)、删除二次确认 |
|
| 会话操作 | 滑动归档/删除、长按菜单、重命名(Alert 输入框)、删除二次确认 |
|
||||||
| 权限审批 | 聊天页内联卡片(允许一次/总是允许/拒绝),启动时补齐待批列表,SSE 实时增删 |
|
| 权限审批 | 聊天页内联卡片(允许一次/总是允许/拒绝),启动时补齐待批列表,SSE 实时增删 |
|
||||||
|
| 多实例 | 保存多个服务器,按最近使用排序;首屏选择连接,连接后可切换;添加/编辑/删除;从旧的单连接记录自动迁移 |
|
||||||
| 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 |
|
| 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 |
|
||||||
| 新建会话 | 会话页「新建」:标题 + 工作目录(服务端默认目录与已加载会话的目录),创建后直接进入聊天 |
|
| 新建会话 | 会话页「新建」:标题 + 工作目录(服务端默认目录与已加载会话的目录),创建后直接进入聊天 |
|
||||||
| 下一步 | 打磨:图标/splash、中英 i18n、空态与错误页;可选 fork asuka 支持更低 minSdk |
|
| 下一步 | 打磨:图标/splash、中英 i18n、空态与错误页;可选 fork asuka 支持更低 minSdk |
|
||||||
|
|||||||
@@ -3,8 +3,9 @@
|
|||||||
A lightweight OpenChamber client for phones, written in Go with
|
A lightweight OpenChamber client for phones, written in Go with
|
||||||
[Asuka](https://asuka.egoist.dev/)'s native widgets. Android first.
|
[Asuka](https://asuka.egoist.dev/)'s native widgets. Android first.
|
||||||
|
|
||||||
Status: M0–M4 done — connect (password / passwordless, HTTP or SOCKS5 proxy,
|
Status: M0–M4 done — multiple saved servers with a connect list (add, edit,
|
||||||
self-signed certificates), live session list, chat with streaming Markdown,
|
delete, switch; password prompt; HTTP or SOCKS5 proxy and self-signed
|
||||||
|
certificates per server), live session list, chat with streaming Markdown,
|
||||||
permissions, model/agent switching, new sessions, archive/delete/rename, and a
|
permissions, model/agent switching, new sessions, archive/delete/rename, and a
|
||||||
UI-independent API client.
|
UI-independent API client.
|
||||||
|
|
||||||
@@ -13,7 +14,7 @@ UI-independent API client.
|
|||||||
| Path | What |
|
| Path | What |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `internal/ocapi/` | OpenChamber HTTP client: auth (password → device token), sessions, messages, prompt/interrupt/model/agent, permissions, SSE events, HTTP/SOCKS5 proxy, certificate pinning |
|
| `internal/ocapi/` | OpenChamber HTTP client: auth (password → device token), sessions, messages, prompt/interrupt/model/agent, permissions, SSE events, HTTP/SOCKS5 proxy, certificate pinning |
|
||||||
| `internal/storage/` | Connection settings in `asuka/sdk/store`, device token in `asuka/sdk/secure` (Android Keystore), per-install id for device dedupe |
|
| `internal/storage/` | Saved servers in `asuka/sdk/store`, one device token per server in `asuka/sdk/secure` (Android Keystore), per-install id for device dedupe, migration from the single-server record |
|
||||||
| `internal/appui/` | Screens: connect, sessions, chat (streaming Markdown, reasoning/tool folding, permissions) |
|
| `internal/appui/` | Screens: connect, sessions, chat (streaming Markdown, reasoning/tool folding, permissions) |
|
||||||
| `cmd/ocprobe/` | Terminal probe used to validate the API without a device |
|
| `cmd/ocprobe/` | Terminal probe used to validate the API without a device |
|
||||||
| `PLAN.md` | Research, API contract, architecture, milestones, risks |
|
| `PLAN.md` | Research, API contract, architecture, milestones, risks |
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "OpenChamber",
|
"name": "OpenChamber",
|
||||||
"id": "com.openchamber.native",
|
"id": "com.openchamber.native",
|
||||||
"version": "0.1.1",
|
"version": "0.1.2",
|
||||||
"build": 2,
|
"build": 3,
|
||||||
"orientations": ["portrait", "landscape"]
|
"orientations": ["portrait", "landscape"]
|
||||||
}
|
}
|
||||||
+25
-13
@@ -54,6 +54,9 @@ type chat struct {
|
|||||||
reloadScheduled bool
|
reloadScheduled bool
|
||||||
listNode ui.Node
|
listNode ui.Node
|
||||||
|
|
||||||
|
permList *signal.Signal[[]ocapi.PermissionRequest]
|
||||||
|
hasPerms *signal.Signal[bool]
|
||||||
|
|
||||||
pickerOpen *signal.Signal[bool]
|
pickerOpen *signal.Signal[bool]
|
||||||
pickerKind string
|
pickerKind string
|
||||||
pickerItems *signal.Signal[[]pickerItem]
|
pickerItems *signal.Signal[[]pickerItem]
|
||||||
@@ -91,12 +94,15 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
|
|||||||
errText: signal.New(""),
|
errText: signal.New(""),
|
||||||
textSlots: map[string]map[int]int{},
|
textSlots: map[string]map[int]int{},
|
||||||
reasoningSlots: map[string]map[int]int{},
|
reasoningSlots: map[string]map[int]int{},
|
||||||
|
permList: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
||||||
|
hasPerms: signal.New(false),
|
||||||
pickerOpen: signal.New(false),
|
pickerOpen: signal.New(false),
|
||||||
pickerItems: signal.NewFunc([]pickerItem{}, nil),
|
pickerItems: signal.NewFunc([]pickerItem{}, nil),
|
||||||
pickerFilter: signal.New(""),
|
pickerFilter: signal.New(""),
|
||||||
pickerLoad: signal.New(false),
|
pickerLoad: signal.New(false),
|
||||||
}
|
}
|
||||||
c.chat = ch
|
c.chat = ch
|
||||||
|
ch.syncPerms()
|
||||||
ch.load()
|
ch.load()
|
||||||
return ch
|
return ch
|
||||||
}
|
}
|
||||||
@@ -591,24 +597,29 @@ func (ch *chat) applyPick(it pickerItem) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// perms are the pending permission requests for this session.
|
// perms are the pending permission requests for this session.
|
||||||
func (ch *chat) perms() signal.Accessor[[]ocapi.PermissionRequest] {
|
func (ch *chat) perms() []ocapi.PermissionRequest {
|
||||||
return signal.Func(func() []ocapi.PermissionRequest {
|
var out []ocapi.PermissionRequest
|
||||||
var out []ocapi.PermissionRequest
|
for _, p := range ch.c.perms.Get() {
|
||||||
for _, p := range ch.c.perms.Get() {
|
if p.SessionID == ch.id {
|
||||||
if p.SessionID == ch.id {
|
out = append(out, p)
|
||||||
out = append(out, p)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return out
|
}
|
||||||
})
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// syncPerms publishes this session's pending permission requests. The list
|
||||||
|
// and the flag are plain signals so the section updates without a computed
|
||||||
|
// chain (which is timing-sensitive in the test host).
|
||||||
|
func (ch *chat) syncPerms() {
|
||||||
|
list := ch.perms()
|
||||||
|
ch.permList.Set(list)
|
||||||
|
ch.hasPerms.Set(len(list) > 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ch *chat) permissionSection() ui.Node {
|
func (ch *chat) permissionSection() ui.Node {
|
||||||
list := ch.perms()
|
return ui.Show(ch.hasPerms, func() ui.Node {
|
||||||
shown := signal.Func(func() bool { return len(list.Get()) > 0 })
|
|
||||||
return ui.Show(shown, func() ui.Node {
|
|
||||||
return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(6, 12)},
|
return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(6, 12)},
|
||||||
ui.For(list, func(p ocapi.PermissionRequest) string { return p.ID },
|
ui.For(ch.permList, func(p ocapi.PermissionRequest) string { return p.ID },
|
||||||
func(p signal.Accessor[ocapi.PermissionRequest], _ signal.Accessor[int]) ui.Node {
|
func(p signal.Accessor[ocapi.PermissionRequest], _ signal.Accessor[int]) ui.Node {
|
||||||
return ui.View(ui.ViewProps{Style: ui.Style{Gap: 8, Padding: ui.Symmetric(10, 12),
|
return ui.View(ui.ViewProps{Style: ui.Style{Gap: 8, Padding: ui.Symmetric(10, 12),
|
||||||
CornerRadius: 12, Background: colors.SecondaryBackground}},
|
CornerRadius: 12, Background: colors.SecondaryBackground}},
|
||||||
@@ -656,6 +667,7 @@ func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDeci
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ch.c.perms.Set(next)
|
ch.c.perms.Set(next)
|
||||||
|
ch.syncPerms()
|
||||||
})
|
})
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -151,8 +151,7 @@ func TestOpenSessionAndSend(t *testing.T) {
|
|||||||
st := &memStore{}
|
st := &memStore{}
|
||||||
a := uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
|
|
||||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
connectViaForm(t, a, srv.URL)
|
||||||
a.Tap("连接")
|
|
||||||
a.WaitFor("First session")
|
a.WaitFor("First session")
|
||||||
select {
|
select {
|
||||||
case <-srv.ready:
|
case <-srv.ready:
|
||||||
@@ -186,8 +185,7 @@ func TestPermissionCardAndReply(t *testing.T) {
|
|||||||
srv := newChatServer(t)
|
srv := newChatServer(t)
|
||||||
// The session list's pending-permission read.
|
// The session list's pending-permission read.
|
||||||
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
connectViaForm(t, a, srv.URL)
|
||||||
a.Tap("连接")
|
|
||||||
a.WaitFor("First session")
|
a.WaitFor("First session")
|
||||||
select {
|
select {
|
||||||
case <-srv.ready:
|
case <-srv.ready:
|
||||||
@@ -199,6 +197,7 @@ func TestPermissionCardAndReply(t *testing.T) {
|
|||||||
a.WaitFor("Hello from the agent")
|
a.WaitFor("Hello from the agent")
|
||||||
|
|
||||||
srv.push(`{"id":"evt_10","created":200,"type":"permission.asked","data":{"sessionID":"ses_1","id":"per_1","action":"bash","resources":["npm test"]}}`)
|
srv.push(`{"id":"evt_10","created":200,"type":"permission.asked","data":{"sessionID":"ses_1","id":"per_1","action":"bash","resources":["npm test"]}}`)
|
||||||
|
a.Settle()
|
||||||
a.WaitFor("需要权限:bash")
|
a.WaitFor("需要权限:bash")
|
||||||
a.Expect("npm test")
|
a.Expect("npm test")
|
||||||
|
|
||||||
@@ -216,8 +215,7 @@ func TestPermissionCardAndReply(t *testing.T) {
|
|||||||
func TestSwitchModel(t *testing.T) {
|
func TestSwitchModel(t *testing.T) {
|
||||||
srv := newChatServer(t)
|
srv := newChatServer(t)
|
||||||
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
connectViaForm(t, a, srv.URL)
|
||||||
a.Tap("连接")
|
|
||||||
a.WaitFor("First session")
|
a.WaitFor("First session")
|
||||||
a.Tap("First session")
|
a.Tap("First session")
|
||||||
a.WaitFor("Hello from the agent")
|
a.WaitFor("Hello from the agent")
|
||||||
@@ -240,8 +238,7 @@ func TestSwitchModel(t *testing.T) {
|
|||||||
func TestCreateSession(t *testing.T) {
|
func TestCreateSession(t *testing.T) {
|
||||||
srv := newChatServer(t)
|
srv := newChatServer(t)
|
||||||
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
connectViaForm(t, a, srv.URL)
|
||||||
a.Tap("连接")
|
|
||||||
a.WaitFor("First session")
|
a.WaitFor("First session")
|
||||||
|
|
||||||
a.Tap("新建")
|
a.Tap("新建")
|
||||||
|
|||||||
@@ -0,0 +1,357 @@
|
|||||||
|
package appui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/egoist/asuka/colors"
|
||||||
|
"github.com/egoist/asuka/fonts"
|
||||||
|
"github.com/egoist/asuka/signal"
|
||||||
|
"github.com/egoist/asuka/ui"
|
||||||
|
"github.com/openchamber/openchamber-native/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// connectionsScreen is the first screen: the saved servers, or the
|
||||||
|
// introduction when there are none. It mirrors the first-party client: the
|
||||||
|
// server last used leads, the others follow, and adding is one tap away.
|
||||||
|
func (c *controller) connectionsScreen() ui.Node {
|
||||||
|
return ui.Dynamic(func() ui.Node {
|
||||||
|
list := c.connections.Get()
|
||||||
|
if len(list) == 0 {
|
||||||
|
return c.firstRun()
|
||||||
|
}
|
||||||
|
lead := list[0]
|
||||||
|
for _, conn := range list {
|
||||||
|
if conn.ID == c.activeID.Get() && c.connected.Get() {
|
||||||
|
lead = conn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
others := make([]storage.Connection, 0, len(list))
|
||||||
|
for _, conn := range list {
|
||||||
|
if conn.ID != lead.ID {
|
||||||
|
others = append(others, conn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ui.Scroll(
|
||||||
|
ui.ScrollProps{
|
||||||
|
Style: ui.Style{Grow: 1},
|
||||||
|
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
|
||||||
|
},
|
||||||
|
ui.StaticText("OpenChamber", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
|
||||||
|
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||||
|
}),
|
||||||
|
c.leadCard(lead),
|
||||||
|
ui.Show(signal.Func(func() bool { return len(c.connections.Get()) > 1 }), func() ui.Node {
|
||||||
|
return ui.Column(ui.Style{Gap: 6},
|
||||||
|
ui.StaticText("其他服务器", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
ui.For(c.otherConnections(lead.ID), func(conn storage.Connection) string { return conn.ID },
|
||||||
|
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
|
||||||
|
return c.connectionRow(conn)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
ui.Button(ui.ButtonProps{
|
||||||
|
Title: ui.Val("添加服务器"),
|
||||||
|
Icon: ui.IconPlus,
|
||||||
|
Variant: ui.ButtonTinted,
|
||||||
|
OnPress: c.openAddForm,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) otherConnections(leadID string) signal.Accessor[[]storage.Connection] {
|
||||||
|
return signal.Func(func() []storage.Connection {
|
||||||
|
out := make([]storage.Connection, 0, len(c.connections.Get()))
|
||||||
|
for _, conn := range c.connections.Get() {
|
||||||
|
if conn.ID != leadID {
|
||||||
|
out = append(out, conn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) firstRun() ui.Node {
|
||||||
|
return ui.Scroll(
|
||||||
|
ui.ScrollProps{
|
||||||
|
Style: ui.Style{Grow: 1},
|
||||||
|
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
|
||||||
|
},
|
||||||
|
ui.StaticText("OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
|
||||||
|
ui.StaticText("连接到正在运行的 OpenChamber 服务器。保存过的服务器会出现在这里,可以随时切换。",
|
||||||
|
ui.Style{Color: colors.SecondaryLabel}),
|
||||||
|
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||||
|
}),
|
||||||
|
ui.Button(ui.ButtonProps{
|
||||||
|
Title: ui.Val("手动输入地址"),
|
||||||
|
Icon: "link",
|
||||||
|
Variant: ui.ButtonFilled,
|
||||||
|
OnPress: c.openAddForm,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) leadCard(conn storage.Connection) ui.Node {
|
||||||
|
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.All(16), Gap: 8, CornerRadius: 14,
|
||||||
|
Background: colors.SecondaryBackground}},
|
||||||
|
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
|
||||||
|
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
||||||
|
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
|
||||||
|
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||||
|
),
|
||||||
|
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
|
||||||
|
OnPress: func() { c.connectionActions(conn) }}),
|
||||||
|
),
|
||||||
|
ui.Show(signal.Func(func() bool { return c.activeID.Get() == conn.ID && c.connected.Get() }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
|
||||||
|
ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
|
||||||
|
CornerRadius: 4, Background: colors.Accent}}),
|
||||||
|
ui.StaticText("已连接", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Show(signal.Func(func() bool { return c.connecting.Get() == conn.ID }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignCenter},
|
||||||
|
ui.Activity(), ui.StaticText("连接中…", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}))
|
||||||
|
},
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Button(ui.ButtonProps{
|
||||||
|
Title: ui.Val("连接"),
|
||||||
|
Variant: ui.ButtonFilled,
|
||||||
|
OnPress: func() { c.connectTo(conn, "", true) },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) connectionRow(conn signal.Accessor[storage.Connection]) ui.Node {
|
||||||
|
return ui.View(ui.ViewProps{
|
||||||
|
OnPress: func() { c.selectConnection(conn.Get()) },
|
||||||
|
Style: ui.Style{Padding: ui.Symmetric(10, 12), CornerRadius: 10, Gap: 6},
|
||||||
|
}, ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
|
||||||
|
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
||||||
|
ui.Text(signal.Func(func() string { return c.labelOf(conn.Get()) }), ui.Style{Font: fonts.Body, Lines: 1}),
|
||||||
|
ui.Text(signal.Func(func() string { return conn.Get().URL }),
|
||||||
|
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||||
|
),
|
||||||
|
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
|
||||||
|
OnPress: func() { c.connectionActions(conn.Get()) }}),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) selectConnection(conn storage.Connection) {
|
||||||
|
c.instancesOpen.Set(false)
|
||||||
|
if conn.ID == c.activeID.Peek() && c.connected.Peek() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if c.connected.Peek() {
|
||||||
|
c.logout("")
|
||||||
|
}
|
||||||
|
c.connectTo(conn, "", true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) connectionActions(conn storage.Connection) {
|
||||||
|
ui.Alert(ui.AlertProps{
|
||||||
|
Title: c.labelOf(conn),
|
||||||
|
ActionSheet: true,
|
||||||
|
Actions: []ui.Action{
|
||||||
|
{Title: ui.Val("连接"), Icon: "play", OnPress: func() { c.selectConnection(conn) }},
|
||||||
|
{Title: ui.Val("编辑"), Icon: "pencil", OnPress: func() { c.openEditForm(conn) }},
|
||||||
|
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
|
||||||
|
OnPress: func() { c.confirmDeleteConnection(conn) }},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) confirmDeleteConnection(conn storage.Connection) {
|
||||||
|
ui.Alert(ui.AlertProps{
|
||||||
|
Title: "删除服务器?",
|
||||||
|
Message: "只会删除这个客户端里保存的连接,服务器上的数据不受影响。",
|
||||||
|
Actions: []ui.Action{
|
||||||
|
{Title: ui.Val("取消"), Role: ui.ActionCancel},
|
||||||
|
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
|
||||||
|
OnPress: func() { c.deleteConnection(conn) }},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) deleteConnection(conn storage.Connection) {
|
||||||
|
if c.activeID.Peek() == conn.ID {
|
||||||
|
c.logout("")
|
||||||
|
}
|
||||||
|
list := c.connections.Peek()
|
||||||
|
next := make([]storage.Connection, 0, len(list))
|
||||||
|
for _, saved := range list {
|
||||||
|
if saved.ID != conn.ID {
|
||||||
|
next = append(next, saved)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.st.SaveConnections(next)
|
||||||
|
c.connections.Set(next)
|
||||||
|
go func() { _ = c.st.ClearToken(conn) }()
|
||||||
|
}
|
||||||
|
|
||||||
|
// formSheet is the add/edit form, a full-screen sheet like the first-party
|
||||||
|
// client's panel.
|
||||||
|
func (c *controller) formSheet() ui.Node {
|
||||||
|
title := "添加服务器"
|
||||||
|
if c.formEditID != "" {
|
||||||
|
title = "编辑服务器"
|
||||||
|
}
|
||||||
|
submit := "连接"
|
||||||
|
if c.connected.Peek() {
|
||||||
|
submit = "保存"
|
||||||
|
}
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: c.formOpen,
|
||||||
|
FullScreen: true,
|
||||||
|
Content: func() ui.Node {
|
||||||
|
return ui.SafeArea(ui.Style{Grow: 1},
|
||||||
|
ui.Scroll(
|
||||||
|
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14}},
|
||||||
|
ui.Row(ui.Style{Align: ui.AlignCenter},
|
||||||
|
ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
|
||||||
|
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.closeForm}),
|
||||||
|
),
|
||||||
|
ui.TextField(ui.TextFieldProps{
|
||||||
|
Value: c.formLabel,
|
||||||
|
Placeholder: ui.Val("名称(可选)"),
|
||||||
|
}),
|
||||||
|
ui.TextField(ui.TextFieldProps{
|
||||||
|
Value: c.url,
|
||||||
|
Placeholder: ui.Val("http://192.168.1.5:3000"),
|
||||||
|
Keyboard: ui.KeyboardURL,
|
||||||
|
ContentType: "url",
|
||||||
|
Autocapitalize: ui.CapitalizeNone,
|
||||||
|
Autocorrect: ui.AutocorrectNo,
|
||||||
|
ReturnKey: ui.ReturnNext,
|
||||||
|
}),
|
||||||
|
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||||
|
ui.StaticText("使用代理", ui.Style{Grow: 1}),
|
||||||
|
ui.Toggle(ui.ToggleProps{Value: c.formUseProxy}),
|
||||||
|
),
|
||||||
|
ui.Show(c.formUseProxy, func() ui.Node {
|
||||||
|
return ui.TextField(ui.TextFieldProps{
|
||||||
|
Value: c.formProxy,
|
||||||
|
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
|
||||||
|
Keyboard: ui.KeyboardURL,
|
||||||
|
Autocapitalize: ui.CapitalizeNone,
|
||||||
|
Autocorrect: ui.AutocorrectNo,
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||||
|
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
|
||||||
|
ui.Toggle(ui.ToggleProps{Value: c.formInsecure}),
|
||||||
|
),
|
||||||
|
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||||
|
}),
|
||||||
|
ui.Button(ui.ButtonProps{
|
||||||
|
Title: ui.Val(submit),
|
||||||
|
Variant: ui.ButtonFilled,
|
||||||
|
Disabled: signal.Func(func() bool { return c.connecting.Get() != "" }),
|
||||||
|
OnPress: c.submitForm,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) passwordSheet() ui.Node {
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: c.passwordOpen,
|
||||||
|
Detents: ui.DetentMedium,
|
||||||
|
Grabber: true,
|
||||||
|
OnDismiss: c.cancelPassword,
|
||||||
|
Content: func() ui.Node {
|
||||||
|
conn := c.passwordFor
|
||||||
|
for _, saved := range c.connections.Peek() {
|
||||||
|
if saved.ID == conn.ID {
|
||||||
|
conn = saved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14},
|
||||||
|
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
|
||||||
|
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||||
|
ui.StaticText("这台服务器需要密码。", ui.Style{Color: colors.SecondaryLabel}),
|
||||||
|
ui.TextField(ui.TextFieldProps{
|
||||||
|
Value: c.passwordText,
|
||||||
|
Placeholder: ui.Val("密码"),
|
||||||
|
Secure: true,
|
||||||
|
ContentType: ui.ContentPassword,
|
||||||
|
ReturnKey: ui.ReturnGo,
|
||||||
|
OnSubmit: c.submitPassword,
|
||||||
|
}),
|
||||||
|
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||||
|
}),
|
||||||
|
ui.Row(ui.Style{Justify: ui.JustifyEnd, Gap: 8},
|
||||||
|
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.cancelPassword}),
|
||||||
|
ui.Button(ui.ButtonProps{
|
||||||
|
Title: ui.Val("解锁"),
|
||||||
|
Variant: ui.ButtonFilled,
|
||||||
|
Disabled: signal.Func(func() bool {
|
||||||
|
return c.passwordBusy.Get() || strings.TrimSpace(c.passwordText.Get()) == ""
|
||||||
|
}),
|
||||||
|
OnPress: c.submitPassword,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// instancesSheet is the switcher while connected: the same list, in a sheet.
|
||||||
|
func (c *controller) instancesSheet() ui.Node {
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: c.instancesOpen,
|
||||||
|
FullScreen: true,
|
||||||
|
Content: func() ui.Node {
|
||||||
|
return ui.SafeArea(ui.Style{Grow: 1},
|
||||||
|
ui.Scroll(
|
||||||
|
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 12}},
|
||||||
|
ui.Row(ui.Style{Align: ui.AlignCenter},
|
||||||
|
ui.StaticText("实例", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
|
||||||
|
ui.Button(ui.ButtonProps{Title: ui.Val("关闭"),
|
||||||
|
OnPress: func() { c.instancesOpen.Set(false) }}),
|
||||||
|
),
|
||||||
|
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||||
|
}),
|
||||||
|
ui.For(c.connections, func(conn storage.Connection) string { return conn.ID },
|
||||||
|
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
|
||||||
|
return ui.Column(ui.Style{Gap: 4},
|
||||||
|
c.connectionRow(conn),
|
||||||
|
ui.Show(signal.Func(func() bool {
|
||||||
|
return conn.Get().ID == c.activeID.Get() && c.connected.Get()
|
||||||
|
}), func() ui.Node {
|
||||||
|
return ui.StaticText("当前连接", ui.Style{Font: fonts.Footnote,
|
||||||
|
Color: colors.SecondaryLabel, Padding: ui.Symmetric(0, 12)})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
ui.Button(ui.ButtonProps{
|
||||||
|
Title: ui.Val("添加服务器"),
|
||||||
|
Icon: ui.IconPlus,
|
||||||
|
Variant: ui.ButtonTinted,
|
||||||
|
OnPress: func() {
|
||||||
|
c.instancesOpen.Set(false)
|
||||||
|
c.openAddForm()
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -79,7 +79,7 @@ type permissionData struct {
|
|||||||
|
|
||||||
// startEvents subscribes to the server's event stream for the given client.
|
// startEvents subscribes to the server's event stream for the given client.
|
||||||
// It must run on the main thread (it writes the cancel function).
|
// It must run on the main thread (it writes the cancel function).
|
||||||
func (c *controller) startEvents(client *ocapi.Client, p connectParams) {
|
func (c *controller) startEvents(client *ocapi.Client) {
|
||||||
if c.cancelSSE != nil {
|
if c.cancelSSE != nil {
|
||||||
c.cancelSSE()
|
c.cancelSSE()
|
||||||
}
|
}
|
||||||
@@ -226,6 +226,9 @@ func (c *controller) applyEvent(ev ocapi.Event) {
|
|||||||
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
|
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
|
||||||
})
|
})
|
||||||
c.perms.Set(next)
|
c.perms.Set(next)
|
||||||
|
if c.chat != nil {
|
||||||
|
c.chat.syncPerms()
|
||||||
|
}
|
||||||
|
|
||||||
case "permission.replied":
|
case "permission.replied":
|
||||||
var d struct {
|
var d struct {
|
||||||
@@ -243,6 +246,9 @@ func (c *controller) applyEvent(ev ocapi.Event) {
|
|||||||
}
|
}
|
||||||
if len(next) != len(list) {
|
if len(next) != len(list) {
|
||||||
c.perms.Set(next)
|
c.perms.Set(next)
|
||||||
|
if c.chat != nil {
|
||||||
|
c.chat.syncPerms()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+297
-136
@@ -5,6 +5,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -50,20 +51,34 @@ func newApp(st storage.Store) (*controller, ui.Node) {
|
|||||||
type controller struct {
|
type controller struct {
|
||||||
st storage.Store
|
st storage.Store
|
||||||
|
|
||||||
|
connections *signal.Signal[[]storage.Connection]
|
||||||
|
|
||||||
url *signal.Signal[string]
|
url *signal.Signal[string]
|
||||||
password *signal.Signal[string]
|
|
||||||
useProxy *signal.Signal[bool]
|
|
||||||
proxy *signal.Signal[string]
|
|
||||||
insecure *signal.Signal[bool]
|
|
||||||
status *signal.Signal[string]
|
status *signal.Signal[string]
|
||||||
|
errorMsg *signal.Signal[string]
|
||||||
|
|
||||||
server *signal.Signal[string]
|
formOpen *signal.Signal[bool]
|
||||||
connected *signal.Signal[bool]
|
formEditID string
|
||||||
busy *signal.Signal[bool]
|
formLabel *signal.Signal[string]
|
||||||
sessions *signal.Signal[[]ocapi.Session]
|
formUseProxy *signal.Signal[bool]
|
||||||
active *signal.Signal[map[string]bool]
|
formProxy *signal.Signal[string]
|
||||||
perms *signal.Signal[[]ocapi.PermissionRequest]
|
formInsecure *signal.Signal[bool]
|
||||||
|
|
||||||
|
passwordOpen *signal.Signal[bool]
|
||||||
|
passwordFor storage.Connection
|
||||||
|
passwordText *signal.Signal[string]
|
||||||
|
passwordBusy *signal.Signal[bool]
|
||||||
|
|
||||||
|
instancesOpen *signal.Signal[bool]
|
||||||
|
|
||||||
|
server *signal.Signal[string]
|
||||||
|
connected *signal.Signal[bool]
|
||||||
|
busy *signal.Signal[bool]
|
||||||
|
connecting *signal.Signal[string]
|
||||||
|
activeID *signal.Signal[string]
|
||||||
|
sessions *signal.Signal[[]ocapi.Session]
|
||||||
|
active *signal.Signal[map[string]bool]
|
||||||
|
perms *signal.Signal[[]ocapi.PermissionRequest]
|
||||||
defaultDir *signal.Signal[string]
|
defaultDir *signal.Signal[string]
|
||||||
|
|
||||||
newOpen *signal.Signal[bool]
|
newOpen *signal.Signal[bool]
|
||||||
@@ -78,45 +93,54 @@ type controller struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func newController(st storage.Store) *controller {
|
func newController(st storage.Store) *controller {
|
||||||
|
conns := st.Connections()
|
||||||
|
sort.SliceStable(conns, func(i, j int) bool { return conns[i].LastUsedAt > conns[j].LastUsedAt })
|
||||||
c := &controller{
|
c := &controller{
|
||||||
st: st,
|
st: st,
|
||||||
url: signal.New(""),
|
connections: signal.NewFunc(conns, nil),
|
||||||
password: signal.New(""),
|
url: signal.New(""),
|
||||||
useProxy: signal.New(false),
|
status: signal.New(""),
|
||||||
proxy: signal.New(""),
|
errorMsg: signal.New(""),
|
||||||
insecure: signal.New(false),
|
formOpen: signal.New(false),
|
||||||
status: signal.New("输入服务器地址与密码后连接"),
|
formLabel: signal.New(""),
|
||||||
server: signal.New(""),
|
formUseProxy: signal.New(false),
|
||||||
connected: signal.New(false),
|
formProxy: signal.New(""),
|
||||||
busy: signal.New(false),
|
formInsecure: signal.New(false),
|
||||||
sessions: signal.NewFunc([]ocapi.Session{}, nil),
|
passwordOpen: signal.New(false),
|
||||||
active: signal.NewFunc(map[string]bool{}, nil),
|
passwordText: signal.New(""),
|
||||||
perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
passwordBusy: signal.New(false),
|
||||||
defaultDir: signal.New(""),
|
instancesOpen: signal.New(false),
|
||||||
newOpen: signal.New(false),
|
server: signal.New(""),
|
||||||
newTitle: signal.New(""),
|
connected: signal.New(false),
|
||||||
newDir: signal.New(0),
|
busy: signal.New(false),
|
||||||
creating: signal.New(false),
|
connecting: signal.New(""),
|
||||||
|
activeID: signal.New(""),
|
||||||
|
sessions: signal.NewFunc([]ocapi.Session{}, nil),
|
||||||
|
active: signal.NewFunc(map[string]bool{}, nil),
|
||||||
|
perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
||||||
|
defaultDir: signal.New(""),
|
||||||
|
newOpen: signal.New(false),
|
||||||
|
newTitle: signal.New(""),
|
||||||
|
newDir: signal.New(0),
|
||||||
|
creating: signal.New(false),
|
||||||
}
|
}
|
||||||
if conn, ok := st.Connection(); ok {
|
// Come back to the server last used, as the first-party client does.
|
||||||
c.url.Set(conn.URL)
|
if len(conns) > 0 {
|
||||||
c.proxy.Set(conn.Proxy)
|
c.connectTo(conns[0], "", false)
|
||||||
c.useProxy.Set(conn.Proxy != "")
|
|
||||||
c.insecure.Set(conn.Insecure)
|
|
||||||
c.status.Set("正在恢复连接…")
|
|
||||||
c.reconnect(conn)
|
|
||||||
}
|
}
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *controller) screen() ui.Node {
|
func (c *controller) screen() ui.Node {
|
||||||
return ui.SafeArea(ui.Style{Grow: 1},
|
return ui.SafeArea(ui.Style{Grow: 1},
|
||||||
ui.Show(c.connected, c.sessionsScreen, c.connectScreen),
|
ui.Show(c.connected, c.sessionsScreen, c.connectionsScreen),
|
||||||
|
c.formSheet(),
|
||||||
|
c.passwordSheet(),
|
||||||
|
c.instancesSheet(),
|
||||||
|
c.newSessionSheetNode(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// shutdown stops what the controller started; the root owner calls it when
|
|
||||||
// the app (or a test) unmounts.
|
|
||||||
func (c *controller) shutdown() {
|
func (c *controller) shutdown() {
|
||||||
if c.cancelSSE != nil {
|
if c.cancelSSE != nil {
|
||||||
c.cancelSSE()
|
c.cancelSSE()
|
||||||
@@ -125,75 +149,42 @@ func (c *controller) shutdown() {
|
|||||||
c.client = nil
|
c.client = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *controller) connect() {
|
// connectTo starts a connection attempt off the main thread. password is
|
||||||
if c.busy.Peek() {
|
// the one the user typed, if any; explicit marks a tap (a password may be
|
||||||
|
// asked for), while the launch reconnect stays quiet.
|
||||||
|
func (c *controller) connectTo(conn storage.Connection, password string, explicit bool) {
|
||||||
|
if c.connecting.Peek() != "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
params := connectParams{
|
c.connecting.Set(conn.ID)
|
||||||
url: strings.TrimSpace(c.url.Peek()),
|
c.errorMsg.Set("")
|
||||||
password: c.password.Peek(),
|
|
||||||
insecure: c.insecure.Peek(),
|
|
||||||
explicit: true,
|
|
||||||
}
|
|
||||||
if c.useProxy.Peek() {
|
|
||||||
params.proxy = strings.TrimSpace(c.proxy.Peek())
|
|
||||||
}
|
|
||||||
c.busy.Set(true)
|
|
||||||
c.status.Set("连接中…")
|
|
||||||
go func() {
|
go func() {
|
||||||
c.establish(params, "")
|
c.establish(conn, password, explicit)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// reconnect retries a stored connection, whose token lives in secure
|
// establish runs the whole connect sequence: health, token probe, optional
|
||||||
// storage (readable only off the main thread).
|
// password login, first page of sessions.
|
||||||
func (c *controller) reconnect(conn storage.Connection) {
|
func (c *controller) establish(conn storage.Connection, password string, explicit bool) {
|
||||||
params := connectParams{
|
|
||||||
url: conn.URL,
|
|
||||||
proxy: conn.Proxy,
|
|
||||||
insecure: conn.Insecure,
|
|
||||||
}
|
|
||||||
if conn.Passwordless {
|
|
||||||
// No token was issued; the server answers without one.
|
|
||||||
go func() { c.establish(params, "") }()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
token, ok, err := c.st.LoadToken(conn.URL)
|
|
||||||
if err != nil || !ok {
|
|
||||||
ui.Post(func() { c.status.Set("请重新输入密码") })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.establish(params, token)
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
type connectParams struct {
|
|
||||||
url string
|
|
||||||
password string
|
|
||||||
proxy string
|
|
||||||
insecure bool
|
|
||||||
// explicit means the user pressed Connect: a password prompt is
|
|
||||||
// theirs to answer. A background reconnect never asks.
|
|
||||||
explicit bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// establish runs the whole connect sequence off the main thread: health,
|
|
||||||
// token probe, optional password login, first page of sessions. It reports
|
|
||||||
// through the signals with ui.Post.
|
|
||||||
func (c *controller) establish(p connectParams, token string) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
fail := func(err error) {
|
fail := func(err error) {
|
||||||
ui.Post(func() {
|
ui.Post(func() {
|
||||||
c.busy.Set(false)
|
c.connecting.Set("")
|
||||||
c.status.Set(friendlyError(err))
|
c.errorMsg.Set(friendlyError(err))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
if !strings.Contains(conn.URL, "://") {
|
||||||
|
normalized, err := ocapi.NormalizeBaseURL(conn.URL)
|
||||||
|
if err != nil {
|
||||||
|
fail(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn.URL = normalized
|
||||||
|
}
|
||||||
|
|
||||||
opts := ocapi.Options{Proxy: p.proxy, InsecureSkipVerify: p.insecure}
|
client, err := ocapi.New(conn.URL, ocapi.Options{Proxy: conn.Proxy, InsecureSkipVerify: conn.Insecure})
|
||||||
client, err := ocapi.New(p.url, opts)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fail(err)
|
fail(err)
|
||||||
return
|
return
|
||||||
@@ -208,48 +199,59 @@ func (c *controller) establish(p connectParams, token string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
passwordless := false
|
token := ""
|
||||||
if token != "" {
|
if !conn.Passwordless {
|
||||||
client.SetToken(token)
|
if t, ok, err := c.st.LoadToken(conn); err == nil && ok {
|
||||||
|
token = t
|
||||||
|
client.SetToken(t)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
passwordless := conn.Passwordless
|
||||||
auth, authErr := client.SessionStatus(ctx)
|
auth, authErr := client.SessionStatus(ctx)
|
||||||
switch {
|
switch {
|
||||||
case authErr == nil:
|
case authErr == nil:
|
||||||
passwordless = auth.Disabled
|
passwordless = auth.Disabled
|
||||||
case ocapi.IsUnauthorized(authErr):
|
case ocapi.IsUnauthorized(authErr):
|
||||||
if strings.TrimSpace(p.password) == "" {
|
if strings.TrimSpace(password) == "" {
|
||||||
if token != "" {
|
if explicit {
|
||||||
// The stored token is no good: drop it so the next
|
ui.Post(func() {
|
||||||
// attempt does not retry with it.
|
c.connecting.Set("")
|
||||||
server := client.BaseURL()
|
c.askPassword(conn)
|
||||||
go func() { _ = c.st.ClearToken(server) }()
|
})
|
||||||
}
|
|
||||||
if p.explicit {
|
|
||||||
fail(errUnauthorized)
|
|
||||||
} else {
|
} else {
|
||||||
ui.Post(func() { c.status.Set("登录已失效,请输入密码重新连接") })
|
ui.Post(func() {
|
||||||
|
c.connecting.Set("")
|
||||||
|
c.errorMsg.Set("登录已失效,请重新输入密码")
|
||||||
|
c.askPassword(conn)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if token != "" {
|
||||||
|
go func() { _ = c.st.ClearToken(conn) }()
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
res, err := client.Login(ctx, ocapi.LoginRequest{
|
res, err := client.Login(ctx, ocapi.LoginRequest{
|
||||||
Password: p.password,
|
Password: password,
|
||||||
DedupeKey: c.st.InstallID(),
|
DedupeKey: c.st.InstallID(),
|
||||||
ClientLabel: "OpenChamber Native",
|
ClientLabel: "OpenChamber Native",
|
||||||
ClientKind: "mobile",
|
ClientKind: "mobile",
|
||||||
DevicePlatform: "android",
|
DevicePlatform: "android",
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fail(err)
|
ui.Post(func() {
|
||||||
|
c.connecting.Set("")
|
||||||
|
c.errorMsg.Set(friendlyError(err))
|
||||||
|
c.passwordBusy.Set(false)
|
||||||
|
c.passwordOpen.Set(true)
|
||||||
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if res.ClientToken == "" {
|
if res.ClientToken == "" {
|
||||||
fail(errors.New("登录没有返回设备 token"))
|
fail(errors.New("登录没有返回设备 token"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := c.st.SaveToken(client.BaseURL(), res.ClientToken); err != nil {
|
_ = c.st.SaveToken(conn.ID, res.ClientToken)
|
||||||
// A token that cannot be persisted still works for this run.
|
passwordless = false
|
||||||
_ = err
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
fail(authErr)
|
fail(authErr)
|
||||||
return
|
return
|
||||||
@@ -270,19 +272,23 @@ func (c *controller) establish(p connectParams, token string) {
|
|||||||
}
|
}
|
||||||
perms, _ := client.PendingPermissions(ctx, "")
|
perms, _ := client.PendingPermissions(ctx, "")
|
||||||
|
|
||||||
info := fmt.Sprintf("%s · OpenChamber %s", client.BaseURL(), health.OpenChamberVersion)
|
info := fmt.Sprintf("%s · OpenChamber %s", c.labelOf(conn), health.OpenChamberVersion)
|
||||||
if !health.IsOpenCodeReady {
|
if !health.IsOpenCodeReady {
|
||||||
info += " · OpenCode 未就绪"
|
info += " · OpenCode 未就绪"
|
||||||
}
|
}
|
||||||
c.st.SaveConnection(storage.Connection{
|
|
||||||
URL: client.BaseURL(),
|
conn.URL = client.BaseURL()
|
||||||
Proxy: p.proxy,
|
if conn.Label == "" {
|
||||||
Insecure: p.insecure,
|
conn.Label = hostOf(conn.URL)
|
||||||
ServerID: health.ServerID,
|
}
|
||||||
Passwordless: passwordless,
|
conn.ServerID = health.ServerID
|
||||||
})
|
conn.Passwordless = passwordless
|
||||||
|
conn.LastUsedAt = time.Now().UnixMilli()
|
||||||
|
|
||||||
ui.Post(func() {
|
ui.Post(func() {
|
||||||
|
c.connecting.Set("")
|
||||||
|
c.saveConnection(conn)
|
||||||
|
c.activeID.Set(conn.ID)
|
||||||
c.client = client
|
c.client = client
|
||||||
c.sessions.Set(page.Data)
|
c.sessions.Set(page.Data)
|
||||||
c.active.Set(running)
|
c.active.Set(running)
|
||||||
@@ -290,12 +296,47 @@ func (c *controller) establish(p connectParams, token string) {
|
|||||||
c.server.Set(info)
|
c.server.Set(info)
|
||||||
c.connected.Set(true)
|
c.connected.Set(true)
|
||||||
c.busy.Set(false)
|
c.busy.Set(false)
|
||||||
c.password.Set("")
|
c.formOpen.Set(false)
|
||||||
|
c.passwordOpen.Set(false)
|
||||||
|
c.passwordText.Set("")
|
||||||
|
c.passwordBusy.Set(false)
|
||||||
|
c.instancesOpen.Set(false)
|
||||||
|
c.errorMsg.Set("")
|
||||||
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
|
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
|
||||||
c.startEvents(client, p)
|
c.startEvents(client)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *controller) saveConnection(conn storage.Connection) {
|
||||||
|
conns := c.connections.Peek()
|
||||||
|
found := false
|
||||||
|
next := make([]storage.Connection, 0, len(conns)+1)
|
||||||
|
for _, existing := range conns {
|
||||||
|
if existing.ID == conn.ID {
|
||||||
|
next = append(next, conn)
|
||||||
|
found = true
|
||||||
|
} else {
|
||||||
|
next = append(next, existing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
if conn.ID == "" {
|
||||||
|
conn.ID = storage.NewID()
|
||||||
|
}
|
||||||
|
next = append(next, conn)
|
||||||
|
}
|
||||||
|
sort.SliceStable(next, func(i, j int) bool { return next[i].LastUsedAt > next[j].LastUsedAt })
|
||||||
|
c.st.SaveConnections(next)
|
||||||
|
c.connections.Set(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) labelOf(conn storage.Connection) string {
|
||||||
|
if strings.TrimSpace(conn.Label) != "" {
|
||||||
|
return conn.Label
|
||||||
|
}
|
||||||
|
return hostOf(conn.URL)
|
||||||
|
}
|
||||||
|
|
||||||
func (c *controller) refresh() {
|
func (c *controller) refresh() {
|
||||||
if c.client == nil || c.busy.Peek() {
|
if c.client == nil || c.busy.Peek() {
|
||||||
return
|
return
|
||||||
@@ -305,9 +346,6 @@ func (c *controller) refresh() {
|
|||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if loc, err := client.Location(ctx); err == nil && loc.Directory != "" {
|
|
||||||
ui.Post(func() { c.defaultDir.Set(loc.Directory) })
|
|
||||||
}
|
|
||||||
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"})
|
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"})
|
||||||
active, aerr := client.ActiveSessions(ctx)
|
active, aerr := client.ActiveSessions(ctx)
|
||||||
running := make(map[string]bool, len(active))
|
running := make(map[string]bool, len(active))
|
||||||
@@ -322,7 +360,7 @@ func (c *controller) refresh() {
|
|||||||
c.logout("登录已失效,请输入密码重新连接")
|
c.logout("登录已失效,请输入密码重新连接")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.status.Set(friendlyError(err))
|
c.errorMsg.Set(friendlyError(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.sessions.Set(page.Data)
|
c.sessions.Set(page.Data)
|
||||||
@@ -337,31 +375,143 @@ func (c *controller) refresh() {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// logout drops the session but keeps the address so the user only types
|
// logout drops the live session but keeps the saved servers.
|
||||||
// the password again.
|
|
||||||
func (c *controller) logout(reason string) {
|
func (c *controller) logout(reason string) {
|
||||||
if c.cancelSSE != nil {
|
if c.cancelSSE != nil {
|
||||||
c.cancelSSE()
|
c.cancelSSE()
|
||||||
c.cancelSSE = nil
|
c.cancelSSE = nil
|
||||||
}
|
}
|
||||||
if c.client != nil {
|
var conn storage.Connection
|
||||||
server := c.client.BaseURL()
|
if id := c.activeID.Peek(); id != "" {
|
||||||
go func() { _ = c.st.ClearToken(server) }()
|
for _, saved := range c.connections.Peek() {
|
||||||
}
|
if saved.ID == id {
|
||||||
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
|
conn = saved
|
||||||
c.chat.nav.Pop()
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c.client = nil
|
c.client = nil
|
||||||
c.connected.Set(false)
|
c.connected.Set(false)
|
||||||
|
c.activeID.Set("")
|
||||||
c.sessions.Set(nil)
|
c.sessions.Set(nil)
|
||||||
c.active.Set(map[string]bool{})
|
c.active.Set(map[string]bool{})
|
||||||
c.perms.Set(nil)
|
c.perms.Set(nil)
|
||||||
c.server.Set("")
|
c.server.Set("")
|
||||||
c.status.Set(reason)
|
c.errorMsg.Set(reason)
|
||||||
|
if conn.ID != "" && reason != "" {
|
||||||
|
go func() { _ = c.st.ClearToken(conn) }()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *controller) disconnect() {
|
func (c *controller) disconnect() {
|
||||||
c.logout("已断开")
|
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
|
||||||
|
c.chat.nav.Pop()
|
||||||
|
}
|
||||||
|
c.logout("")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- form ---------------------------------------------------------------
|
||||||
|
|
||||||
|
func (c *controller) openAddForm() {
|
||||||
|
c.formEditID = ""
|
||||||
|
c.url.Set("")
|
||||||
|
c.formLabel.Set("")
|
||||||
|
c.formUseProxy.Set(false)
|
||||||
|
c.formProxy.Set("")
|
||||||
|
c.formInsecure.Set(false)
|
||||||
|
c.errorMsg.Set("")
|
||||||
|
c.formOpen.Set(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) openEditForm(conn storage.Connection) {
|
||||||
|
c.formEditID = conn.ID
|
||||||
|
c.url.Set(conn.URL)
|
||||||
|
c.formLabel.Set(conn.Label)
|
||||||
|
c.formUseProxy.Set(conn.Proxy != "")
|
||||||
|
c.formProxy.Set(conn.Proxy)
|
||||||
|
c.formInsecure.Set(conn.Insecure)
|
||||||
|
c.errorMsg.Set("")
|
||||||
|
c.formOpen.Set(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) closeForm() {
|
||||||
|
c.formOpen.Set(false)
|
||||||
|
c.errorMsg.Set("")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) submitForm() {
|
||||||
|
raw := strings.TrimSpace(c.url.Peek())
|
||||||
|
if raw == "" {
|
||||||
|
c.errorMsg.Set("请输入服务器地址")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
normalized, err := ocapi.NormalizeBaseURL(raw)
|
||||||
|
if err != nil {
|
||||||
|
c.errorMsg.Set(friendlyError(err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn := storage.Connection{ID: c.formEditID, URL: normalized, Label: strings.TrimSpace(c.formLabel.Peek())}
|
||||||
|
if c.formUseProxy.Peek() {
|
||||||
|
conn.Proxy = strings.TrimSpace(c.formProxy.Peek())
|
||||||
|
}
|
||||||
|
conn.Insecure = c.formInsecure.Peek()
|
||||||
|
if conn.ID != "" {
|
||||||
|
for _, saved := range c.connections.Peek() {
|
||||||
|
if saved.ID == conn.ID {
|
||||||
|
conn.ServerID = saved.ServerID
|
||||||
|
conn.Passwordless = saved.Passwordless
|
||||||
|
conn.LastUsedAt = saved.LastUsedAt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if conn.ID == "" {
|
||||||
|
conn.ID = storage.NewID()
|
||||||
|
}
|
||||||
|
c.saveConnection(conn)
|
||||||
|
c.formOpen.Set(false)
|
||||||
|
|
||||||
|
if !c.connected.Peek() {
|
||||||
|
c.connectTo(conn, "", true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.status.Set("已保存")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- password -----------------------------------------------------------
|
||||||
|
|
||||||
|
func (c *controller) askPassword(conn storage.Connection) {
|
||||||
|
c.passwordFor = conn
|
||||||
|
c.passwordText.Set("")
|
||||||
|
c.passwordBusy.Set(false)
|
||||||
|
c.passwordOpen.Set(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) submitPassword() {
|
||||||
|
if c.passwordBusy.Peek() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pw := c.passwordText.Peek()
|
||||||
|
if strings.TrimSpace(pw) == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn := c.passwordFor
|
||||||
|
c.passwordBusy.Set(true)
|
||||||
|
c.passwordOpen.Set(false)
|
||||||
|
c.connectToPassword(conn, pw)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) connectToPassword(conn storage.Connection, password string) {
|
||||||
|
if c.connecting.Peek() != "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.connecting.Set(conn.ID)
|
||||||
|
c.errorMsg.Set("")
|
||||||
|
go func() { c.establish(conn, password, true) }()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *controller) cancelPassword() {
|
||||||
|
c.passwordOpen.Set(false)
|
||||||
|
c.passwordText.Set("")
|
||||||
|
c.passwordBusy.Set(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
var errUnauthorized = errors.New("这个服务器需要密码")
|
var errUnauthorized = errors.New("这个服务器需要密码")
|
||||||
@@ -399,6 +549,17 @@ func friendlyError(err error) string {
|
|||||||
return msg
|
return msg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func hostOf(raw string) string {
|
||||||
|
s := strings.TrimSpace(raw)
|
||||||
|
if i := strings.Index(s, "://"); i >= 0 {
|
||||||
|
s = s[i+3:]
|
||||||
|
}
|
||||||
|
if i := strings.IndexByte(s, '/'); i >= 0 {
|
||||||
|
s = s[:i]
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
func shortPath(p string) string {
|
func shortPath(p string) string {
|
||||||
p = strings.TrimRight(p, "/")
|
p = strings.TrimRight(p, "/")
|
||||||
if p == "" {
|
if p == "" {
|
||||||
|
|||||||
+150
-80
@@ -16,71 +16,77 @@ import (
|
|||||||
// memStore is a storage.Store that keeps everything in memory.
|
// memStore is a storage.Store that keeps everything in memory.
|
||||||
type memStore struct {
|
type memStore struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
conn storage.Connection
|
conns []storage.Connection
|
||||||
has bool
|
|
||||||
tokens map[string]string
|
tokens map[string]string
|
||||||
id string
|
id string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memStore) Connection() (storage.Connection, bool) {
|
func (m *memStore) Connections() []storage.Connection {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
return m.conn, m.has
|
out := make([]storage.Connection, len(m.conns))
|
||||||
|
copy(out, m.conns)
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
func (m *memStore) SaveConnection(c storage.Connection) {
|
|
||||||
|
func (m *memStore) SaveConnections(list []storage.Connection) {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
m.conn, m.has = c, c.URL != ""
|
out := make([]storage.Connection, len(list))
|
||||||
}
|
copy(out, list)
|
||||||
func (m *memStore) ClearConnection() {
|
m.conns = out
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
m.conn, m.has = storage.Connection{}, false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memStore) InstallID() string {
|
func (m *memStore) InstallID() string {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
if m.id == "" {
|
if m.id == "" {
|
||||||
m.id = "test-install"
|
m.id = "test-install"
|
||||||
}
|
}
|
||||||
return m.id
|
return m.id
|
||||||
}
|
}
|
||||||
func (m *memStore) LoadToken(server string) (string, bool, error) {
|
|
||||||
|
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
t, ok := m.tokens[server]
|
t, ok := m.tokens[c.ID]
|
||||||
return t, ok, nil
|
return t, ok, nil
|
||||||
}
|
}
|
||||||
func (m *memStore) SaveToken(server, token string) error {
|
|
||||||
|
func (m *memStore) SaveToken(id, token string) error {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
if m.tokens == nil {
|
if m.tokens == nil {
|
||||||
m.tokens = map[string]string{}
|
m.tokens = map[string]string{}
|
||||||
}
|
}
|
||||||
m.tokens[server] = token
|
m.tokens[id] = token
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (m *memStore) ClearToken(server string) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
delete(m.tokens, server)
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memStore) token(server string) string {
|
func (m *memStore) ClearToken(c storage.Connection) error {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
return m.tokens[server]
|
delete(m.tokens, c.ID)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *memStore) connection() storage.Connection {
|
func (m *memStore) token(id string) string {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
defer m.mu.Unlock()
|
defer m.mu.Unlock()
|
||||||
return m.conn
|
return m.tokens[id]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *memStore) connections() []storage.Connection {
|
||||||
|
return m.Connections()
|
||||||
}
|
}
|
||||||
|
|
||||||
// fakeServer stands in for OpenChamber: /health, /auth/session and the
|
// fakeServer stands in for OpenChamber: /health, /auth/session and the
|
||||||
// session list. password "" with validToken "" makes it passwordless.
|
// session list. An empty password makes it passwordless.
|
||||||
func fakeServer(t *testing.T, password, validToken string) *httptest.Server {
|
func fakeServer(t *testing.T, password, validToken, sessionTitle string) *httptest.Server {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
if sessionTitle == "" {
|
||||||
|
sessionTitle = "First session"
|
||||||
|
}
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
authorized := func(r *http.Request) bool {
|
authorized := func(r *http.Request) bool {
|
||||||
if validToken == "" {
|
if validToken == "" {
|
||||||
@@ -117,15 +123,16 @@ func fakeServer(t *testing.T, password, validToken string) *httptest.Server {
|
|||||||
fmt.Fprintf(w, `{"authenticated":true,"clientToken":%q}`, validToken)
|
fmt.Fprintf(w, `{"authenticated":true,"clientToken":%q}`, validToken)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
|
||||||
|
})
|
||||||
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
|
||||||
if !authorized(r) {
|
if !authorized(r) {
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fmt.Fprint(w, `{"data":[
|
fmt.Fprintf(w, `{"data":[{"id":"ses_1","title":%q,"time":{"created":1,"updated":2},
|
||||||
{"id":"ses_1","title":"First session","time":{"created":1,"updated":2},
|
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`, sessionTitle)
|
||||||
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],
|
|
||||||
"cursor":{}}`)
|
|
||||||
})
|
})
|
||||||
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
|
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
|
||||||
@@ -151,86 +158,149 @@ func mount(t *testing.T, st *memStore) *uitest.App {
|
|||||||
return uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
return uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConnectWithPassword(t *testing.T) {
|
// connectViaForm adds a server from the first screen (or the saved list)
|
||||||
srv := fakeServer(t, "secret", "oc_client_test")
|
// and taps Connect.
|
||||||
|
func connectViaForm(t *testing.T, a *uitest.App, url string) {
|
||||||
|
t.Helper()
|
||||||
|
if a.Has("手动输入地址") {
|
||||||
|
a.Tap("手动输入地址")
|
||||||
|
} else {
|
||||||
|
a.Tap("添加服务器")
|
||||||
|
}
|
||||||
|
a.Type("http://192.168.1.5:3000", url)
|
||||||
|
a.Tap("连接")
|
||||||
|
}
|
||||||
|
|
||||||
|
func unlockWith(t *testing.T, a *uitest.App, password string) {
|
||||||
|
t.Helper()
|
||||||
|
a.WaitFor("这台服务器需要密码。")
|
||||||
|
a.Type("密码", password)
|
||||||
|
a.Tap("解锁")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnectWithPassword(t *testing.T) {
|
||||||
|
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||||
st := &memStore{}
|
st := &memStore{}
|
||||||
a := mount(t, st)
|
a := mount(t, st)
|
||||||
a.Expect("连接到 OpenChamber")
|
connectViaForm(t, a, srv.URL)
|
||||||
|
unlockWith(t, a, "secret")
|
||||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
|
||||||
a.Type("密码(可选)", "secret")
|
|
||||||
a.Tap("连接")
|
|
||||||
a.WaitFor("First session")
|
a.WaitFor("First session")
|
||||||
a.ExpectNo("密码(可选)")
|
|
||||||
|
|
||||||
if got := st.connection().URL; got != srv.URL {
|
conns := st.connections()
|
||||||
t.Errorf("connection not saved: %q", got)
|
if len(conns) != 1 || conns[0].URL != srv.URL {
|
||||||
|
t.Fatalf("connections = %+v", conns)
|
||||||
}
|
}
|
||||||
if got := st.token(srv.URL); got != "oc_client_test" {
|
if got := st.token(conns[0].ID); got != "oc_client_test" {
|
||||||
t.Errorf("token not saved: %q", got)
|
t.Errorf("token = %q", got)
|
||||||
|
}
|
||||||
|
if conns[0].Passwordless {
|
||||||
|
t.Error("password server marked passwordless")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWrongPassword(t *testing.T) {
|
func TestWrongPasswordThenRetry(t *testing.T) {
|
||||||
srv := fakeServer(t, "secret", "oc_client_test")
|
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||||
|
st := &memStore{}
|
||||||
a := mount(t, &memStore{})
|
a := mount(t, st)
|
||||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
connectViaForm(t, a, srv.URL)
|
||||||
a.Type("密码(可选)", "nope")
|
unlockWith(t, a, "nope")
|
||||||
a.Tap("连接")
|
|
||||||
a.WaitFor("密码错误")
|
a.WaitFor("密码错误")
|
||||||
|
// The prompt stays up so the password can be retried.
|
||||||
|
a.Type("密码", "secret")
|
||||||
|
a.Tap("解锁")
|
||||||
|
a.WaitFor("First session")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAutoReconnectWithStoredToken(t *testing.T) {
|
func TestAutoReconnectWithStoredToken(t *testing.T) {
|
||||||
srv := fakeServer(t, "secret", "oc_client_test")
|
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||||
|
|
||||||
st := &memStore{
|
st := &memStore{
|
||||||
conn: storage.Connection{URL: srv.URL},
|
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
|
||||||
has: true,
|
tokens: map[string]string{"a": "oc_client_test"},
|
||||||
tokens: map[string]string{srv.URL: "oc_client_test"},
|
|
||||||
}
|
}
|
||||||
a := mount(t, st)
|
a := mount(t, st)
|
||||||
a.WaitFor("First session")
|
a.WaitFor("First session")
|
||||||
a.ExpectNo("连接到 OpenChamber")
|
a.ExpectNo("手动输入地址")
|
||||||
|
a.ExpectNo("这台服务器需要密码。")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExpiredTokenAsksForPassword(t *testing.T) {
|
func TestExpiredTokenAsksForPassword(t *testing.T) {
|
||||||
srv := fakeServer(t, "secret", "oc_client_test")
|
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||||
|
|
||||||
st := &memStore{
|
st := &memStore{
|
||||||
conn: storage.Connection{URL: srv.URL},
|
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
|
||||||
has: true,
|
tokens: map[string]string{"a": "revoked"},
|
||||||
tokens: map[string]string{srv.URL: "revoked"},
|
|
||||||
}
|
}
|
||||||
a := mount(t, st)
|
a := mount(t, st)
|
||||||
a.WaitFor("登录已失效,请输入密码重新连接")
|
a.WaitFor("登录已失效,请重新输入密码")
|
||||||
a.Expect("连接到 OpenChamber")
|
a.Until("the revoked token to be dropped", func() bool { return st.token("a") == "" })
|
||||||
a.Until("the revoked token to be dropped", func() bool { return st.token(srv.URL) == "" })
|
unlockWith(t, a, "secret")
|
||||||
|
a.WaitFor("First session")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPasswordlessServer(t *testing.T) {
|
func TestPasswordlessServer(t *testing.T) {
|
||||||
srv := fakeServer(t, "", "")
|
srv := fakeServer(t, "", "", "")
|
||||||
|
|
||||||
st := &memStore{}
|
st := &memStore{}
|
||||||
a := mount(t, st)
|
a := mount(t, st)
|
||||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
connectViaForm(t, a, srv.URL)
|
||||||
a.Tap("连接")
|
|
||||||
a.WaitFor("First session")
|
a.WaitFor("First session")
|
||||||
if got := st.connection(); !got.Passwordless {
|
conns := st.connections()
|
||||||
t.Errorf("passwordless not remembered: %+v", got)
|
if len(conns) != 1 || !conns[0].Passwordless {
|
||||||
|
t.Fatalf("connections = %+v", conns)
|
||||||
|
}
|
||||||
|
if got := st.token(conns[0].ID); got != "" {
|
||||||
|
t.Errorf("unexpected token %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAutoReconnectPasswordlessWithoutToken(t *testing.T) {
|
func TestMultipleConnectionsAndSwitch(t *testing.T) {
|
||||||
srv := fakeServer(t, "", "")
|
srvA := fakeServer(t, "", "", "Session A")
|
||||||
t.Cleanup(srv.Close)
|
srvB := fakeServer(t, "", "", "Session B")
|
||||||
|
st := &memStore{conns: []storage.Connection{
|
||||||
st := &memStore{
|
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 2},
|
||||||
conn: storage.Connection{URL: srv.URL, Passwordless: true},
|
{ID: "b", URL: srvB.URL, Label: "B", Passwordless: true, LastUsedAt: 1},
|
||||||
has: true,
|
}}
|
||||||
}
|
|
||||||
a := mount(t, st)
|
a := mount(t, st)
|
||||||
a.WaitFor("First session")
|
a.WaitFor("Session A")
|
||||||
a.ExpectNo("请重新输入密码")
|
|
||||||
|
a.Tap("断开")
|
||||||
|
a.Expect("A")
|
||||||
|
a.Expect("B")
|
||||||
|
|
||||||
|
a.Tap("B")
|
||||||
|
a.WaitFor("Session B")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddAnotherConnection(t *testing.T) {
|
||||||
|
srvA := fakeServer(t, "", "", "Session A")
|
||||||
|
srvB := fakeServer(t, "", "", "Session B")
|
||||||
|
st := &memStore{conns: []storage.Connection{
|
||||||
|
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
|
||||||
|
}}
|
||||||
|
a := mount(t, st)
|
||||||
|
a.WaitFor("Session A")
|
||||||
|
a.Tap("断开")
|
||||||
|
a.Tap("添加服务器")
|
||||||
|
a.Type("http://192.168.1.5:3000", srvB.URL)
|
||||||
|
a.Type("名称(可选)", "B")
|
||||||
|
a.Tap("连接")
|
||||||
|
a.WaitFor("Session B")
|
||||||
|
|
||||||
|
if conns := st.connections(); len(conns) != 2 {
|
||||||
|
t.Fatalf("connections = %+v", conns)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteConnection(t *testing.T) {
|
||||||
|
srv := fakeServer(t, "", "", "Session A")
|
||||||
|
st := &memStore{conns: []storage.Connection{
|
||||||
|
{ID: "a", URL: srv.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
|
||||||
|
}}
|
||||||
|
a := mount(t, st)
|
||||||
|
a.WaitFor("Session A")
|
||||||
|
a.Tap("断开")
|
||||||
|
|
||||||
|
a.Tap("操作")
|
||||||
|
a.Tap("删除")
|
||||||
|
a.Tap("删除")
|
||||||
|
a.Until("the connection list to empty", func() bool { return len(st.connections()) == 0 })
|
||||||
|
a.Expect("手动输入地址")
|
||||||
}
|
}
|
||||||
+10
-62
@@ -10,65 +10,20 @@ import (
|
|||||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c *controller) connectScreen() ui.Node {
|
|
||||||
return ui.Scroll(
|
|
||||||
ui.ScrollProps{
|
|
||||||
Style: ui.Style{Grow: 1},
|
|
||||||
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
|
|
||||||
},
|
|
||||||
ui.StaticText("连接到 OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
|
|
||||||
ui.StaticText("输入正在运行的 OpenChamber 服务器地址。没有设置密码的服务器可以留空密码。",
|
|
||||||
ui.Style{Color: colors.SecondaryLabel}),
|
|
||||||
ui.TextField(ui.TextFieldProps{
|
|
||||||
Value: c.url,
|
|
||||||
Placeholder: ui.Val("http://192.168.1.5:3000"),
|
|
||||||
Keyboard: ui.KeyboardURL,
|
|
||||||
ContentType: "url",
|
|
||||||
Autocapitalize: ui.CapitalizeNone,
|
|
||||||
Autocorrect: ui.AutocorrectNo,
|
|
||||||
ReturnKey: ui.ReturnNext,
|
|
||||||
}),
|
|
||||||
ui.TextField(ui.TextFieldProps{
|
|
||||||
Value: c.password,
|
|
||||||
Placeholder: ui.Val("密码(可选)"),
|
|
||||||
Secure: true,
|
|
||||||
ContentType: ui.ContentPassword,
|
|
||||||
ReturnKey: ui.ReturnGo,
|
|
||||||
OnSubmit: c.connect,
|
|
||||||
}),
|
|
||||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
|
||||||
ui.StaticText("使用代理", ui.Style{Grow: 1}),
|
|
||||||
ui.Toggle(ui.ToggleProps{Value: c.useProxy}),
|
|
||||||
),
|
|
||||||
ui.Show(c.useProxy, func() ui.Node {
|
|
||||||
return ui.TextField(ui.TextFieldProps{
|
|
||||||
Value: c.proxy,
|
|
||||||
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
|
|
||||||
Keyboard: ui.KeyboardURL,
|
|
||||||
Autocapitalize: ui.CapitalizeNone,
|
|
||||||
Autocorrect: ui.AutocorrectNo,
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
|
||||||
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
|
|
||||||
ui.Toggle(ui.ToggleProps{Value: c.insecure}),
|
|
||||||
),
|
|
||||||
ui.Button(ui.ButtonProps{
|
|
||||||
Title: ui.Val("连接"),
|
|
||||||
Variant: ui.ButtonFilled,
|
|
||||||
Disabled: c.busy,
|
|
||||||
OnPress: c.connect,
|
|
||||||
}),
|
|
||||||
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *controller) sessionsScreen() ui.Node {
|
func (c *controller) sessionsScreen() ui.Node {
|
||||||
nav := ui.UseNavigator()
|
nav := ui.UseNavigator()
|
||||||
c.nav = nav
|
c.nav = nav
|
||||||
return ui.Column(ui.Style{Grow: 1},
|
return ui.Column(ui.Style{Grow: 1},
|
||||||
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 8, Align: ui.AlignCenter},
|
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 4, Align: ui.AlignCenter},
|
||||||
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1, Grow: 1}),
|
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
||||||
|
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||||
|
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||||
|
func() ui.Node {
|
||||||
|
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red, Lines: 2})
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
ui.Button(ui.ButtonProps{Title: ui.Val("实例"), Variant: ui.ButtonPlain,
|
||||||
|
OnPress: func() { c.instancesOpen.Set(true) }}),
|
||||||
ui.Button(ui.ButtonProps{Title: ui.Val("断开"), Variant: ui.ButtonPlain, OnPress: c.disconnect}),
|
ui.Button(ui.ButtonProps{Title: ui.Val("断开"), Variant: ui.ButtonPlain, OnPress: c.disconnect}),
|
||||||
),
|
),
|
||||||
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
|
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
|
||||||
@@ -103,13 +58,6 @@ func (c *controller) sessionsScreen() ui.Node {
|
|||||||
OnLongPress: func() { c.sessionMenu(s.Get()) },
|
OnLongPress: func() { c.sessionMenu(s.Get()) },
|
||||||
}, c.sessionRow(s, idx))
|
}, c.sessionRow(s, idx))
|
||||||
}),
|
}),
|
||||||
ui.Sheet(ui.SheetProps{
|
|
||||||
Open: c.newOpen,
|
|
||||||
Detents: ui.DetentLarge,
|
|
||||||
Grabber: true,
|
|
||||||
Content: c.newSessionSheet,
|
|
||||||
OnDismiss: func() { c.creating.Set(false) },
|
|
||||||
}),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -169,6 +169,16 @@ func (c *controller) openNewSession() {
|
|||||||
c.newOpen.Set(true)
|
c.newOpen.Set(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *controller) newSessionSheetNode() ui.Node {
|
||||||
|
return ui.Sheet(ui.SheetProps{
|
||||||
|
Open: c.newOpen,
|
||||||
|
Detents: ui.DetentLarge,
|
||||||
|
Grabber: true,
|
||||||
|
Content: c.newSessionSheet,
|
||||||
|
OnDismiss: func() { c.creating.Set(false) },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (c *controller) newSessionSheet() ui.Node {
|
func (c *controller) newSessionSheet() ui.Node {
|
||||||
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14, Grow: 1},
|
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14, Grow: 1},
|
||||||
ui.StaticText("新建会话", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
|
ui.StaticText("新建会话", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
|
||||||
|
|||||||
+98
-56
@@ -1,5 +1,5 @@
|
|||||||
// Package storage keeps the connection settings in the app's store and the
|
// Package storage keeps saved servers in the app's store and their device
|
||||||
// device token in the platform's secure storage.
|
// tokens in the platform's secure storage.
|
||||||
package storage
|
package storage
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -7,77 +7,99 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"sort"
|
||||||
|
|
||||||
"github.com/egoist/asuka/sdk/secure"
|
"github.com/egoist/asuka/sdk/secure"
|
||||||
"github.com/egoist/asuka/sdk/store"
|
"github.com/egoist/asuka/sdk/store"
|
||||||
"github.com/egoist/asuka/signal"
|
"github.com/egoist/asuka/signal"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Connection is the last server the app connected to.
|
// Connection is one saved server.
|
||||||
type Connection struct {
|
type Connection struct {
|
||||||
URL string `json:"url"`
|
ID string `json:"id"`
|
||||||
Proxy string `json:"proxy,omitempty"`
|
Label string `json:"label"`
|
||||||
Insecure bool `json:"insecure,omitempty"`
|
URL string `json:"url"`
|
||||||
Fingerprint string `json:"fingerprint,omitempty"`
|
Proxy string `json:"proxy,omitempty"`
|
||||||
ServerID string `json:"serverId,omitempty"`
|
Insecure bool `json:"insecure,omitempty"`
|
||||||
// Passwordless servers need no token; remembering that avoids a
|
Fingerprint string `json:"fingerprint,omitempty"`
|
||||||
// pointless password prompt on the next launch.
|
ServerID string `json:"serverId,omitempty"`
|
||||||
Passwordless bool `json:"passwordless,omitempty"`
|
Passwordless bool `json:"passwordless,omitempty"`
|
||||||
|
LastUsedAt int64 `json:"lastUsedAt,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store is the persistence the UI needs. Tests use a memory store.
|
// Store is the persistence the UI needs. Tests use a memory store.
|
||||||
type Store interface {
|
type Store interface {
|
||||||
Connection() (Connection, bool)
|
Connections() []Connection
|
||||||
SaveConnection(Connection)
|
SaveConnections([]Connection)
|
||||||
ClearConnection()
|
|
||||||
InstallID() string
|
InstallID() string
|
||||||
LoadToken(server string) (string, bool, error)
|
LoadToken(c Connection) (string, bool, error)
|
||||||
SaveToken(server, token string) error
|
SaveToken(id, token string) error
|
||||||
ClearToken(server string) error
|
ClearToken(c Connection) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Persistent is the app's store: settings in store.json, tokens in the
|
// Persistent is the app's store: servers in store.json, tokens in the
|
||||||
// Android Keystore / Keychain.
|
// Android Keystore / Keychain.
|
||||||
type Persistent struct {
|
type Persistent struct {
|
||||||
conn *signal.Signal[Connection]
|
conns *signal.Signal[[]Connection]
|
||||||
hasConn *signal.Signal[bool]
|
|
||||||
installID *signal.Signal[string]
|
installID *signal.Signal[string]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
connectionsKey = "openchamber.connections"
|
||||||
|
installIDKey = "openchamber.installId"
|
||||||
|
// legacyKey is the single-server record earlier versions wrote.
|
||||||
|
legacyKey = "openchamber.connection"
|
||||||
|
)
|
||||||
|
|
||||||
// New makes the persistent store. Call it on the main thread, while a
|
// New makes the persistent store. Call it on the main thread, while a
|
||||||
// component builds, as any signal.
|
// component builds, as any signal.
|
||||||
func New() *Persistent {
|
func New() *Persistent {
|
||||||
raw := store.Signal("openchamber.connection", "")
|
conns := store.Signal(connectionsKey, []Connection{})
|
||||||
var c Connection
|
list := conns.Get()
|
||||||
ok := raw.Get() != "" && json.Unmarshal([]byte(raw.Get()), &c) == nil && c.URL != ""
|
if len(list) == 0 {
|
||||||
|
list = migrateLegacy()
|
||||||
|
if len(list) > 0 {
|
||||||
|
conns.Set(list)
|
||||||
|
}
|
||||||
|
}
|
||||||
p := &Persistent{
|
p := &Persistent{
|
||||||
conn: signal.NewFunc(c, nil),
|
conns: conns,
|
||||||
hasConn: signal.New(ok),
|
installID: store.Signal(installIDKey, ""),
|
||||||
installID: store.Signal("openchamber.installId", ""),
|
|
||||||
}
|
}
|
||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Persistent) Connection() (Connection, bool) {
|
// migrateLegacy turns the old single-connection record into a list entry.
|
||||||
return p.conn.Get(), p.hasConn.Get()
|
func migrateLegacy() []Connection {
|
||||||
}
|
var raw string
|
||||||
|
if !store.Get(legacyKey, &raw) || raw == "" {
|
||||||
func (p *Persistent) SaveConnection(c Connection) {
|
return nil
|
||||||
p.conn.Set(c)
|
|
||||||
p.hasConn.Set(c.URL != "")
|
|
||||||
buf, err := json.Marshal(c)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
// Keep it in the store as JSON; the signal above stays the source of
|
var old Connection
|
||||||
// truth for the UI.
|
if json.Unmarshal([]byte(raw), &old) != nil || old.URL == "" {
|
||||||
store.Set("openchamber.connection", string(buf))
|
return nil
|
||||||
|
}
|
||||||
|
if old.ID == "" {
|
||||||
|
old.ID = newID()
|
||||||
|
}
|
||||||
|
if old.Label == "" {
|
||||||
|
old.Label = old.URL
|
||||||
|
}
|
||||||
|
// Clear it so the next launch does not migrate again.
|
||||||
|
_ = store.Set(legacyKey, "")
|
||||||
|
return []Connection{old}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Persistent) ClearConnection() {
|
func (p *Persistent) Connections() []Connection {
|
||||||
p.conn.Set(Connection{})
|
list := p.conns.Get()
|
||||||
p.hasConn.Set(false)
|
out := make([]Connection, len(list))
|
||||||
store.Set("openchamber.connection", "")
|
copy(out, list)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Persistent) SaveConnections(list []Connection) {
|
||||||
|
sort.SliceStable(list, func(i, j int) bool { return list[i].LastUsedAt > list[j].LastUsedAt })
|
||||||
|
p.conns.Set(list)
|
||||||
}
|
}
|
||||||
|
|
||||||
// InstallID is a stable random id for this installation. It names the
|
// InstallID is a stable random id for this installation. It names the
|
||||||
@@ -86,28 +108,48 @@ func (p *Persistent) InstallID() string {
|
|||||||
if id := p.installID.Get(); id != "" {
|
if id := p.installID.Get(); id != "" {
|
||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
var b [16]byte
|
id := newID()
|
||||||
if _, err := rand.Read(b[:]); err != nil {
|
|
||||||
return "openchamber-" + hex.EncodeToString(b[:8])
|
|
||||||
}
|
|
||||||
id := hex.EncodeToString(b[:])
|
|
||||||
p.installID.Set(id)
|
p.installID.Set(id)
|
||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Persistent) tokenKey(server string) string {
|
func (p *Persistent) tokenKey(id string) string {
|
||||||
sum := sha256.Sum256([]byte(server))
|
sum := sha256.Sum256([]byte(id))
|
||||||
return "openchamber.token." + hex.EncodeToString(sum[:12])
|
return "openchamber.token." + hex.EncodeToString(sum[:12])
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Persistent) LoadToken(server string) (string, bool, error) {
|
// legacyTokenKey is where earlier versions kept a token: by server URL.
|
||||||
return secure.Get(p.tokenKey(server))
|
func legacyTokenKey(url string) string {
|
||||||
|
sum := sha256.Sum256([]byte(url))
|
||||||
|
return "openchamber.token." + hex.EncodeToString(sum[:12])
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Persistent) SaveToken(server, token string) error {
|
func (p *Persistent) LoadToken(c Connection) (string, bool, error) {
|
||||||
return secure.Set(p.tokenKey(server), token)
|
if tok, ok, err := secure.Get(p.tokenKey(c.ID)); err != nil || ok {
|
||||||
|
return tok, ok, err
|
||||||
|
}
|
||||||
|
// A connection migrated from the single-server record keeps its token
|
||||||
|
// under the old URL-based key.
|
||||||
|
return secure.Get(legacyTokenKey(c.URL))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Persistent) ClearToken(server string) error {
|
func (p *Persistent) SaveToken(id, token string) error {
|
||||||
return secure.Delete(p.tokenKey(server))
|
return secure.Set(p.tokenKey(id), token)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *Persistent) ClearToken(c Connection) error {
|
||||||
|
err := secure.Delete(p.tokenKey(c.ID))
|
||||||
|
_ = secure.Delete(legacyTokenKey(c.URL))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func newID() string {
|
||||||
|
var b [8]byte
|
||||||
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
|
return "srv_" + hex.EncodeToString(b[:4])
|
||||||
|
}
|
||||||
|
return "srv_" + hex.EncodeToString(b[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewID returns a fresh connection id.
|
||||||
|
func NewID() string { return newID() }
|
||||||
Reference in new issue
Block a user