gui: Bark push target for every alert, and a daily spend summary (EV_John_Liu on X)
Settings > Usage has a Bark row: a server (default https://api.day.app, or
a self-hosted one) and the device key, then Test and Remove. Every alert
that goes through notifier.sendAs (allowance, balance, reset reminder, task
done, masking, sign-in) is also pushed to Bark when a key is set, whether or
not the system lets this computer notify. A second row, once a key is set,
turns on a daily summary at a time of day: today's cost and request count,
and each window or balance near its cap (the Allowance alert's share, else
80%), capped at 8 lines. It is pushed once a day (a restart does not resend;
a failed push is retried every 15 minutes; one more than 6 hours late is
left), in the page's language (en, zh, zh-TW, ja, de).
The device key is a key: the page only gets barkKeySet, never the key; it has
its own route (POST /api/settings/bark, key omitted keeps it, "" removes it),
a Settings save carries it (settingsapi.Merge), and a backup or sync without
keys leaves it out and keeps this machine's. No log line or error names it
(the Bark client replaces it with "..." in what the server or client says).
bark.js is a lazy module so app.js (budget) gains one line.
Run (mote, at the pushed tree before the rebase onto 6d7862769):
- go test ./internal/bark ./internal/settings ./internal/settingsapi
./internal/backup ./internal/davsync ./internal/provider: ok.
- go test -run 'Bark|AlertsGoTo|GitHubToken' ./internal/gui: ok. go vet
darwin, GOOS=linux -tags nogui and GOOS=windows over gui, bark, settings:
clean. gofmt -l: clean.
- GUI: bark.test.cjs (5 languages x 900/380px x chromium/webkit), i18n-keys,
i18n-en-no-cjk, usage-alert: pass. Whole GUI suite started; reds so far are
in account/agent/checkin tests that do not touch Settings or Bark, filed
separately after this tag; old-webkit's Safari 15.0 :has() is #5919.
- All against fake servers; nothing reaches the network.
Broken by hand, each went red: no barkPush in sendAs
(TestAlertsGoToBark), BarkKeySet forced true / key shown (TestBarkSettingAndTest),
no same-day check in the daily step (TestBarkDailyStep).
Not tried: a real Bark device or the real api.day.app; win-run and wsl-run
(vet only for those OSes); a self-hosted Bark server.
This commit is contained in:
@@ -248,6 +248,7 @@ func Collect(keys bool, app string) (Bundle, error) {
|
||||
s.LANKey, s.LANKeyID = "", ""
|
||||
s.OTel.Headers = nil
|
||||
s.GitHubToken = ""
|
||||
s.BarkKey = ""
|
||||
}
|
||||
b.Settings = &s
|
||||
}
|
||||
@@ -489,6 +490,7 @@ func Restore(b Bundle, parts Parts) (Result, error) {
|
||||
if !keys {
|
||||
s.LANKey, s.LANKeyID = cur.LANKey, cur.LANKeyID
|
||||
s.GitHubToken = cur.GitHubToken
|
||||
s.BarkKey = cur.BarkKey
|
||||
s.OTel.Headers = nil
|
||||
if strings.TrimRight(strings.TrimSpace(s.OTel.Endpoint), "/") == cur.OTel.Endpoint {
|
||||
s.OTel.Headers = cur.OTel.Headers
|
||||
|
||||
@@ -266,6 +266,41 @@ func TestGitHubTokenBackup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Bark's device key is a key too (EV_John_Liu on X): a backup without keys
|
||||
// leaves it out, and restoring one keeps the key this machine has.
|
||||
func TestBarkKeyBackup(t *testing.T) {
|
||||
home(t)
|
||||
if err := settings.Save(settings.Settings{BarkKey: "bark_local_key", BarkServer: "https://bark.example.com", Theme: "dark"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, keys := range []bool{false, true} {
|
||||
b, err := Collect(keys, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := Seal(b, "pw")
|
||||
if got := strings.Contains(string(mustOpen(t, data)), "bark_local_key"); got != keys {
|
||||
t.Fatalf("keys %v: the Bark key is in the backup: %v", keys, got)
|
||||
}
|
||||
}
|
||||
for _, keys := range []bool{false, true} {
|
||||
incoming := settings.Settings{Theme: "light"}
|
||||
if keys {
|
||||
incoming.BarkKey = "bark_incoming_key"
|
||||
}
|
||||
if err := settings.Save(settings.Settings{BarkKey: "bark_local_key"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Restore(Bundle{Version: 1, Keys: keys, Settings: &incoming}, Parts{Settings: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[bool]string{false: "bark_local_key", true: "bark_incoming_key"}[keys]
|
||||
if got := settings.Load(); got.BarkKey != want {
|
||||
t.Errorf("keys %v: restored key %q, want %q", keys, got.BarkKey, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mustOpen(t *testing.T, data []byte) []byte {
|
||||
t.Helper()
|
||||
b, err := Open(data, "pw")
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// Package bark pushes a message to the iOS Bark app (bark.day.app): one
|
||||
// POST of JSON to the server's /push, with the device key in the body, so
|
||||
// a key never sits in an address that a log, a proxy or an error names.
|
||||
// The server is Bark's own, https://api.day.app, or a self-hosted one.
|
||||
package bark
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
)
|
||||
|
||||
// DefaultServer is the Bark app's own server, used when none is set.
|
||||
const DefaultServer = "https://api.day.app"
|
||||
|
||||
// Target is where a push goes: Server ("" is DefaultServer) and the device
|
||||
// key the Bark app shows.
|
||||
type Target struct {
|
||||
Server, Key string
|
||||
}
|
||||
|
||||
// On is whether there is a device key to push to.
|
||||
func (t Target) On() bool { return strings.TrimSpace(t.Key) != "" }
|
||||
|
||||
func (t Target) url() string {
|
||||
s := strings.TrimRight(strings.TrimSpace(t.Server), "/")
|
||||
if s == "" {
|
||||
s = DefaultServer
|
||||
}
|
||||
return s + "/push"
|
||||
}
|
||||
|
||||
// client follows the app's proxy, as its other requests to the Internet do;
|
||||
// a var for tests.
|
||||
var client = &http.Client{Timeout: 15 * time.Second, Transport: proxied()}
|
||||
|
||||
func proxied() http.RoundTripper {
|
||||
t := http.DefaultTransport.(*http.Transport).Clone()
|
||||
t.Proxy = netproxy.Func
|
||||
return netproxy.Dispatch(t)
|
||||
}
|
||||
|
||||
// group names the pushes in the Bark app's list.
|
||||
const group = "magpie"
|
||||
|
||||
// Push sends title and body to t. The error names the server's answer,
|
||||
// never the device key.
|
||||
func Push(ctx context.Context, t Target, title, body string) error {
|
||||
if !t.On() {
|
||||
return errors.New("no Bark device key is set")
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
"device_key": strings.TrimSpace(t.Key),
|
||||
"title": title,
|
||||
"body": body,
|
||||
"group": group,
|
||||
})
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", t.url(), bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return errors.New("the Bark server's address can't be used")
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
// the client's error names the address, which holds no key
|
||||
return fmt.Errorf("Bark server: %s", strings.ReplaceAll(err.Error(), strings.TrimSpace(t.Key), "…"))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
var reply struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
json.Unmarshal(raw, &reply)
|
||||
if resp.StatusCode/100 == 2 && (reply.Code == 0 || reply.Code == 200) {
|
||||
return nil
|
||||
}
|
||||
say := strings.TrimSpace(reply.Message)
|
||||
if say == "" {
|
||||
say = http.StatusText(resp.StatusCode)
|
||||
}
|
||||
// a server may say the key back
|
||||
say = strings.ReplaceAll(say, strings.TrimSpace(t.Key), "…")
|
||||
return fmt.Errorf("Bark server answered %d: %s", resp.StatusCode, say)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package bark
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fake is a Bark server: it records each push and answers as Bark does.
|
||||
type fake struct {
|
||||
mu sync.Mutex
|
||||
got []map[string]any
|
||||
urls []string
|
||||
code int
|
||||
say string
|
||||
*httptest.Server
|
||||
}
|
||||
|
||||
func newFake(t *testing.T, code int, say string) *fake {
|
||||
f := &fake{code: code, say: say}
|
||||
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var m map[string]any
|
||||
json.Unmarshal(b, &m)
|
||||
f.mu.Lock()
|
||||
f.got, f.urls = append(f.got, m), append(f.urls, r.Method+" "+r.URL.String())
|
||||
f.mu.Unlock()
|
||||
w.WriteHeader(f.code)
|
||||
io.WriteString(w, f.say)
|
||||
}))
|
||||
t.Cleanup(f.Close)
|
||||
old := client
|
||||
client = &http.Client{} // the test's own: never the system proxy, never the network
|
||||
t.Cleanup(func() { client = old })
|
||||
return f
|
||||
}
|
||||
|
||||
func TestPushPostsJSONAndNeverPutsTheKeyInTheAddress(t *testing.T) {
|
||||
f := newFake(t, 200, `{"code":200,"message":"success"}`)
|
||||
if err := Push(context.Background(), Target{Server: f.URL + "/", Key: " SECRETKEY123 "}, "Title", "Body"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(f.got) != 1 || f.urls[0] != "POST /push" {
|
||||
t.Fatalf("requests %v", f.urls)
|
||||
}
|
||||
m := f.got[0]
|
||||
if m["device_key"] != "SECRETKEY123" || m["title"] != "Title" || m["body"] != "Body" || m["group"] != "magpie" {
|
||||
t.Fatalf("body %v", m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushRefusalNamesNeitherKey(t *testing.T) {
|
||||
f := newFake(t, 400, `{"code":400,"message":"failed to get device token: SECRETKEY123 not found"}`)
|
||||
err := Push(context.Background(), Target{Server: f.URL, Key: "SECRETKEY123"}, "t", "b")
|
||||
if err == nil || !strings.Contains(err.Error(), "400") {
|
||||
t.Fatalf("err %v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "SECRETKEY123") {
|
||||
t.Fatalf("the error says the key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushNeedsAKeyAndFailedConnectionsSayNoKey(t *testing.T) {
|
||||
if err := Push(context.Background(), Target{Server: "http://127.0.0.1:1"}, "t", "b"); err == nil {
|
||||
t.Fatal("pushed with no key")
|
||||
}
|
||||
old := client
|
||||
client = &http.Client{} // port 1 on this computer: refused, nothing leaves it
|
||||
t.Cleanup(func() { client = old })
|
||||
err := Push(context.Background(), Target{Server: "http://127.0.0.1:1/SECRETKEY123", Key: "SECRETKEY123"}, "t", "b")
|
||||
if err == nil || strings.Contains(err.Error(), "SECRETKEY123") {
|
||||
t.Fatalf("err %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultServer(t *testing.T) {
|
||||
if got := (Target{Key: "k"}).url(); got != "https://api.day.app/push" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := (Target{Server: " https://bark.example.com/ ", Key: "k"}).url(); got != "https://bark.example.com/push" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
@@ -1018,6 +1018,7 @@ func take(to *backup.Bundle, from backup.Bundle, part string) {
|
||||
copy := *s
|
||||
copy.LANKey, copy.LANKeyID = to.Settings.LANKey, to.Settings.LANKeyID
|
||||
copy.GitHubToken = to.Settings.GitHubToken
|
||||
copy.BarkKey = to.Settings.BarkKey
|
||||
copy.OTel.Headers = nil
|
||||
if strings.TrimRight(strings.TrimSpace(copy.OTel.Endpoint), "/") == to.Settings.OTel.Endpoint {
|
||||
copy.OTel.Headers = to.Settings.OTel.Headers
|
||||
|
||||
@@ -78,7 +78,7 @@ func TestGatewayKeysTakeSettings(t *testing.T) {
|
||||
func TestGatewayKeysKeylessSettings(t *testing.T) {
|
||||
for _, sameEndpoint := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "different collector", true: "same collector"}[sameEndpoint], func(t *testing.T) {
|
||||
cur := settings.Settings{Theme: "dark", LANKey: "fixture-lan", LANKeyID: "default", GitHubToken: "fixture-github"}
|
||||
cur := settings.Settings{Theme: "dark", LANKey: "fixture-lan", LANKeyID: "default", GitHubToken: "fixture-github", BarkKey: "fixture-bark"}
|
||||
cur.OTel = settings.OTel{Endpoint: "https://collector.example.com", Headers: map[string]string{"Authorization": "fixture-otel"}}
|
||||
from := settings.Settings{Theme: "light"}
|
||||
from.OTel.Endpoint = "https://different.example.com"
|
||||
@@ -89,7 +89,7 @@ func TestGatewayKeysKeylessSettings(t *testing.T) {
|
||||
to := backup.Bundle{Keys: true, Settings: &cur, GatewayKeys: keys}
|
||||
take(&to, backup.Bundle{Settings: &from}, "settings")
|
||||
got := to.Settings
|
||||
if got.Theme != "light" || got.LANKey != cur.LANKey || got.LANKeyID != cur.LANKeyID || got.GitHubToken != cur.GitHubToken || !reflect.DeepEqual(to.GatewayKeys, keys) || !to.Keys {
|
||||
if got.Theme != "light" || got.LANKey != cur.LANKey || got.LANKeyID != cur.LANKeyID || got.GitHubToken != cur.GitHubToken || got.BarkKey != cur.BarkKey || !reflect.DeepEqual(to.GatewayKeys, keys) || !to.Keys {
|
||||
t.Error("a keyless theme upload erased credentials already on the server")
|
||||
}
|
||||
if sameEndpoint && !reflect.DeepEqual(got.OTel.Headers, cur.OTel.Headers) {
|
||||
@@ -98,7 +98,7 @@ func TestGatewayKeysKeylessSettings(t *testing.T) {
|
||||
if !sameEndpoint && len(got.OTel.Headers) != 0 {
|
||||
t.Error("a different collector received the old collector's credentials")
|
||||
}
|
||||
if from.GitHubToken != "" || from.LANKey != "" || from.OTel.Headers != nil {
|
||||
if from.GitHubToken != "" || from.BarkKey != "" || from.LANKey != "" || from.OTel.Headers != nil {
|
||||
t.Error("merging modified the keyless source bundle")
|
||||
}
|
||||
})
|
||||
|
||||
@@ -34,6 +34,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/applog"
|
||||
"github.com/yetone/magpie/internal/autostart"
|
||||
"github.com/yetone/magpie/internal/bark"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/fonts"
|
||||
@@ -549,6 +550,8 @@ type settingsJSON struct {
|
||||
// the token set in Settings was refused by GitHub (401): it is still
|
||||
// shown, masked, while requests go without a token (#3926)
|
||||
GitHubTokenRefused bool `json:"githubTokenRefused,omitempty"`
|
||||
// whether a Bark device key is set; never the key (EV_John_Liu on X)
|
||||
BarkKeySet bool `json:"barkKeySet,omitempty"`
|
||||
// where other machines reach the gateway while it is shared
|
||||
LANURLs []string `json:"lanURLs,omitempty"`
|
||||
// LANURLs are a container's own addresses, not the host's: the page
|
||||
@@ -842,6 +845,7 @@ func settingsState() settingsJSON {
|
||||
s.GatewayOn, s.GatewayWhy = gatewayMode(s.Web)
|
||||
s.GatewayPaused = pausedNow()
|
||||
s.LANKey = "" // the retained credential belongs on disk, not in UI state
|
||||
s.BarkKeySet, s.BarkKey = strings.TrimSpace(s.BarkKey) != "", ""
|
||||
// the GitHub token, masked, and where the library's requests take one
|
||||
// from: Settings, or the environment variable named
|
||||
own := strings.TrimSpace(s.GitHubToken)
|
||||
@@ -2721,6 +2725,56 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// the Bark target every alert also goes to, and the time of the daily
|
||||
// summary (EV_John_Liu on X). A field left out stays; the key, "" takes it
|
||||
// away. The key is written and never read back by the page.
|
||||
mux.HandleFunc("POST /api/settings/bark", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Server *string `json:"server"`
|
||||
Key *string `json:"key"`
|
||||
Daily *string `json:"daily"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
s := settings.Load()
|
||||
if in.Server != nil {
|
||||
s.BarkServer = *in.Server
|
||||
}
|
||||
if in.Key != nil {
|
||||
s.BarkKey = *in.Key
|
||||
}
|
||||
if in.Daily != nil {
|
||||
s.BarkDaily = *in.Daily
|
||||
}
|
||||
if err := settings.CheckBark(s.BarkServer, s.BarkKey, s.BarkDaily); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if err := settings.Save(s); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// a push to the saved Bark target, to see that it arrives
|
||||
mux.HandleFunc("POST /api/bark/test", func(rw http.ResponseWriter, r *http.Request) {
|
||||
s := settings.Load()
|
||||
t := barkTarget(s)
|
||||
if !t.On() {
|
||||
fail(rw, fmt.Errorf("no Bark device key is set"))
|
||||
return
|
||||
}
|
||||
title, body := barkTestText(trayLang(s.Lang, systemLang))
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||
defer cancel()
|
||||
if err := bark.Push(ctx, t, title, body); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, map[string]bool{"ok": true})
|
||||
})
|
||||
// the GitHub download mirror updates come through (#893), the same
|
||||
// setting `magpie update mirror` sets: a full https:// prefix, or ""
|
||||
// for GitHub itself. The feed and its checksums are never the mirror's.
|
||||
|
||||
@@ -4131,6 +4131,9 @@ input.words.remote-key { width: 160px; }
|
||||
.warm-at.times > :not(.warm-times) { flex: none; }
|
||||
.warm-at .warm-times { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px 8px; min-width: 0; }
|
||||
.warm-at .warm-time { display: inline-flex; align-items: center; gap: 2px; }
|
||||
.bark-box { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; margin-left: auto; min-width: 0; max-width: 100%; }
|
||||
.bark-box input.words { width: 180px; }
|
||||
.bark-box code { font-size: 12.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; max-width: 220px; }
|
||||
.warm-at .warm-rm, .warm-at .warm-add { min-width: 24px; height: 27px; padding: 0 6px; font-size: 14px; line-height: 1; }
|
||||
.row.pref .sub .warn { color: var(--amber); }
|
||||
.row.pref .sub.wraps { white-space: normal; }
|
||||
|
||||
@@ -21110,6 +21110,7 @@ function renderAlerts(s, keep) {
|
||||
const turnOpts = [["0", t("Off")], ...mins.map((m) => [String(m * 60), t("{n} min", { n: m })])];
|
||||
if (d && !mins.some((m) => m * 60 === d)) turnOpts.push([String(d), d % 60 ? t("{n} s", { n: d }) : t("{n} min", { n: d / 60 })]);
|
||||
$("#turnDoneSegs").replaceChildren(segs(turnOpts, String(d), (v) => savePrefs({ ...keep, turnDoneAlert: Number(v) })));
|
||||
window.barkPaint ? barkPaint(s) : import("./bark.js").then(() => barkPaint(prefs || s), statusErr);
|
||||
}
|
||||
|
||||
// AGENT_PREFS: an agent's own settings rows, by its id (openAgentPrefs)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Settings › Usage's Bark rows (EV_John_Liu on X): the server and device key
|
||||
// every alert also goes to, and a daily summary. app.js imports this when
|
||||
// renderSettings draws them (renderBark), so it weighs nothing on the core.
|
||||
// The page never has the key back: it is written here, and settings tell
|
||||
// only that one is set.
|
||||
|
||||
let barkDraft = { server: "", key: "" };
|
||||
|
||||
window.barkPaint = function (s) {
|
||||
const box = $("#barkBox");
|
||||
const set = !!s.barkKeySet;
|
||||
const save = (body, done) => writingPrefs(api("settings/bark", body))
|
||||
.then((ns) => { prefs = ns; if (state) state.settings = ns; if (done) barkDraft = { server: "", key: "" }; renderSettings(); status(t("Saved"), "ok", 1500); })
|
||||
.catch((e) => statusTErr(e));
|
||||
box.replaceChildren();
|
||||
if (set) {
|
||||
const server = el("code", "bark-server", (s.barkServer || "https://api.day.app").replace(/^https?:\/\//, ""));
|
||||
server.title = s.barkServer || "https://api.day.app";
|
||||
const test = el("button", "text bark-test", t("Test"));
|
||||
test.onclick = () => {
|
||||
test.disabled = true;
|
||||
api("bark/test", {}).then(() => status(t("Sent to Bark"), "ok", 1500), statusTErr).finally(() => { test.disabled = false; });
|
||||
};
|
||||
const x = el("button", "text bark-remove", t("Remove"));
|
||||
x.onclick = () => save({ key: "", daily: "" });
|
||||
box.append(server, el("code", "bark-key", "••••••••"), test, x);
|
||||
} else {
|
||||
const srv = input(barkDraft.server, "https://api.day.app", "url");
|
||||
srv.className = "words bark-server-input";
|
||||
srv.setAttribute("aria-label", t("Server"));
|
||||
srv.oninput = () => { barkDraft.server = srv.value; };
|
||||
const key = input(barkDraft.key, t("Device key"), "password");
|
||||
key.className = "words bark-key-input";
|
||||
key.setAttribute("aria-label", t("Device key"));
|
||||
key.oninput = () => { barkDraft.key = key.value; };
|
||||
const go = el("button", "text bark-save", t("Save"));
|
||||
go.onclick = () => {
|
||||
if (!key.value.trim()) return key.focus();
|
||||
save({ server: srv.value.trim(), key: key.value.trim() }, true);
|
||||
};
|
||||
for (const i of [srv, key]) i.addEventListener("keydown", (e) => { if (e.key === "Enter") go.onclick(); });
|
||||
box.append(srv, key, go);
|
||||
}
|
||||
// the daily summary, with its time of day, once there is a key
|
||||
$("#barkDailyRow").hidden = !set;
|
||||
const daily = $("#barkDailySegs");
|
||||
daily.replaceChildren();
|
||||
if (!set) return;
|
||||
const at = s.barkDaily || "";
|
||||
if (at) {
|
||||
const i = input(at, "21:00", "time");
|
||||
i.className = "at";
|
||||
i.setAttribute("aria-label", t("Time of day"));
|
||||
blurOnEnter(i);
|
||||
i.onchange = () => { if (i.value && i.value !== at) save({ daily: i.value }); };
|
||||
daily.append(i);
|
||||
}
|
||||
daily.append(segs([["off", t("Off")], ["on", t("On")]], at ? "on" : "off", (v) => save({ daily: v === "on" ? "21:00" : "" })));
|
||||
};
|
||||
@@ -1380,6 +1380,11 @@ const I18N = {
|
||||
"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "每周或每月窗口用量不到 85% 即将重置时,或重置卡将过期未用时,提前这么久通知",
|
||||
"{n} h before": "提前 {n} 小时",
|
||||
"Task done alert": "任务完成提醒",
|
||||
"Bark": "Bark",
|
||||
"Bark daily summary": "Bark 每日汇总",
|
||||
"Server": "服务器",
|
||||
"Device key": "设备密钥",
|
||||
"Sent to Bark": "已发送到 Bark",
|
||||
"Masking alert": "脱敏提醒",
|
||||
"A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "首次脱敏某个值时通知:只说类型和个数,从不显示值本身",
|
||||
"A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Claude Code、Codex、OpenCode 等经由 magpie 的智能体完成一个至少跑了这么久的任务时通知",
|
||||
@@ -6368,6 +6373,11 @@ const I18N = {
|
||||
"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "每週或每月時段用量不到 85% 即將重置時,或重置卡將過期未用時,提前這麼久通知",
|
||||
"{n} h before": "提前 {n} 小時",
|
||||
"Task done alert": "任務完成提醒",
|
||||
"Bark": "Bark",
|
||||
"Bark daily summary": "Bark 每日彙總",
|
||||
"Server": "伺服器",
|
||||
"Device key": "裝置金鑰",
|
||||
"Sent to Bark": "已傳送到 Bark",
|
||||
"Masking alert": "脫敏提醒",
|
||||
"A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "首次脫敏某個值時通知:只說類型和個數,從不顯示值本身",
|
||||
"A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Claude Code、Codex、OpenCode 等經由 magpie 的智慧體完成一個至少跑了這麼久的任務時通知",
|
||||
@@ -11317,6 +11327,11 @@ const I18N = {
|
||||
"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "週間・月間の枠が 85% 未満の使用でリセットされる前、または未使用のリセットが期限切れになる前に、この時間だけ早く通知します",
|
||||
"{n} h before": "{n} 時間前",
|
||||
"Task done alert": "タスク完了通知",
|
||||
"Bark": "Bark",
|
||||
"Bark daily summary": "Bark の毎日のまとめ",
|
||||
"Server": "サーバー",
|
||||
"Device key": "デバイスキー",
|
||||
"Sent to Bark": "Bark に送信しました",
|
||||
"Masking alert": "マスク通知",
|
||||
"A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "値を初めてマスクしたときに通知:種類と件数だけで、値そのものは表示しません",
|
||||
"A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Claude Code、Codex、OpenCode など magpie を通るエージェントが、少なくともこの時間かかったタスクを終えたときに通知",
|
||||
@@ -16301,6 +16316,11 @@ const I18N = {
|
||||
"A notification this long before a weekly or monthly window renews with under 85% of it used, or before unused resets expire": "Eine Benachrichtigung so lange bevor ein wöchentliches oder monatliches Fenster mit unter 85 % Verbrauch erneuert wird oder ungenutzte Resets verfallen",
|
||||
"{n} h before": "{n} Std. vorher",
|
||||
"Task done alert": "Benachrichtigung bei fertiger Aufgabe",
|
||||
"Bark": "Bark",
|
||||
"Bark daily summary": "Bark-Tagesübersicht",
|
||||
"Server": "Server",
|
||||
"Device key": "Geräteschlüssel",
|
||||
"Sent to Bark": "An Bark gesendet",
|
||||
"Masking alert": "Benachrichtigung beim Maskieren",
|
||||
"A notification when masking swaps a value for the first time: its kind and how many, never the value itself": "Eine Benachrichtigung, wenn ein Wert zum ersten Mal maskiert wird: Art und Anzahl, nie der Wert selbst",
|
||||
"A notification when Claude Code, Codex, OpenCode or another agent going through magpie finishes a task that ran at least this long": "Eine Benachrichtigung, wenn Claude Code, Codex, OpenCode oder ein anderer Agent über magpie eine Aufgabe beendet, die mindestens so lange lief",
|
||||
|
||||
@@ -335,6 +335,14 @@
|
||||
<div class="who"><div class="name" data-t>Task done alert</div><div class="sub" id="turnDoneSub"></div></div>
|
||||
<div id="turnDoneSegs"></div>
|
||||
</div>
|
||||
<div class="row pref" id="barkRow">
|
||||
<div class="who"><div class="name" data-t>Bark</div></div>
|
||||
<div id="barkBox" class="bark-box"></div>
|
||||
</div>
|
||||
<div class="row pref" id="barkDailyRow" hidden>
|
||||
<div class="who"><div class="name" data-t>Bark daily summary</div></div>
|
||||
<div id="barkDailySegs" class="warm-at"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="set-page" id="setPage-network" role="tabpanel" aria-labelledby="setTab-network">
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/bark"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// barkLate is how long after its time of day a summary is still pushed: a
|
||||
// computer asleep then sends it on waking, and one woken the next evening
|
||||
// leaves the day be.
|
||||
const barkLate = 6 * time.Hour
|
||||
|
||||
// barkRetry is how long a push that failed waits before it is tried again.
|
||||
const barkRetry = 15 * time.Minute
|
||||
|
||||
// barkTarget is where Settings sends pushes, and whether anywhere.
|
||||
func barkTarget(s settings.Settings) bark.Target {
|
||||
return bark.Target{Server: s.BarkServer, Key: s.BarkKey}
|
||||
}
|
||||
|
||||
// barkPush sends one alert's words to Bark when it is set, without making
|
||||
// the alert wait for it. The key is never logged.
|
||||
func barkPush(title, body string) {
|
||||
t := barkTarget(settings.Load())
|
||||
if !t.On() {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
if err := bark.Push(ctx, t, title, body); err != nil {
|
||||
log.Println("bark:", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// barkDaily keeps the day the summary was last pushed, in memory and in a
|
||||
// file beside the alerts' marks, so a restart doesn't push it again.
|
||||
type barkDaily struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
sent string
|
||||
retryAt time.Time
|
||||
}
|
||||
|
||||
func (d *barkDaily) lastDay() string {
|
||||
if d.sent != "" {
|
||||
return d.sent
|
||||
}
|
||||
var m struct {
|
||||
Day string `json:"day"`
|
||||
}
|
||||
if b, err := os.ReadFile(d.path); err == nil {
|
||||
json.Unmarshal(b, &m)
|
||||
}
|
||||
return m.Day
|
||||
}
|
||||
|
||||
// step pushes the day's summary when it is due at now: Settings has a key
|
||||
// and a time, the time has come and is not more than barkLate past, and none
|
||||
// was pushed today. A failed push is asked again after barkRetry, and a
|
||||
// summary that can't be pushed in barkLate is left. It reports whether it
|
||||
// pushed.
|
||||
func (d *barkDaily) step(now time.Time, s settings.Settings, build func() (string, string), send func(title, body string) error) bool {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if !barkTarget(s).On() || s.BarkDaily == "" {
|
||||
return false
|
||||
}
|
||||
h, m, ok := settings.Clock(s.BarkDaily)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
y, mo, dd := now.Date()
|
||||
at := time.Date(y, mo, dd, h, m, 0, 0, now.Location())
|
||||
day := now.Format("2006-01-02")
|
||||
if now.Before(at) || now.Sub(at) > barkLate || d.lastDay() == day || now.Before(d.retryAt) {
|
||||
return false
|
||||
}
|
||||
title, body := build()
|
||||
if err := send(title, body); err != nil {
|
||||
log.Println("bark:", err)
|
||||
d.retryAt = now.Add(barkRetry)
|
||||
return false
|
||||
}
|
||||
d.sent = day
|
||||
if b, err := json.Marshal(map[string]string{"day": day}); err == nil {
|
||||
os.MkdirAll(filepath.Dir(d.path), 0o755)
|
||||
os.WriteFile(d.path, append(b, '\n'), 0o600)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// barkSummary reads today's spend and the allowances now, and says them.
|
||||
func barkSummary(ctx context.Context, now time.Time) (title, body string) {
|
||||
s := settings.Load()
|
||||
cx, cancel := context.WithTimeout(ctx, time.Minute)
|
||||
qs := provider.Quotas(cx)
|
||||
cancel()
|
||||
pct := s.UsageAlert
|
||||
if pct <= 0 {
|
||||
pct = barkNearPct
|
||||
}
|
||||
currency, rate := trayCurrency()
|
||||
return barkDailyText(trayLang(s.Lang, systemLang), trayTotalSum(usage.Today), currency, rate,
|
||||
provider.NearLimits(qs, pct, s.BalanceAlert, now), s.BalanceAlert, s.QuotaLeft, now)
|
||||
}
|
||||
|
||||
// watchBarkDaily pushes the daily summary at the time Settings names, until
|
||||
// ctx ends.
|
||||
func watchBarkDaily(ctx context.Context) {
|
||||
d := &barkDaily{path: filepath.Join(settings.Dir(), "bark-daily.json")}
|
||||
t := time.NewTicker(time.Minute)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case now := <-t.C:
|
||||
d.step(now, settings.Load(), func() (string, string) { return barkSummary(ctx, now) }, func(title, body string) error {
|
||||
cx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
return bark.Push(cx, barkTarget(settings.Load()), title, body)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//go:build !nogui
|
||||
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
func barkSandbox(t *testing.T) {
|
||||
t.Helper()
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))
|
||||
}
|
||||
|
||||
// fakeBark is a Bark server that keeps what it was sent.
|
||||
type fakeBark struct {
|
||||
mu sync.Mutex
|
||||
pushes []map[string]string
|
||||
*httptest.Server
|
||||
}
|
||||
|
||||
func newFakeBark(t *testing.T) *fakeBark {
|
||||
f := &fakeBark{}
|
||||
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var m map[string]string
|
||||
json.Unmarshal(b, &m)
|
||||
f.mu.Lock()
|
||||
f.pushes = append(f.pushes, m)
|
||||
f.mu.Unlock()
|
||||
w.Write([]byte(`{"code":200,"message":"success"}`))
|
||||
}))
|
||||
t.Cleanup(f.Close)
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeBark) got() []map[string]string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]map[string]string(nil), f.pushes...)
|
||||
}
|
||||
|
||||
// Settings' Bark target is saved with its key kept away from the page, the
|
||||
// test button pushes to it, and a save of the Settings page keeps it.
|
||||
func TestBarkSettingAndTest(t *testing.T) {
|
||||
barkSandbox(t)
|
||||
fake := newFakeBark(t)
|
||||
const key = "AbCdEf123456secretkey"
|
||||
call := func(method, path, body string) (int, string) {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
|
||||
return rec.Code, rec.Body.String()
|
||||
}
|
||||
if code, _ := call("POST", "/api/bark/test", ""); code == http.StatusOK {
|
||||
t.Fatal("a test with no key pushed")
|
||||
}
|
||||
code, body := call("POST", "/api/settings/bark", `{"server":"`+fake.URL+`/","key":" `+key+` ","daily":"21:30"}`)
|
||||
s := settings.Load()
|
||||
if code != http.StatusOK || s.BarkKey != key || s.BarkServer != fake.URL || s.BarkDaily != "21:30" {
|
||||
t.Fatalf("set: %d %s, saved %+v", code, body, s)
|
||||
}
|
||||
if strings.Contains(body, key) || !strings.Contains(body, `"barkKeySet":true`) {
|
||||
t.Errorf("the page was told %s", body)
|
||||
}
|
||||
if code, body = call("GET", "/api/settings", ""); strings.Contains(body, key) || !strings.Contains(body, `"barkKeySet":true`) {
|
||||
t.Errorf("GET /api/settings: %d %s", code, body)
|
||||
}
|
||||
// a Settings save and a server-only change keep the key
|
||||
if code, body = call("POST", "/api/settings", `{"theme":"dark","barkKey":""}`); code != http.StatusOK || settings.Load().BarkKey != key {
|
||||
t.Fatalf("save: %d %s, key %q", code, body, settings.Load().BarkKey)
|
||||
}
|
||||
if code, _ = call("POST", "/api/settings/bark", `{"daily":""}`); code != http.StatusOK || settings.Load().BarkKey != key || settings.Load().BarkDaily != "" {
|
||||
t.Fatalf("daily off: %d, %+v", code, settings.Load())
|
||||
}
|
||||
if code, _ = call("POST", "/api/settings/bark", `{"key":"two words"}`); code == http.StatusOK || settings.Load().BarkKey != key {
|
||||
t.Errorf("a key with a space was taken: %d", code)
|
||||
}
|
||||
code, body = call("POST", "/api/bark/test", "")
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("test: %d %s", code, body)
|
||||
}
|
||||
p := fake.got()
|
||||
if len(p) != 1 || p[0]["device_key"] != key || p[0]["body"] == "" {
|
||||
t.Errorf("the fake was sent %v", p)
|
||||
}
|
||||
if code, body = call("POST", "/api/settings/bark", `{"key":""}`); code != http.StatusOK || settings.Load().BarkKey != "" || strings.Contains(body, `"barkKeySet"`) {
|
||||
t.Errorf("remove: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
// Every alert goes to Bark when it is set, and to nothing when it is not.
|
||||
func TestAlertsGoToBark(t *testing.T) {
|
||||
barkSandbox(t)
|
||||
fake := newFakeBark(t)
|
||||
// the system side is out of reach, as it is where notifications are off
|
||||
n := ¬ifier{err: errors.New("no notifications here")}
|
||||
n.once.Do(func() {})
|
||||
n.send("title", "body")
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if p := fake.got(); len(p) != 0 {
|
||||
t.Fatalf("pushed with no Bark set: %v", p)
|
||||
}
|
||||
s := settings.Load()
|
||||
s.BarkServer, s.BarkKey = fake.URL, "k1"
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n.send("Allowance", "Claude 5h is at 90%")
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for len(fake.got()) == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
p := fake.got()
|
||||
if len(p) != 1 || p[0]["title"] != "Allowance" || p[0]["body"] != "Claude 5h is at 90%" {
|
||||
t.Errorf("the fake was sent %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
// The daily summary is pushed once, at its time and not before, not again
|
||||
// after a restart, retried after a failure, and left when it is too late.
|
||||
func TestBarkDailyStep(t *testing.T) {
|
||||
barkSandbox(t)
|
||||
d := &barkDaily{path: filepath.Join(t.TempDir(), "bark-daily.json")}
|
||||
s := settings.Settings{BarkKey: "k", BarkDaily: "21:00"}
|
||||
day := time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC)
|
||||
var sent int
|
||||
build := func() (string, string) { return "t", "b" }
|
||||
ok := func(string, string) error { sent++; return nil }
|
||||
step := func(at time.Time, s settings.Settings, send func(string, string) error) bool {
|
||||
return d.step(at, s, build, send)
|
||||
}
|
||||
if step(day.Add(20*time.Hour), s, ok) || sent != 0 {
|
||||
t.Fatal("pushed before its time")
|
||||
}
|
||||
if !step(day.Add(21*time.Hour+time.Minute), s, ok) || sent != 1 {
|
||||
t.Fatal("not pushed at its time")
|
||||
}
|
||||
if step(day.Add(22*time.Hour), s, ok) {
|
||||
t.Fatal("pushed twice in a day")
|
||||
}
|
||||
// a restart reads the day from the file
|
||||
d2 := &barkDaily{path: d.path}
|
||||
if d2.step(day.Add(22*time.Hour), s, build, ok) || sent != 1 {
|
||||
t.Fatal("pushed again after a restart")
|
||||
}
|
||||
// tomorrow: a failure waits, then retries
|
||||
next := day.Add(24 * time.Hour)
|
||||
bad := func(string, string) error { return errors.New("down") }
|
||||
if step(next.Add(21*time.Hour), s, bad) {
|
||||
t.Fatal("a failed push counted")
|
||||
}
|
||||
if step(next.Add(21*time.Hour+5*time.Minute), s, ok) || sent != 1 {
|
||||
t.Fatal("retried before the pause")
|
||||
}
|
||||
if !step(next.Add(21*time.Hour+20*time.Minute), s, ok) || sent != 2 {
|
||||
t.Fatal("not retried after the pause")
|
||||
}
|
||||
// too late, off, no key
|
||||
late := next.Add(24 * time.Hour)
|
||||
if step(late.Add(21*time.Hour+barkLate+time.Minute), s, ok) {
|
||||
t.Fatal("pushed a summary that was a day late")
|
||||
}
|
||||
if step(late.Add(21*time.Hour), settings.Settings{BarkKey: "k"}, ok) || step(late.Add(21*time.Hour), settings.Settings{BarkDaily: "21:00"}, ok) {
|
||||
t.Fatal("pushed while off")
|
||||
}
|
||||
}
|
||||
|
||||
// The summary says what today cost and the allowances near their end, in
|
||||
// the page's language, and caps the list.
|
||||
func TestBarkDailyText(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 21, 0, 0, 0, time.UTC)
|
||||
reset := now.Add(2 * time.Hour)
|
||||
var near []provider.QuotaAlert
|
||||
for i := 0; i < 10; i++ {
|
||||
near = append(near, provider.QuotaAlert{Provider: "claude", Name: "Claude", Window: "5h", Used: 91, ResetsAt: &reset})
|
||||
}
|
||||
title, body := barkDailyText("en", usage.Totals{Calls: 12, Cost: 3.5}, "usd", 0, near[:2], 0, false, now)
|
||||
if title == "" || !strings.Contains(body, "$3.50") || !strings.Contains(body, "12 requests") || strings.Count(body, "\n· ") != 2 {
|
||||
t.Errorf("en: %q %q", title, body)
|
||||
}
|
||||
_, body = barkDailyText("en", usage.Totals{Calls: 12, Cost: 3.5, Unpriced: 1}, "usd", 0, nil, 0, false, now)
|
||||
if !strings.Contains(body, "$3.50+") || !strings.Contains(body, "No allowance is near") {
|
||||
t.Errorf("unpriced: %q", body)
|
||||
}
|
||||
_, body = barkDailyText("zh", usage.Totals{}, "usd", 0, near, 0, false, now)
|
||||
if !strings.Contains(body, "今天还没有请求") || !strings.Contains(body, "另有 2 项") || strings.Count(body, "\n· ") != barkNearMax {
|
||||
t.Errorf("zh: %q", body)
|
||||
}
|
||||
for lang, w := range barkWords {
|
||||
for k := range barkWords["en"] {
|
||||
if w[k] == "" {
|
||||
t.Errorf("%s misses %s", lang, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// barkNearPct is the share of a window the daily summary calls near its end
|
||||
// when Settings' Allowance alert is off (with it on, its own share).
|
||||
const barkNearPct = 80
|
||||
|
||||
// barkNearMax is how many near-limit lines a push carries before "and N
|
||||
// more": a push is read on a lock screen.
|
||||
const barkNearMax = 8
|
||||
|
||||
// barkWords is the daily summary's and the test push's words, in the
|
||||
// languages the notifications speak. %s is an amount, %d a count.
|
||||
var barkWords = map[string]map[string]string{
|
||||
"en": {
|
||||
"title": "magpie · today", "spent": "Spent about %s today · %d requests", "calls": "%d requests today",
|
||||
"none": "No requests yet today", "near": "Near the limit:", "clear": "No allowance is near its limit.",
|
||||
"more": "…and %d more", "test": "Bark is set up: alerts and the daily summary come here.",
|
||||
},
|
||||
"zh": {
|
||||
"title": "magpie · 今日", "spent": "今日约花费 %s · %d 次请求", "calls": "今日 %d 次请求",
|
||||
"none": "今天还没有请求", "near": "额度快用完:", "clear": "没有额度接近上限。",
|
||||
"more": "…另有 %d 项", "test": "Bark 已接通:提醒和每日汇总会发到这里。",
|
||||
},
|
||||
"zh-TW": {
|
||||
"title": "magpie · 今日", "spent": "今日約花費 %s · %d 次請求", "calls": "今日 %d 次請求",
|
||||
"none": "今天還沒有請求", "near": "額度快用完:", "clear": "沒有額度接近上限。",
|
||||
"more": "…另有 %d 項", "test": "Bark 已接通:提醒和每日彙總會發到這裡。",
|
||||
},
|
||||
"ja": {
|
||||
"title": "magpie · 今日", "spent": "今日の支出は約 %s · %d リクエスト", "calls": "今日 %d リクエスト",
|
||||
"none": "今日はまだリクエストがありません", "near": "上限が近い枠:", "clear": "上限に近い枠はありません。",
|
||||
"more": "…ほか %d 件", "test": "Bark につながりました。通知と毎日のまとめがここに届きます。",
|
||||
},
|
||||
"de": {
|
||||
"title": "magpie · heute", "spent": "Heute etwa %s ausgegeben · %d Anfragen", "calls": "%d Anfragen heute",
|
||||
"none": "Heute noch keine Anfragen", "near": "Nahe am Limit:", "clear": "Kein Kontingent ist nahe am Limit.",
|
||||
"more": "…und %d weitere", "test": "Bark ist eingerichtet: Hinweise und die tägliche Übersicht kommen hierher.",
|
||||
},
|
||||
}
|
||||
|
||||
func barkWord(lang, key string, args ...any) string {
|
||||
s, ok := barkWords[lang][key]
|
||||
if !ok {
|
||||
s = barkWords["en"][key]
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf(s, args...)
|
||||
}
|
||||
|
||||
// barkTestText is the push Settings' Test sends.
|
||||
func barkTestText(lang string) (title, body string) {
|
||||
return "magpie", barkWord(lang, "test")
|
||||
}
|
||||
|
||||
// barkDailyText is the once-a-day push (EV_John_Liu on X): what today cost
|
||||
// and the windows and balances near their end, each as its alert would say
|
||||
// it. near is what provider.NearLimits found, bal the balance alert's line.
|
||||
func barkDailyText(lang string, today usage.Totals, currency string, rate float64, near []provider.QuotaAlert, bal float64, left bool, now time.Time) (title, body string) {
|
||||
var lines []string
|
||||
switch {
|
||||
case today.Calls == 0:
|
||||
lines = append(lines, barkWord(lang, "none"))
|
||||
case today.Cost > 0:
|
||||
c := usage.FormatCost(today.Cost, currency, rate)
|
||||
if today.Unpriced > 0 {
|
||||
c += "+"
|
||||
}
|
||||
lines = append(lines, barkWord(lang, "spent", c, today.Calls))
|
||||
default:
|
||||
lines = append(lines, barkWord(lang, "calls", today.Calls))
|
||||
}
|
||||
if len(near) == 0 {
|
||||
lines = append(lines, barkWord(lang, "clear"))
|
||||
} else {
|
||||
lines = append(lines, barkWord(lang, "near"))
|
||||
for i, a := range near {
|
||||
if i == barkNearMax {
|
||||
lines = append(lines, barkWord(lang, "more", len(near)-i))
|
||||
break
|
||||
}
|
||||
t, b := alertText(lang, a, bal, left, now)
|
||||
lines = append(lines, "· "+t+": "+b)
|
||||
}
|
||||
}
|
||||
return barkWord(lang, "title"), strings.Join(lines, "\n")
|
||||
}
|
||||
@@ -103,6 +103,9 @@ const (
|
||||
func (n *notifier) send(title, body string) { n.sendAs("magpie-alert-", title, body) }
|
||||
|
||||
func (n *notifier) sendAs(kind, title, body string) {
|
||||
// every alert goes to Bark too, when it is set, whether or not the
|
||||
// system lets this computer notify (EV_John_Liu on X)
|
||||
barkPush(title, body)
|
||||
if !n.allowed() {
|
||||
return
|
||||
}
|
||||
@@ -196,6 +199,7 @@ func (h *host) watchAlerts() {
|
||||
// an account in use signed out, or a Claude sign-in about to end
|
||||
// (steven_4422 on Discord): always on, as the account's Sign in
|
||||
// again is
|
||||
go watchBarkDaily(backendCtx)
|
||||
go provider.WatchSignIns(backendCtx, func(a provider.SignInAlert) {
|
||||
title, body := signInText(trayLang(settings.Load().Lang, systemLang), a, time.Now())
|
||||
n.sendAs(signInKind(a.Provider), title, body)
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Bark (EV_John_Liu on X): Settings › Usage has a Bark row, where a server
|
||||
// and a device key are saved, and a daily summary beside it once a key is
|
||||
// set. The page never has the key back: after it is saved only dots show,
|
||||
// and the key is in no text of the page. Test pushes, Remove takes the key
|
||||
// and the summary away. Every language, wide and narrow, both engines; the
|
||||
// API is faked here, and nothing reaches the network.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const KEY = "AbCdEf123456secretkey";
|
||||
|
||||
function server(lang, posts) {
|
||||
const fixed = {
|
||||
theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", dock: false, dockWindow: false, proxy: "",
|
||||
redact: true, redactPersonal: false, redactWords: [], codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "",
|
||||
trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "", version: "0.1.900", dir: "~/.config/magpie",
|
||||
gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], lanURLs: [],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, turnDoneAlert: 0, featuresOff: [],
|
||||
};
|
||||
let cur = fixed;
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false,featuresOff:[]};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: fixed.fx });
|
||||
if (url.pathname === "/api/settings/bark") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push({ path: "bark", ...body });
|
||||
const next = { ...cur };
|
||||
if ("server" in body) next.barkServer = body.server;
|
||||
if ("key" in body) next.barkKeySet = !!body.key;
|
||||
if ("daily" in body) next.barkDaily = body.daily;
|
||||
if (!next.barkKeySet) { delete next.barkKeySet; delete next.barkDaily; }
|
||||
cur = next;
|
||||
return json(cur); // never the key
|
||||
}
|
||||
if (url.pathname === "/api/bark/test") { posts.push({ path: "test" }); return json({ ok: true }); }
|
||||
if (url.pathname === "/api/settings") {
|
||||
if (req.method() === "POST") { posts.push({ path: "settings", ...req.postDataJSON() }); cur = { ...cur, ...req.postDataJSON() }; }
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { name: "Bark", daily: "Bark daily summary", key: "Device key", test: "Test", save: "Save", remove: "Remove", off: "Off", on: "On", sent: "Sent to Bark" },
|
||||
zh: { name: "Bark", daily: "Bark 每日汇总", key: "设备密钥", test: "测试", save: "保存", remove: "移除", off: "关闭", on: "开启", sent: "已发送到 Bark" },
|
||||
"zh-TW": { name: "Bark", daily: "Bark 每日彙總", key: "裝置金鑰", test: "測試", save: "儲存", remove: "移除", off: "關閉", on: "開啟", sent: "已傳送到 Bark" },
|
||||
ja: { name: "Bark", daily: "Bark の毎日のまとめ", key: "デバイスキー", test: "テスト", save: "保存", remove: "削除", off: "オフ", on: "オン", sent: "Bark に送信しました" },
|
||||
de: { name: "Bark", daily: "Bark-Tagesübersicht", key: "Geräteschlüssel", test: "Testen", save: "Speichern", remove: "Entfernen", off: "Aus", on: "An", sent: "An Bark gesendet" },
|
||||
};
|
||||
|
||||
async function open(engine, width, lang, posts, t) {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-bark.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posts));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=settings&tab=usage");
|
||||
await settingsDrawn(page);
|
||||
return { page, errors };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
for (const width of [900, 380]) {
|
||||
test(`${engine} ${lang} ${width}px: Bark is set, tried, given a daily summary and removed in Settings › Usage`, async (t) => {
|
||||
const posts = [];
|
||||
const { page, errors } = await open(engine, width, lang, posts, t);
|
||||
const w = words[lang];
|
||||
const posted = async (n) => { for (let i = 0; i < 100 && posts.length < n; i++) await page.waitForTimeout(20); assert.equal(posts.length, n, "posts " + JSON.stringify(posts)); return posts[n - 1]; };
|
||||
const keyField = page.locator("#barkBox input[type=password]");
|
||||
await keyField.waitFor();
|
||||
|
||||
assert.equal((await page.locator("#barkRow .name").textContent()).trim(), w.name);
|
||||
assert.equal(await keyField.getAttribute("placeholder"), w.key);
|
||||
assert.equal(await page.locator("#barkDailyRow").isHidden(), true, "no summary without a key");
|
||||
assert.equal(await page.locator("#barkRow").count(), 1, "one row");
|
||||
|
||||
// no key, nothing saved
|
||||
await reach(page, page.locator("#barkBox .bark-save"));
|
||||
assert.equal((await page.locator("#barkBox .bark-save").textContent()).trim(), w.save);
|
||||
await page.locator("#barkBox .bark-save").click();
|
||||
await page.waitForTimeout(150);
|
||||
assert.equal(posts.length, 0, "saved with no key");
|
||||
|
||||
const scrolled = () => page.locator("#view-settings").evaluate((v) => v.scrollTop);
|
||||
await page.locator("#barkBox .bark-server-input").fill("https://bark.example.com");
|
||||
await keyField.fill(KEY);
|
||||
const top = await scrolled();
|
||||
await page.locator("#barkBox .bark-save").click();
|
||||
const first = await posted(1);
|
||||
assert.deepEqual(first, { path: "bark", server: "https://bark.example.com", key: KEY });
|
||||
|
||||
// the key is written and never shown: dots, Test and Remove
|
||||
await page.locator("#barkBox .bark-key").waitFor();
|
||||
assert.equal((await page.locator("#barkBox .bark-key").textContent()).trim(), "••••••••");
|
||||
assert.equal(await page.locator("#barkBox input").count(), 0, "no field left");
|
||||
const all = await page.evaluate(() => document.documentElement.outerHTML + JSON.stringify([...document.querySelectorAll("input")].map((i) => i.value)));
|
||||
assert.ok(!all.includes(KEY), "the key is in the page");
|
||||
assert.equal(await scrolled(), top, "the click moved the page");
|
||||
assert.equal((await page.locator("#barkBox .bark-server").textContent()).trim(), "bark.example.com");
|
||||
assert.deepEqual(await page.locator("#barkBox button").allTextContents(), [w.test, w.remove]);
|
||||
|
||||
// the daily summary appears, Off until turned on
|
||||
await page.locator("#barkDailyRow").waitFor({ state: "visible" });
|
||||
assert.equal((await page.locator("#barkDailyRow .name").textContent()).trim(), w.daily);
|
||||
const opts = page.locator("#barkDailySegs .opt");
|
||||
assert.deepEqual(await opts.allTextContents(), [w.off, w.on]);
|
||||
assert.equal(await page.locator("#barkDailySegs .opt.on").textContent(), w.off);
|
||||
await reach(page, opts.nth(1));
|
||||
await opts.nth(1).click();
|
||||
assert.deepEqual(await posted(2), { path: "bark", daily: "21:00" });
|
||||
await page.locator("#barkDailySegs input.at").waitFor();
|
||||
assert.equal(await page.locator("#barkDailySegs input.at").inputValue(), "21:00");
|
||||
await page.locator("#barkDailySegs input.at").fill("07:45");
|
||||
await page.locator("#barkDailySegs input.at").blur();
|
||||
assert.deepEqual(await posted(3), { path: "bark", daily: "07:45" });
|
||||
|
||||
// Test pushes, and says so
|
||||
await page.locator("#barkBox .bark-test").click();
|
||||
assert.deepEqual(await posted(4), { path: "test" });
|
||||
await page.getByText(w.sent).first().waitFor();
|
||||
|
||||
// Settings saved later keep the Bark rows
|
||||
const over = await page.evaluate(() => {
|
||||
const rows = [...document.querySelectorAll("#barkRow, #barkDailyRow")];
|
||||
return rows.flatMap((row) => { const r = row.getBoundingClientRect(); return [...row.querySelectorAll("*")].filter((e) => e.getBoundingClientRect().right > Math.max(r.right, innerWidth) + 1).map((e) => e.className || e.id); });
|
||||
});
|
||||
assert.deepEqual(over, [], "nothing past the edge");
|
||||
|
||||
await reach(page, page.locator("#barkBox .bark-remove"));
|
||||
await page.locator("#barkBox .bark-remove").click();
|
||||
assert.deepEqual(await posted(5), { path: "bark", key: "", daily: "" });
|
||||
await keyField.waitFor();
|
||||
assert.equal(await page.locator("#barkDailyRow").isHidden(), true, "no summary without a key");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
// pluginmd.js (a README's renderer) once plugins.js has run;
|
||||
// the checks above
|
||||
// still read them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
});
|
||||
|
||||
test("the styles hold up in Safari 15.0", async () => {
|
||||
|
||||
@@ -295,3 +295,12 @@ func WatchQuotas(ctx context.Context, wake <-chan struct{}, send func(QuotaAlert
|
||||
t.Reset(quotaAlertEvery)
|
||||
}
|
||||
}
|
||||
|
||||
// NearLimits is what the readings qs show now at or past the alert's share
|
||||
// of a window (pct, 0 is none) or at or under its balance (bal, 0 is none),
|
||||
// said or not: the daily summary's (EV_John_Liu on X), where the alerts
|
||||
// themselves go once, by their marks. A reading that failed, or is one kept
|
||||
// from before, says nothing.
|
||||
func NearLimits(qs []SubscriptionQuota, pct int, bal float64, now time.Time) []QuotaAlert {
|
||||
return dueAlerts(qs, map[string]alertMark{}, pct, bal, now)
|
||||
}
|
||||
|
||||
@@ -266,3 +266,23 @@ func TestDueReminders(t *testing.T) {
|
||||
t.Fatalf("failed reading: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// NearLimits (the Bark daily summary) lists every window at its share,
|
||||
// again each time it is asked, and leaves no marks behind for the alerts.
|
||||
func TestNearLimitsTellsEveryTime(t *testing.T) {
|
||||
now := time.Date(2026, 10, 1, 9, 0, 0, 0, time.UTC)
|
||||
reset := now.Add(3 * time.Hour)
|
||||
qs := []SubscriptionQuota{{Provider: "codex", Name: "Codex", Windows: []QuotaWindow{
|
||||
{Name: "5 hours", Used: 85, ResetsAt: &reset},
|
||||
{Name: "Weekly", Used: 10, ResetsAt: &reset},
|
||||
}}}
|
||||
for i := 0; i < 2; i++ {
|
||||
got := NearLimits(qs, 80, 0, now)
|
||||
if len(got) != 1 || got[0].Window != "5 hours" {
|
||||
t.Fatalf("ask %d: %+v", i, got)
|
||||
}
|
||||
}
|
||||
if got := NearLimits(qs, 0, 0, now); len(got) != 0 {
|
||||
t.Fatalf("off: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// normalBark is Bark's server, device key and daily time as they are kept:
|
||||
// trimmed, the server without a closing slash, the time as 09:00.
|
||||
func normalBark(server, key, daily string) (string, string, string) {
|
||||
server, key, daily = strings.TrimRight(strings.TrimSpace(server), "/"), strings.TrimSpace(key), strings.TrimSpace(daily)
|
||||
if h, m, ok := Clock(daily); ok {
|
||||
daily = fmt.Sprintf("%02d:%02d", h, m)
|
||||
}
|
||||
return server, key, daily
|
||||
}
|
||||
|
||||
// CheckBark says what is wrong with a Bark server ("" is the app's own,
|
||||
// https://api.day.app), device key and daily time ("" is off), or nil. The
|
||||
// key is never named in the error.
|
||||
func CheckBark(server, key, daily string) error {
|
||||
server, key, daily = normalBark(server, key, daily)
|
||||
if server != "" {
|
||||
u, err := url.Parse(server)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(server, " \t\r\n") {
|
||||
return errors.New("a Bark server is an http:// or https:// address, like https://api.day.app or https://bark.example.com")
|
||||
}
|
||||
}
|
||||
if strings.ContainsFunc(key, func(c rune) bool { return c <= ' ' || c == 0x7f || c == '/' || c == '?' || c == '#' || c == '%' }) {
|
||||
return errors.New("a Bark device key is the one word the app shows, with no spaces or slashes (not the whole push address)")
|
||||
}
|
||||
if daily != "" {
|
||||
if _, _, ok := Clock(daily); !ok {
|
||||
return fmt.Errorf("the daily summary's time of day must look like 21:00, not %q", daily)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCheckBark(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
server, key, daily string
|
||||
ok bool
|
||||
}{
|
||||
{"", "", "", true},
|
||||
{"", "AbC123", "21:00", true},
|
||||
{"https://bark.example.com/", "k", "9:05", true},
|
||||
{"http://192.168.1.5:8080", "k", "", true},
|
||||
{"bark.example.com", "k", "", false},
|
||||
{"ftp://x.example.com", "k", "", false},
|
||||
{"https://user:pw@x.example.com", "k", "", false},
|
||||
{"https://x.example.com/?a=1", "k", "", false},
|
||||
{"", "https://api.day.app/AbC123", "", false},
|
||||
{"", "two words", "", false},
|
||||
{"", "k", "25:00", false},
|
||||
{"", "k", "evening", false},
|
||||
} {
|
||||
err := CheckBark(c.server, c.key, c.daily)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("%+v: %v", c, err)
|
||||
}
|
||||
if err != nil && c.key != "" && strings.Contains(err.Error(), c.key) && len(c.key) > 3 {
|
||||
t.Errorf("the error names the key: %v", err)
|
||||
}
|
||||
}
|
||||
s, k, d := normalBark(" https://bark.example.com/ ", " k ", "9:05")
|
||||
if s != "https://bark.example.com" || k != "k" || d != "09:05" {
|
||||
t.Errorf("normal: %q %q %q", s, k, d)
|
||||
}
|
||||
}
|
||||
@@ -721,6 +721,17 @@ type Settings struct {
|
||||
// never the value, a burst said once and at most once a minute. Only
|
||||
// requests the app's own gateway serves; off until turned on.
|
||||
MaskAlert bool `json:"maskAlert,omitempty"`
|
||||
// BarkServer and BarkKey are where every alert above is also sent as a
|
||||
// push to the iOS Bark app (EV_John_Liu on X): the server ("" is
|
||||
// https://api.day.app, or a self-hosted Bark server's address) and the
|
||||
// device key the app shows. The key is a secret: the Settings page is
|
||||
// told only that one is set, and a backup or sync without keys leaves
|
||||
// it out, as it does GitHubToken. BarkDaily is the time of day, "HH:MM",
|
||||
// a summary is pushed once a day: what today cost and the allowances
|
||||
// near their end; "" is off.
|
||||
BarkServer string `json:"barkServer,omitempty"`
|
||||
BarkKey string `json:"barkKey,omitempty"`
|
||||
BarkDaily string `json:"barkDaily,omitempty"`
|
||||
// PlainNames has the model lists magpie gives agents name each model
|
||||
// by its name alone, without its provider's or "routing group" after it
|
||||
// (#335) — but for two in one list that would read the same, which keep
|
||||
@@ -2350,6 +2361,9 @@ func saveOwn(s Settings, recording, reads bool) error {
|
||||
if s.TurnDoneAlert < 0 || s.TurnDoneAlert > 86400 {
|
||||
return fmt.Errorf("a turn is said done after 1 to 86400 seconds, or 0 for off, not %d", s.TurnDoneAlert)
|
||||
}
|
||||
if err := CheckBark(s.BarkServer, s.BarkKey, s.BarkDaily); err != nil {
|
||||
return err
|
||||
}
|
||||
if math.IsNaN(s.BalanceAlert) || math.IsInf(s.BalanceAlert, 0) || s.BalanceAlert < 0 {
|
||||
return fmt.Errorf("a balance alert is at an amount of 0 or more (0 for off), not %v", s.BalanceAlert)
|
||||
}
|
||||
@@ -2627,6 +2641,7 @@ func (s Settings) normal() Settings {
|
||||
if h, m, ok := Clock(s.CheckinAt); ok {
|
||||
s.CheckinAt = fmt.Sprintf("%02d:%02d", h, m)
|
||||
}
|
||||
s.BarkServer, s.BarkKey, s.BarkDaily = normalBark(s.BarkServer, s.BarkKey, s.BarkDaily)
|
||||
// a reply's model name: memberModel, as a magpie before replyModel
|
||||
// kept it, when replyModel isn't set, and kept beside it for that
|
||||
// magpie
|
||||
|
||||
@@ -283,6 +283,9 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
|
||||
settings.CarryPerModel(&in, &cur)
|
||||
in.LAN, in.LANKey = cur.LAN, cur.LANKey
|
||||
in.LANKeyID = cur.LANKeyID
|
||||
// Bark has its own route (bark); the page never sees its key
|
||||
in.BarkServer, in.BarkKey, in.BarkDaily = cur.BarkServer, cur.BarkKey, cur.BarkDaily
|
||||
|
||||
in.Port = cur.Port // set on its own (port), which moves the gateway
|
||||
in.CORSOrigins = cur.CORSOrigins // set on its own (cors)
|
||||
in.AllowIPs = cur.AllowIPs // set on its own (allowips)
|
||||
|
||||
Reference in New Issue
Block a user