881 lines
26 KiB
Go
881 lines
26 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.asio.asia/TapRemly/desktop/agent/internal/account"
|
|
"git.asio.asia/TapRemly/desktop/agent/internal/engine"
|
|
"git.asio.asia/TapRemly/desktop/agent/internal/idutil"
|
|
"git.asio.asia/TapRemly/desktop/agent/internal/protocol"
|
|
"git.asio.asia/TapRemly/desktop/agent/internal/store"
|
|
nixmsg "git.asio.asia/nixevol/NixMsg/sdk/go"
|
|
)
|
|
|
|
func (a *App) routes() http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /v1/status", a.authed(a.handleStatus))
|
|
mux.HandleFunc("POST /v1/stop", a.authed(a.handleStop))
|
|
mux.HandleFunc("PUT /v1/settings", a.authed(a.handlePutSettings))
|
|
mux.HandleFunc("POST /v1/session", a.authed(a.handleLogin))
|
|
mux.HandleFunc("POST /v1/session/reconnect", a.authed(a.handleReconnect))
|
|
mux.HandleFunc("DELETE /v1/session", a.authed(a.handleLogout))
|
|
mux.HandleFunc("POST /v1/account/login", a.authed(a.handleAccountLogin))
|
|
mux.HandleFunc("DELETE /v1/account", a.authed(a.handleAccountLogout))
|
|
mux.HandleFunc("GET /v1/devices", a.authed(a.handleDevices))
|
|
mux.HandleFunc("POST /v1/devices", a.authed(a.handleAddDevice))
|
|
mux.HandleFunc("PATCH /v1/devices/{id}", a.authed(a.handlePatchDevice))
|
|
mux.HandleFunc("DELETE /v1/devices/{id}", a.authed(a.handleDeleteDevice))
|
|
mux.HandleFunc("GET /v1/groups", a.authed(a.handleGroups))
|
|
mux.HandleFunc("POST /v1/groups", a.authed(a.handleCreateGroup))
|
|
mux.HandleFunc("PATCH /v1/groups/{id}", a.authed(a.handleRenameGroup))
|
|
mux.HandleFunc("DELETE /v1/groups/{id}", a.authed(a.handleDeleteGroup))
|
|
mux.HandleFunc("GET /v1/trust", a.authed(a.handleTrustList))
|
|
mux.HandleFunc("POST /v1/trust", a.authed(a.handleTrustAdd))
|
|
mux.HandleFunc("DELETE /v1/trust/{id}", a.authed(a.handleTrustRemove))
|
|
mux.HandleFunc("GET /v1/shortcuts/local", a.authed(a.handleLocalList))
|
|
mux.HandleFunc("POST /v1/shortcuts/local", a.authed(a.handleLocalSave))
|
|
mux.HandleFunc("PATCH /v1/shortcuts/local/{id}", a.authed(a.handleLocalUpdate))
|
|
mux.HandleFunc("DELETE /v1/shortcuts/local/{id}", a.authed(a.handleLocalDelete))
|
|
mux.HandleFunc("POST /v1/shortcuts/copy", a.authed(a.handleCopy))
|
|
mux.HandleFunc("GET /v1/shortcuts/remote", a.authed(a.handleRemoteList))
|
|
mux.HandleFunc("POST /v1/shortcuts/remote/refresh", a.authed(a.handleRemoteRefresh))
|
|
mux.HandleFunc("GET /v1/shortcuts/published", a.authed(a.handlePublishedList))
|
|
mux.HandleFunc("POST /v1/shortcuts/published", a.authed(a.handlePublishedSave))
|
|
mux.HandleFunc("PATCH /v1/shortcuts/published/{id}", a.authed(a.handlePublishedUpdate))
|
|
mux.HandleFunc("DELETE /v1/shortcuts/published/{id}", a.authed(a.handlePublishedDelete))
|
|
mux.HandleFunc("POST /v1/send", a.authed(a.handleSend))
|
|
mux.HandleFunc("GET /v1/inbox", a.authed(a.handleInbox))
|
|
mux.HandleFunc("POST /v1/inbox/read", a.authed(a.handleInboxRead))
|
|
mux.HandleFunc("GET /v1/results", a.authed(a.handleResults))
|
|
mux.HandleFunc("GET /v1/logs", a.authed(a.handleLocalLogs))
|
|
mux.HandleFunc("GET /v1/logs/remote", a.authed(a.handleRemoteLogs))
|
|
mux.HandleFunc("POST /v1/logs/fetch", a.authed(a.handleFetchLogs))
|
|
return mux
|
|
}
|
|
|
|
func (a *App) authed(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
h := r.Header.Get("Authorization")
|
|
const prefix = "Bearer "
|
|
a.mu.Lock()
|
|
token := a.token
|
|
a.mu.Unlock()
|
|
if len(h) <= len(prefix) || h[:len(prefix)] != prefix || token == "" || subtleEqual(h[len(prefix):], token) != 1 {
|
|
writeErr(w, http.StatusUnauthorized, "请先连接")
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
func subtleEqual(a, b string) int {
|
|
if len(a) != len(b) {
|
|
return 0
|
|
}
|
|
var v byte
|
|
for i := 0; i < len(a); i++ {
|
|
v |= a[i] ^ b[i]
|
|
}
|
|
if v == 0 {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func (a *App) handleStatus(w http.ResponseWriter, _ *http.Request) {
|
|
var endpoint, server, nix, user, session string
|
|
var hasToken bool
|
|
a.st.View(func(d *store.Data) {
|
|
endpoint, server, nix, user, session = d.EndpointID, d.ServerURL, d.NixURL, d.AccountUser, d.SessionToken
|
|
hasToken = d.DeviceToken != ""
|
|
})
|
|
a.mu.Lock()
|
|
state, text := a.connState, a.connText
|
|
a.mu.Unlock()
|
|
if text == "" {
|
|
text = "未连接"
|
|
}
|
|
lim := a.limits()
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"running": true,
|
|
"conn": state,
|
|
"conn_text": text,
|
|
"endpoint_id": endpoint,
|
|
"logged_in": session != "",
|
|
"server_url": server,
|
|
"nixmsg_url": nix,
|
|
"account_user": user,
|
|
"has_device_token": hasToken,
|
|
"max_ttl_seconds": limOr(lim.MaxTTL, 2592000),
|
|
"max_schedule_seconds": limOr(lim.MaxSchedule, 31536000),
|
|
})
|
|
}
|
|
|
|
func limOr(v, def int64) int64 {
|
|
if v > 0 {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
func (a *App) handleStop(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
go func() {
|
|
time.Sleep(80 * time.Millisecond)
|
|
a.requestStop()
|
|
}()
|
|
}
|
|
|
|
func (a *App) handlePutSettings(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
ServerURL string `json:"server_url"`
|
|
NixURL string `json:"nixmsg_url"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
req.ServerURL = strings.TrimRight(strings.TrimSpace(req.ServerURL), "/")
|
|
req.NixURL = strings.TrimSpace(req.NixURL)
|
|
if !validServer(req.ServerURL) || !validNix(req.NixURL) {
|
|
writeErr(w, http.StatusBadRequest, "地址不正确")
|
|
return
|
|
}
|
|
if err := a.st.Update(func(d *store.Data) error {
|
|
d.ServerURL = req.ServerURL
|
|
d.NixURL = req.NixURL
|
|
return nil
|
|
}); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
EndpointID string `json:"endpoint_id"`
|
|
Password string `json:"password"`
|
|
NixURL string `json:"nixmsg_url"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
req.EndpointID = strings.TrimSpace(req.EndpointID)
|
|
req.NixURL = strings.TrimSpace(req.NixURL)
|
|
if req.NixURL == "" {
|
|
a.st.View(func(d *store.Data) { req.NixURL = d.NixURL })
|
|
}
|
|
if !validNix(req.NixURL) {
|
|
writeErr(w, http.StatusBadRequest, "地址不正确")
|
|
return
|
|
}
|
|
if err := a.connect(req.NixURL, req.EndpointID, req.Password, ""); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "endpoint_id": req.EndpointID})
|
|
}
|
|
|
|
func (a *App) handleReconnect(w http.ResponseWriter, _ *http.Request) {
|
|
var url, id, session, pending string
|
|
a.st.View(func(d *store.Data) {
|
|
url, id, session, pending = d.NixURL, d.EndpointID, d.SessionToken, d.PendingSecret
|
|
})
|
|
if id == "" {
|
|
writeErr(w, http.StatusBadRequest, "请先登录")
|
|
return
|
|
}
|
|
var err error
|
|
switch {
|
|
case session != "":
|
|
err = a.connect(url, id, "", session)
|
|
case pending != "":
|
|
err = a.connect(url, id, pending, "")
|
|
default:
|
|
writeErr(w, http.StatusBadRequest, "请重新登录")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleLogout(w http.ResponseWriter, r *http.Request) {
|
|
a.mu.Lock()
|
|
c := a.client
|
|
a.mu.Unlock()
|
|
if c != nil {
|
|
ctx, cancel := contextTimeout(r)
|
|
_ = c.Logout(ctx)
|
|
cancel()
|
|
}
|
|
a.closeClient()
|
|
_ = a.st.Update(func(d *store.Data) error {
|
|
d.SessionToken = ""
|
|
d.PendingSecret = ""
|
|
return nil
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleAccountLogin(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
req.Username = strings.TrimSpace(req.Username)
|
|
if req.Username == "" || req.Password == "" {
|
|
writeErr(w, http.StatusBadRequest, "请填写账号和密码")
|
|
return
|
|
}
|
|
sess, err := a.session()
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
ctx, cancel := contextTimeout(r)
|
|
defer cancel()
|
|
name, err := sess.Login(ctx, req.Username, req.Password)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
if err := a.st.Update(func(d *store.Data) error {
|
|
d.AccountUser = name
|
|
d.Cookies = sess.Cookies()
|
|
return nil
|
|
}); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"username": name})
|
|
}
|
|
|
|
func (a *App) handleAccountLogout(w http.ResponseWriter, r *http.Request) {
|
|
if sess, err := a.session(); err == nil {
|
|
ctx, cancel := contextTimeout(r)
|
|
_ = sess.Logout(ctx)
|
|
cancel()
|
|
}
|
|
_ = a.st.Update(func(d *store.Data) error {
|
|
d.AccountUser = ""
|
|
d.Cookies = nil
|
|
return nil
|
|
})
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleDevices(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := a.accountSession()
|
|
if err != nil {
|
|
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
|
return
|
|
}
|
|
ctx, cancel := contextTimeout(r)
|
|
defer cancel()
|
|
list, err := sess.Devices(ctx)
|
|
_ = a.st.Update(func(d *store.Data) error {
|
|
d.Cookies = sess.Cookies()
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadGateway, publicErr(err))
|
|
return
|
|
}
|
|
a.rememberDevices(list)
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": a.decorate(list)})
|
|
}
|
|
|
|
func (a *App) handleGroups(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := a.accountSession()
|
|
if err != nil {
|
|
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
|
return
|
|
}
|
|
ctx, cancel := contextTimeout(r)
|
|
defer cancel()
|
|
list, err := sess.Groups(ctx)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadGateway, publicErr(err))
|
|
return
|
|
}
|
|
items := make([]map[string]string, 0, len(list))
|
|
for _, g := range list {
|
|
items = append(items, map[string]string{"id": g.ID, "name": g.Name})
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
|
}
|
|
|
|
func (a *App) handleCreateGroup(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil || !idutil.ValidName(req.Name) {
|
|
writeErr(w, http.StatusBadRequest, "请填写名称")
|
|
return
|
|
}
|
|
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
|
return sess.CreateGroup(ctx, strings.TrimSpace(req.Name))
|
|
})
|
|
}
|
|
|
|
func (a *App) handleRenameGroup(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil || !idutil.ValidName(req.Name) {
|
|
writeErr(w, http.StatusBadRequest, "请填写名称")
|
|
return
|
|
}
|
|
id := r.PathValue("id")
|
|
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
|
return sess.RenameGroup(ctx, id, strings.TrimSpace(req.Name))
|
|
})
|
|
}
|
|
|
|
func (a *App) handleDeleteGroup(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
|
return sess.DeleteGroup(ctx, id)
|
|
})
|
|
}
|
|
|
|
func (a *App) handleAddDevice(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
EndpointID string `json:"endpoint_id"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
req.Name = strings.TrimSpace(req.Name)
|
|
req.EndpointID = strings.TrimSpace(req.EndpointID)
|
|
if !idutil.ValidName(req.Name) {
|
|
writeErr(w, http.StatusBadRequest, "请填写名称")
|
|
return
|
|
}
|
|
if req.EndpointID != "" && !idutil.ValidEndpoint(req.EndpointID) {
|
|
writeErr(w, http.StatusBadRequest, "端编号不正确")
|
|
return
|
|
}
|
|
sess, err := a.accountSession()
|
|
if err != nil {
|
|
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
|
return
|
|
}
|
|
ctx, cancel := contextTimeout(r)
|
|
defer cancel()
|
|
prov, err := sess.AddDevice(ctx, req.Name, req.EndpointID)
|
|
_ = a.st.Update(func(d *store.Data) error {
|
|
d.Cookies = sess.Cookies()
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadGateway, publicErr(err))
|
|
return
|
|
}
|
|
if prov.DeviceToken != "" && req.EndpointID == "" {
|
|
_ = a.st.Update(func(d *store.Data) error {
|
|
d.DeviceToken = prov.DeviceToken
|
|
if prov.EndpointID != "" {
|
|
d.EndpointID = prov.EndpointID
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
if prov.Password != "" && prov.EndpointID != "" {
|
|
var nix string
|
|
a.st.View(func(d *store.Data) { nix = d.NixURL })
|
|
_ = a.connect(nix, prov.EndpointID, prov.Password, "")
|
|
}
|
|
id := prov.ID
|
|
if id == "" {
|
|
id = prov.EndpointID
|
|
}
|
|
name := prov.Name
|
|
if name == "" {
|
|
name = req.Name
|
|
}
|
|
ep := prov.EndpointID
|
|
if ep == "" {
|
|
ep = req.EndpointID
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"id": id, "name": name, "endpoint_id": ep})
|
|
}
|
|
|
|
func (a *App) handlePatchDevice(w http.ResponseWriter, r *http.Request) {
|
|
var raw map[string]json.RawMessage
|
|
if err := readJSON(r, &raw); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
var name, groupID *string
|
|
if b, ok := raw["name"]; ok {
|
|
var s string
|
|
if json.Unmarshal(b, &s) != nil || !idutil.ValidName(s) {
|
|
writeErr(w, http.StatusBadRequest, "请填写名称")
|
|
return
|
|
}
|
|
s = strings.TrimSpace(s)
|
|
name = &s
|
|
}
|
|
if b, ok := raw["group_id"]; ok {
|
|
var s string
|
|
if json.Unmarshal(b, &s) != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
groupID = &s
|
|
}
|
|
id := r.PathValue("id")
|
|
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
|
return sess.PatchDevice(ctx, id, name, groupID)
|
|
})
|
|
}
|
|
|
|
func (a *App) handleDeleteDevice(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
|
return sess.DeleteDevice(ctx, id)
|
|
})
|
|
}
|
|
|
|
func (a *App) handleTrustList(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": a.eng.TrustList()})
|
|
}
|
|
|
|
func (a *App) handleTrustAdd(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
EndpointID string `json:"endpoint_id"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
if err := a.eng.TrustAdd(req.EndpointID); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleTrustRemove(w http.ResponseWriter, r *http.Request) {
|
|
id, _ := url.PathUnescape(r.PathValue("id"))
|
|
if err := a.eng.TrustRemove(id); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleLocalList(w http.ResponseWriter, r *http.Request) {
|
|
remote := r.URL.Query().Get("remote")
|
|
items := a.eng.ListLocal(remote)
|
|
out := make([]map[string]any, 0, len(items))
|
|
for _, it := range items {
|
|
out = append(out, map[string]any{
|
|
"id": it.ID, "name": it.Name, "shell": it.Shell, "confirm": it.Confirm, "remote_id": it.RemoteID,
|
|
})
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": out})
|
|
}
|
|
|
|
func (a *App) handleLocalSave(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
RemoteID string `json:"remote_id"`
|
|
Name string `json:"name"`
|
|
Shell string `json:"shell"`
|
|
Confirm bool `json:"confirm"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
item, err := a.eng.SaveLocal(req.RemoteID, req.Name, req.Shell, req.Confirm)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, item)
|
|
}
|
|
|
|
func (a *App) handleLocalUpdate(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
Shell string `json:"shell"`
|
|
Confirm bool `json:"confirm"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
if err := a.eng.UpdateLocal(r.PathValue("id"), req.Name, req.Shell, req.Confirm); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleLocalDelete(w http.ResponseWriter, r *http.Request) {
|
|
if err := a.eng.DeleteLocal(r.PathValue("id")); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleCopy(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
RemoteID string `json:"remote_id"`
|
|
ShortcutID string `json:"shortcut_id"`
|
|
FromRemote bool `json:"from_remote"`
|
|
Targets []string `json:"targets"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
created, err := a.eng.CopyTo(req.RemoteID, req.ShortcutID, req.FromRemote, req.Targets)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": created})
|
|
}
|
|
|
|
func (a *App) handleRemoteList(w http.ResponseWriter, r *http.Request) {
|
|
remote := r.URL.Query().Get("remote")
|
|
c := a.eng.RemoteCache(remote)
|
|
synced := ""
|
|
if !c.SyncedAt.IsZero() {
|
|
synced = c.SyncedAt.UTC().Format(time.RFC3339)
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"items": c.Items, "synced_at": synced, "syncing": c.Syncing,
|
|
})
|
|
}
|
|
|
|
func (a *App) handleRemoteRefresh(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Remote string `json:"remote"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
if err := a.refreshShortcuts(req.Remote); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handlePublishedList(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": a.eng.Published()})
|
|
}
|
|
|
|
func (a *App) handlePublishedSave(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
Shell string `json:"shell"`
|
|
Confirm bool `json:"confirm"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
item, err := a.eng.SavePublished(req.Name, req.Shell, req.Confirm)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
go a.pushPublished()
|
|
writeJSON(w, http.StatusOK, item)
|
|
}
|
|
|
|
func (a *App) handlePublishedUpdate(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
Shell string `json:"shell"`
|
|
Confirm bool `json:"confirm"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
if err := a.eng.UpdatePublished(r.PathValue("id"), req.Name, req.Shell, req.Confirm); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
go a.pushPublished()
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handlePublishedDelete(w http.ResponseWriter, r *http.Request) {
|
|
if err := a.eng.DeletePublished(r.PathValue("id")); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
go a.pushPublished()
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleSend(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Remote string `json:"remote"`
|
|
Kind string `json:"kind"`
|
|
Shell string `json:"shell"`
|
|
Text string `json:"text"`
|
|
ShortcutID string `json:"shortcut_id"`
|
|
SendAtMs *int64 `json:"send_at_ms"`
|
|
Keep bool `json:"keep"`
|
|
TTLSeconds *int64 `json:"ttl_seconds"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
opt := engine.Delivery{Keep: req.Keep}
|
|
if req.Keep {
|
|
opt.TTL = req.TTLSeconds
|
|
}
|
|
if req.SendAtMs != nil && *req.SendAtMs > 0 {
|
|
t := time.UnixMilli(*req.SendAtMs)
|
|
opt.SendAt = &t
|
|
}
|
|
lim := a.limits()
|
|
var (
|
|
id string
|
|
body []byte
|
|
err error
|
|
)
|
|
switch req.Kind {
|
|
case "shell":
|
|
id, body, err = a.eng.SendShell(req.Remote, req.Shell, opt, lim)
|
|
case "text":
|
|
id, body, err = a.eng.SendText(req.Remote, req.Text, opt, lim)
|
|
case "remote":
|
|
id, body, err = a.eng.SendRemoteShortcut(req.Remote, req.ShortcutID, opt, lim)
|
|
case "local":
|
|
remote, script, _, lerr := a.eng.LocalShell(req.ShortcutID)
|
|
if lerr != nil {
|
|
err = lerr
|
|
break
|
|
}
|
|
id, body, err = a.eng.SendShell(remote, script, opt, lim)
|
|
req.Remote = remote
|
|
default:
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
if _, err := a.sendRaw(req.Remote, body, opt, true); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"id": id, "note": a.offlineNote(req.Remote, opt)})
|
|
}
|
|
|
|
func (a *App) offlineNote(remote string, opt engine.Delivery) string {
|
|
if opt.SendAt != nil && opt.SendAt.After(time.Now().Add(2*time.Second)) {
|
|
return "到时再发送"
|
|
}
|
|
if opt.Keep {
|
|
return ""
|
|
}
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
if a.connState == string(nixmsg.StateOnline) && a.presenceOK && !a.presence[remote] {
|
|
return "没有留下"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (a *App) handleInbox(w http.ResponseWriter, _ *http.Request) {
|
|
items := a.eng.Inbox()
|
|
out := make([]map[string]any, 0, len(items))
|
|
for _, it := range items {
|
|
out = append(out, map[string]any{
|
|
"id": it.ID, "from": it.From, "text": it.Text, "at": it.At.UTC().Format(time.RFC3339), "read": it.Read,
|
|
})
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": out})
|
|
}
|
|
|
|
func (a *App) handleInboxRead(w http.ResponseWriter, _ *http.Request) {
|
|
if err := a.eng.MarkInboxRead(); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) handleResults(w http.ResponseWriter, _ *http.Request) {
|
|
items := a.eng.Results()
|
|
out := make([]map[string]any, 0, len(items))
|
|
for _, it := range items {
|
|
out = append(out, map[string]any{
|
|
"id": it.ID, "remote": it.Remote, "ok": it.OK, "error": it.Error, "duplicate": it.Duplicate,
|
|
"at": it.At.UTC().Format(time.RFC3339),
|
|
})
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": out})
|
|
}
|
|
|
|
func (a *App) handleLocalLogs(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": a.eng.LocalLogs()})
|
|
}
|
|
|
|
func (a *App) handleRemoteLogs(w http.ResponseWriter, r *http.Request) {
|
|
remote := r.URL.Query().Get("remote")
|
|
c := a.eng.RemoteLogs(remote)
|
|
synced := ""
|
|
if !c.SyncedAt.IsZero() {
|
|
synced = c.SyncedAt.UTC().Format(time.RFC3339)
|
|
}
|
|
a.mu.Lock()
|
|
server := append([]protocol.Log(nil), a.serverLogs[remote]...)
|
|
a.mu.Unlock()
|
|
if server == nil {
|
|
server = []protocol.Log{}
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"items": c.Items, "synced_at": synced, "syncing": c.Syncing, "error": c.Error, "server_items": server,
|
|
})
|
|
}
|
|
|
|
func (a *App) handleFetchLogs(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Remote string `json:"remote"`
|
|
}
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "内容不正确")
|
|
return
|
|
}
|
|
if err := a.refreshLogs(req.Remote); err != nil {
|
|
writeErr(w, http.StatusBadRequest, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (a *App) decorate(list []account.Device) []map[string]any {
|
|
a.mu.Lock()
|
|
connected := a.connState == string(nixmsg.StateOnline)
|
|
ready := a.presenceOK
|
|
presence := a.presence
|
|
a.mu.Unlock()
|
|
out := make([]map[string]any, 0, len(list))
|
|
for _, d := range list {
|
|
p := "unknown"
|
|
if connected && ready {
|
|
if presence[d.EndpointID] {
|
|
p = "online"
|
|
} else {
|
|
p = "offline"
|
|
}
|
|
}
|
|
out = append(out, map[string]any{
|
|
"id": d.ID, "name": d.Name, "endpoint_id": d.EndpointID, "group_id": d.GroupID,
|
|
"online": p == "online", "presence": p,
|
|
})
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (a *App) accountSession() (*account.Session, error) {
|
|
var user string
|
|
a.st.View(func(d *store.Data) { user = d.AccountUser })
|
|
if user == "" {
|
|
return nil, engine.Error("请先登录账号")
|
|
}
|
|
return a.session()
|
|
}
|
|
|
|
func (a *App) withAccount(w http.ResponseWriter, r *http.Request, fn func(ctx context.Context, sess *account.Session) error) {
|
|
sess, err := a.accountSession()
|
|
if err != nil {
|
|
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
|
return
|
|
}
|
|
ctx, cancel := contextTimeout(r)
|
|
defer cancel()
|
|
err = fn(ctx, sess)
|
|
_ = a.st.Update(func(d *store.Data) error {
|
|
d.Cookies = sess.Cookies()
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadGateway, publicErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func contextTimeout(r *http.Request) (context.Context, context.CancelFunc) {
|
|
return context.WithTimeout(r.Context(), 20*time.Second)
|
|
}
|
|
|
|
func validServer(s string) bool {
|
|
u, err := url.Parse(s)
|
|
if err != nil || u.Host == "" {
|
|
return false
|
|
}
|
|
return u.Scheme == "http" || u.Scheme == "https"
|
|
}
|
|
|
|
func validNix(s string) bool {
|
|
u, err := url.Parse(s)
|
|
if err != nil || u.Host == "" {
|
|
return false
|
|
}
|
|
return u.Scheme == "ws" || u.Scheme == "wss"
|
|
}
|
|
|
|
func readJSON(r *http.Request, dst any) error {
|
|
dec := json.NewDecoder(http.MaxBytesReader(nil, r.Body, 1<<20))
|
|
return dec.Decode(dst)
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, code int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(code)
|
|
enc := json.NewEncoder(w)
|
|
enc.SetEscapeHTML(false)
|
|
_ = enc.Encode(v)
|
|
}
|
|
|
|
func writeErr(w http.ResponseWriter, code int, msg string) {
|
|
writeJSON(w, code, map[string]string{"error": msg})
|
|
}
|
|
|
|
func cors(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|