diff --git a/internal/lnbits/health.go b/internal/lnbits/health.go new file mode 100644 index 00000000..9ca6e630 --- /dev/null +++ b/internal/lnbits/health.go @@ -0,0 +1,180 @@ +package lnbits + +import ( + "context" + "net/http" + "sync" + "time" + + "github.com/imroc/req" + log "github.com/sirupsen/logrus" +) + +const ( + // requestTimeout bounds every LNbits call except payments, so users get a + // fast answer instead of a frozen bot when LNbits stops responding. + requestTimeout = 15 * time.Second + // paymentTimeout is long on purpose: a payment can take a while to settle + // and aborting it early would leave its outcome unknown. + paymentTimeout = 24 * time.Hour + // probeInterval is how often the background check pings LNbits. + probeInterval = 15 * time.Second + probeTimeout = 10 * time.Second +) + +// Health tracks whether LNbits is reachable. It is updated by every request +// the client makes and by a background probe, so the bot can show a +// maintenance message instead of wrong data (like a 0 balance) when LNbits +// is down. +type Health struct { + mu sync.RWMutex + down bool + downSince time.Time + lastErr string + // onChange is called on every switch between up and down, see + // Client.OnHealthChange. + onChange func(down bool, reason string, since time.Time) +} + +// Available reports whether LNbits is currently reachable. A nil Health is +// always available. +func (h *Health) Available() bool { + if h == nil { + return true + } + h.mu.RLock() + defer h.mu.RUnlock() + return !h.down +} + +func (h *Health) markDown(reason string) { + if h == nil { + return + } + h.mu.Lock() + defer h.mu.Unlock() + h.lastErr = reason + if h.down { + return + } + h.down = true + h.downSince = time.Now() + log.Errorf("[lnbits] LNbits is unreachable, entering maintenance mode: %s", reason) + if h.onChange != nil { + h.onChange(true, reason, h.downSince) + } +} + +func (h *Health) markUp() { + if h == nil { + return + } + h.mu.Lock() + defer h.mu.Unlock() + if !h.down { + return + } + log.Warnf("[lnbits] LNbits is reachable again after %s, leaving maintenance mode", time.Since(h.downSince).Round(time.Second)) + h.down = false + h.lastErr = "" + if h.onChange != nil { + h.onChange(false, "", h.downSince) + } +} + +// isOutageStatus reports whether an HTTP status means LNbits itself is down, +// as opposed to rejecting one request. 502/503/504 come from the reverse proxy +// in front of LNbits when LNbits does not answer. +func isOutageStatus(code int) bool { + return code == http.StatusBadGateway || + code == http.StatusServiceUnavailable || + code == http.StatusGatewayTimeout +} + +// healthTransport records the outcome of every LNbits request in Health. +// Connection errors, timeouts and gateway errors mark LNbits as down; any +// other response means LNbits answered, so it is up. +type healthTransport struct { + next http.RoundTripper + health *Health +} + +func (t *healthTransport) RoundTrip(r *http.Request) (*http.Response, error) { + resp, err := t.next.RoundTrip(r) + switch { + case err != nil: + t.health.markDown(err.Error()) + case isOutageStatus(resp.StatusCode): + t.health.markDown(resp.Status) + default: + t.health.markUp() + } + return resp, err +} + +// newHTTP returns a req instance whose requests are tracked by health. +func newHTTP(health *Health, timeout time.Duration) *req.Req { + r := req.New() + r.SetClient(&http.Client{ + Transport: &healthTransport{next: http.DefaultTransport.(*http.Transport).Clone(), health: health}, + Timeout: timeout, + }) + return r +} + +// Available reports whether LNbits is currently reachable. +func (c *Client) Available() bool { + return c.health.Available() +} + +// OnHealthChange registers fn to be called each time LNbits goes down +// (down=true, with the error) or comes back up (down=false). since is when +// the outage started. fn runs under the health lock, so calls arrive in +// order, but it must return quickly and must not call back into the client. +func (c *Client) OnHealthChange(fn func(down bool, reason string, since time.Time)) { + if c.health == nil { + return + } + c.health.mu.Lock() + defer c.health.mu.Unlock() + c.health.onChange = fn +} + +// StartHealthCheck pings LNbits in the background until ctx is done, so the +// bot notices an outage, and the recovery, even while no user is active. +func (c *Client) StartHealthCheck(ctx context.Context) { + probe := newHTTP(c.health, probeTimeout) + go func() { + t := time.NewTicker(probeInterval) + defer t.Stop() + for { + // The transport records the result; the response itself is unused. + // Any non-gateway answer, even a 404, proves LNbits is up. + if resp, err := probe.Get(c.url + "/api/v1/health"); err == nil { + resp.Response().Body.Close() + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } + }() +} + +// httpClient returns the tracked client for normal calls. A Client built +// without NewClient (e.g. in tests) falls back to an untracked one. +func (c Client) httpClient() *req.Req { + if c.http == nil { + return newHTTP(nil, requestTimeout) + } + return c.http +} + +// payClient returns the tracked client for payments, see httpClient. +func (c Client) payClient() *req.Req { + if c.payHTTP == nil { + return newHTTP(nil, paymentTimeout) + } + return c.payHTTP +} diff --git a/internal/lnbits/health_test.go b/internal/lnbits/health_test.go new file mode 100644 index 00000000..0076d4ed --- /dev/null +++ b/internal/lnbits/health_test.go @@ -0,0 +1,104 @@ +package lnbits + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +func TestHealthTracksRequests(t *testing.T) { + var status int32 + atomic.StoreInt32(&status, http.StatusOK) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(int(atomic.LoadInt32(&status))) + })) + defer srv.Close() + + c := NewClient("key", "token", srv.URL) + w := Wallet{Inkey: "k"} + + steps := []struct { + name string + status int + up bool + }{ + {"ok response", http.StatusOK, true}, + {"gateway error means down", http.StatusBadGateway, false}, + {"plain 404 means up again", http.StatusNotFound, true}, + {"503 means down", http.StatusServiceUnavailable, false}, + {"request error is not an outage", http.StatusBadRequest, true}, + {"504 means down", http.StatusGatewayTimeout, false}, + {"500 is a request error, not an outage", http.StatusInternalServerError, true}, + } + for _, s := range steps { + atomic.StoreInt32(&status, int32(s.status)) + c.Info(w) + if got := c.Available(); got != s.up { + t.Fatalf("%s: Available() = %v, want %v", s.name, got, s.up) + } + } +} + +func TestHealthMarksDownWhenUnreachable(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + url := srv.URL + srv.Close() + + c := NewClient("key", "token", url) + if _, err := c.Info(Wallet{Inkey: "k"}); err == nil { + t.Fatal("expected an error from a closed server") + } + if c.Available() { + t.Fatal("Available() = true after connection error, want false") + } +} + +func TestHealthCheckRecovers(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/v1/health" { + t.Errorf("probe hit %s, want /api/v1/health", r.URL.Path) + } + })) + defer srv.Close() + + c := NewClient("key", "token", srv.URL) + c.health.markDown("test") + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + c.StartHealthCheck(ctx) + + deadline := time.Now().Add(5 * time.Second) + for !c.Available() { + if time.Now().After(deadline) { + t.Fatal("health check did not mark LNbits as up") + } + time.Sleep(10 * time.Millisecond) + } +} + +func TestZeroClientIsAvailable(t *testing.T) { + if !(&Client{}).Available() { + t.Fatal("a Client without health tracking should report available") + } +} + +func TestHealthChangeCallback(t *testing.T) { + c := NewClient("key", "token", "http://unused") + var events []bool + c.OnHealthChange(func(down bool, reason string, since time.Time) { + events = append(events, down) + }) + + c.health.markDown("a") + c.health.markDown("b") // already down: no new event + c.health.markUp() + c.health.markUp() // already up: no new event + + if len(events) != 2 || events[0] != true || events[1] != false { + t.Fatalf("events = %v, want [true false]", events) + } +} diff --git a/internal/lnbits/lnbits.go b/internal/lnbits/lnbits.go index deb397f7..b29c0f76 100644 --- a/internal/lnbits/lnbits.go +++ b/internal/lnbits/lnbits.go @@ -2,7 +2,6 @@ package lnbits import ( "fmt" - "time" "github.com/imroc/req" ) @@ -24,8 +23,12 @@ func parseLNbitsError(resp *req.Resp) Error { // NewClient returns a new lnbits api client. Pass your API key, the ACL token // used for account management, and the url here. func NewClient(key, adminToken, url string) *Client { + health := &Health{} return &Client{ - url: url, + url: url, + health: health, + http: newHTTP(health, requestTimeout), + payHTTP: newHTTP(health, paymentTimeout), // info: this header holds the ADMIN key for the entire API // it can be used to create wallets for example // if you want to check the balance of a user, use w.Inkey @@ -45,7 +48,7 @@ func NewClient(key, adminToken, url string) *Client { // GetUser returns user information func (c *Client) GetUser(userId string) (user User, err error) { - resp, err := req.Get(c.url+"/users/api/v1/user/"+userId, c.adminHeader, nil) + resp, err := c.httpClient().Get(c.url+"/users/api/v1/user/"+userId, c.adminHeader, nil) if err != nil { return } @@ -71,7 +74,7 @@ func (c *Client) GetUser(userId string) (user User, err error) { func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId string, email string) (wal User, err error) { // email is deliberately not sent: the bot passes a telegram handle here, // which lnbits 1.x rejects via is_valid_email_address. - resp, err := req.Post(c.url+"/users/api/v1/user", c.adminHeader, req.BodyJSON(struct { + resp, err := c.httpClient().Post(c.url+"/users/api/v1/user", c.adminHeader, req.BodyJSON(struct { UserName string `json:"username"` }{userName})) if err != nil { @@ -107,7 +110,7 @@ func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId strin // renameWallet sets a wallet's name. It authenticates with the wallet's own // admin key rather than the ACL token, so it stays outside that token's scope. func (c *Client) renameWallet(w Wallet, name string) error { - resp, err := req.Patch(c.url+"/api/v1/wallet", req.Header{ + resp, err := c.httpClient().Patch(c.url+"/api/v1/wallet", req.Header{ "Content-Type": "application/json", "Accept": "application/json", "X-Api-Key": w.Adminkey, @@ -127,7 +130,7 @@ func (c *Client) renameWallet(w Wallet, name string) error { // // adminId is unused, see CreateUserWithInitialWallet. func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, err error) { - resp, err := req.Post(c.url+"/users/api/v1/user/"+userId+"/wallet", c.adminHeader, + resp, err := c.httpClient().Post(c.url+"/users/api/v1/user/"+userId+"/wallet", c.adminHeader, req.BodyJSON(struct { Name string `json:"name"` }{walletName})) @@ -151,7 +154,7 @@ func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx Invoice, err erro "Accept": "application/json", "X-Api-Key": w.Inkey, } - resp, err := req.Post(c.url+"/api/v1/payments", invoiceHeader, req.BodyJSON(¶ms)) + resp, err := c.httpClient().Post(c.url+"/api/v1/payments", invoiceHeader, req.BodyJSON(¶ms)) if err != nil { return } @@ -173,7 +176,7 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) { "Accept": "application/json", "X-Api-Key": w.Inkey, } - resp, err := req.Get(c.url+"/api/v1/wallet", invoiceHeader, nil) + resp, err := c.httpClient().Get(c.url+"/api/v1/wallet", invoiceHeader, nil) if err != nil { return } @@ -201,7 +204,7 @@ func (c Client) PaymentsWithOptions(w Wallet, limit, offset int) (wtx Payments, "X-Api-Key": w.Inkey, } url := fmt.Sprintf("%s/api/v1/payments?limit=%d&offset=%d", c.url, limit, offset) - resp, err := req.Get(url, invoiceHeader, nil) + resp, err := c.httpClient().Get(url, invoiceHeader, nil) if err != nil { return } @@ -223,7 +226,7 @@ func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, e "Accept": "application/json", "X-Api-Key": w.Inkey, } - resp, err := req.Get(c.url+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil) + resp, err := c.httpClient().Get(c.url+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil) if err != nil { return } @@ -239,7 +242,7 @@ func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, e // Wallets returns all wallets belonging to an user func (c Client) Wallets(w User) (wtx []Wallet, err error) { - resp, err := req.Get(c.url+"/users/api/v1/user/"+w.ID+"/wallet", c.adminHeader, nil) + resp, err := c.httpClient().Get(c.url+"/users/api/v1/user/"+w.ID+"/wallet", c.adminHeader, nil) if err != nil { return } @@ -261,9 +264,7 @@ func (w Wallet) Pay(params PaymentParams, c *Client) (wtx Invoice, err error) { "Accept": "application/json", "X-Api-Key": w.Adminkey, } - r := req.New() - r.SetTimeout(time.Hour * 24) - resp, err := r.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms)) + resp, err := c.payClient().Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms)) if err != nil { return } diff --git a/internal/lnbits/types.go b/internal/lnbits/types.go index 3f2de32e..360cdcb6 100644 --- a/internal/lnbits/types.go +++ b/internal/lnbits/types.go @@ -22,8 +22,12 @@ type Client struct { // cannot be used to spend: it is scoped to account management only. adminHeader req.Header url string - AdminKey string - InvoiceKey string + // health tracks LNbits reachability; http and payHTTP report into it. + health *Health + http *req.Req + payHTTP *req.Req + AdminKey string + InvoiceKey string } type User struct { diff --git a/internal/telegram/balance.go b/internal/telegram/balance.go index 6ac89d29..891e2262 100644 --- a/internal/telegram/balance.go +++ b/internal/telegram/balance.go @@ -36,11 +36,23 @@ func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, err } usrStr := GetUserStr(ctx.Sender()) + // While LNbits is down, show a maintenance notice with the last known + // balance instead of waiting for a call that will fail. + if !bot.Client.Available() { + bot.trySendMessage(ctx.Sender(), maintenanceBalanceMessage(ctx, user.Wallet.Balance)) + return ctx, nil + } // Get available balance (wallet balance - pot balance) availableBalance, err := bot.GetUserAvailableBalance(user) if err != nil { + // Never show a made-up 0 balance: users would think their funds are gone. log.Errorf("[/balance] Error fetching %s's available balance: %s", usrStr, err) - availableBalance = 0 + if !bot.Client.Available() { + bot.trySendMessage(ctx.Sender(), maintenanceBalanceMessage(ctx, user.Wallet.Balance)) + } else { + bot.trySendMessage(ctx.Sender(), Translate(ctx, "errorTryLaterMessage")) + } + return ctx, err } log.Infof("[/balance] %s's available balance: %s\n", usrStr, utils.FormatSats(availableBalance)) diff --git a/internal/telegram/bot.go b/internal/telegram/bot.go index 583bf8ed..92bbf105 100644 --- a/internal/telegram/bot.go +++ b/internal/telegram/bot.go @@ -1,6 +1,7 @@ package telegram import ( + "context" "fmt" "os" "os/signal" @@ -127,6 +128,10 @@ func (bot *TipBot) Start() { log.Errorf("Could not initialize bot wallet: %s", err.Error()) } + // watch LNbits so the bot can switch to maintenance mode while it is down + bot.startLNbitsAlerts() + bot.Client.StartHealthCheck(context.Background()) + // register telegram handlers bot.registerTelegramHandlers() diff --git a/internal/telegram/handler.go b/internal/telegram/handler.go index 44d37b1e..0961d2ec 100644 --- a/internal/telegram/handler.go +++ b/internal/telegram/handler.go @@ -39,7 +39,11 @@ func getDefaultAfterInterceptor(bot TipBot) []intercept.Func { // registerHandlerWithInterceptor will register a ctx with all the predefined interceptors, based on the interceptor type func (bot TipBot) registerHandlerWithInterceptor(h InterceptionWrapper) { - h.Interceptor.Before = append(getDefaultBeforeInterceptor(bot), h.Interceptor.Before...) + before := getDefaultBeforeInterceptor(bot) + if !worksWithoutLNbits(h.Endpoints) { + before = append(before, bot.lnbitsAvailableInterceptor) + } + h.Interceptor.Before = append(before, h.Interceptor.Before...) //h.Interceptor.After = append(h.Interceptor.After, getDefaultAfterInterceptor(bot)...) //h.Interceptor.OnDefer = append(h.Interceptor.OnDefer, getDefaultDeferInterceptor(bot)...) for _, endpoint := range h.Endpoints { diff --git a/internal/telegram/lnbits_alert.go b/internal/telegram/lnbits_alert.go new file mode 100644 index 00000000..9d3b2ddd --- /dev/null +++ b/internal/telegram/lnbits_alert.go @@ -0,0 +1,86 @@ +package telegram + +import ( + "sync" + "time" + + "github.com/LightningTipBot/LightningTipBot/internal/utils" +) + +// lnbitsAlertDelay is how long LNbits must stay down before admins are +// alerted, so a single failed request does not page anyone. +const lnbitsAlertDelay = 30 * time.Second + +// lnbitsAlerter tells admins in the log group when LNbits goes down and when +// it comes back. Users already get the maintenance message right away; this +// is only for admins. +type lnbitsAlerter struct { + mu sync.Mutex + downSince time.Time // zero while LNbits is up + alerted bool // a down alert was sent for the current outage + delay time.Duration + sendDown func(reason string, since time.Time) + sendUp func(since time.Time) +} + +// onChange is registered with lnbits.Client.OnHealthChange. It must not +// block, so alerts are sent from timers and goroutines. +func (a *lnbitsAlerter) onChange(down bool, reason string, since time.Time) { + a.mu.Lock() + defer a.mu.Unlock() + if down { + a.downSince = since + a.alerted = false + time.AfterFunc(a.delay, func() { a.confirmDown(reason, since) }) + return + } + if a.alerted { + go a.sendUp(since) + } + a.downSince = time.Time{} + a.alerted = false +} + +// confirmDown sends the down alert if the outage that started at since is +// still going on. +func (a *lnbitsAlerter) confirmDown(reason string, since time.Time) { + a.mu.Lock() + if !a.downSince.Equal(since) { + // recovered already, or this is an older outage + a.mu.Unlock() + return + } + a.alerted = true + a.mu.Unlock() + a.sendDown(reason, since) +} + +// startLNbitsAlerts hooks the admin alerts into the LNbits health tracking. +func (bot *TipBot) startLNbitsAlerts() { + if bot.ErrorLogger == nil || !bot.ErrorLogger.enabled { + return + } + a := &lnbitsAlerter{ + delay: lnbitsAlertDelay, + sendDown: bot.ErrorLogger.LogLNbitsDown, + sendUp: bot.ErrorLogger.LogLNbitsUp, + } + bot.Client.OnHealthChange(a.onChange) +} + +// LogLNbitsDown alerts the log group that LNbits is unreachable. +func (el *ErrorLogger) LogLNbitsDown(reason string, since time.Time) { + msg := "š“ LNbits is down\n\n" + + "Users now get the maintenance message.\n" + + "š Since: " + since.UTC().Format("2006-01-02 15:04:05 UTC") + "\n" + + "
ā " + utils.EscapeHTML(reason) + "" + el.sendToTelegramHTML(msg) +} + +// LogLNbitsUp alerts the log group that LNbits is reachable again. +func (el *ErrorLogger) LogLNbitsUp(since time.Time) { + msg := "š¢ LNbits is back up\n\n" + + "The bot works normally again.\n" + + "ā± Downtime: " + time.Since(since).Round(time.Second).String() + el.sendToTelegramHTML(msg) +} diff --git a/internal/telegram/lnbits_alert_test.go b/internal/telegram/lnbits_alert_test.go new file mode 100644 index 00000000..425eb1af --- /dev/null +++ b/internal/telegram/lnbits_alert_test.go @@ -0,0 +1,55 @@ +package telegram + +import ( + "sync" + "testing" + "time" +) + +type alertRecorder struct { + mu sync.Mutex + downs int + ups int +} + +func (r *alertRecorder) counts() (int, int) { + r.mu.Lock() + defer r.mu.Unlock() + return r.downs, r.ups +} + +func newTestAlerter(r *alertRecorder) *lnbitsAlerter { + return &lnbitsAlerter{ + delay: 20 * time.Millisecond, + sendDown: func(string, time.Time) { r.mu.Lock(); r.downs++; r.mu.Unlock() }, + sendUp: func(time.Time) { r.mu.Lock(); r.ups++; r.mu.Unlock() }, + } +} + +func TestLNbitsAlertSkipsShortOutage(t *testing.T) { + r := &alertRecorder{} + a := newTestAlerter(r) + since := time.Now() + a.onChange(true, "blip", since) + a.onChange(false, "", since) + time.Sleep(60 * time.Millisecond) + if d, u := r.counts(); d != 0 || u != 0 { + t.Fatalf("short outage sent %d down / %d up alerts, want none", d, u) + } +} + +func TestLNbitsAlertLongOutage(t *testing.T) { + r := &alertRecorder{} + a := newTestAlerter(r) + since := time.Now() + a.onChange(true, "connection refused", since) + time.Sleep(60 * time.Millisecond) + if d, _ := r.counts(); d != 1 { + t.Fatalf("down alerts = %d, want 1", d) + } + a.onChange(false, "", since) + time.Sleep(20 * time.Millisecond) + if d, u := r.counts(); d != 1 || u != 1 { + t.Fatalf("got %d down / %d up alerts, want 1 / 1", d, u) + } +} diff --git a/internal/telegram/maintenance.go b/internal/telegram/maintenance.go new file mode 100644 index 00000000..94241ca2 --- /dev/null +++ b/internal/telegram/maintenance.go @@ -0,0 +1,86 @@ +package telegram + +import ( + "fmt" + "strings" + + "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" + "github.com/LightningTipBot/LightningTipBot/internal/utils" + log "github.com/sirupsen/logrus" + tb "gopkg.in/lightningtipbot/telebot.v3" +) + +var errLNbitsUnavailable = fmt.Errorf("lnbits unavailable") + +// worksWithoutLNbits reports whether a handler can run while LNbits is down. +// Help and price commands never touch LNbits, and cancel buttons only edit +// messages. /balance is listed because it handles the outage itself, so it +// can also show the last known balance. +func worksWithoutLNbits(endpoints []interface{}) bool { + allowed := []interface{}{ + "/help", &btnHelpMainMenu, "/basics", "/advanced", + "/lkrsats", &btnConvertMainMenu, "/convert", + "/balance", &btnBalanceMainMenu, + &btnCancelPay, &btnCancelSend, &btnCancelSendBatch, &btnCancelAPITx, + &btnCancelInlineSend, &btnCancelInlineReceive, &btnCancelInlineFaucet, + &btnCancelInlineTipjar, &btnCancelWithdraw, &btnCancelAuth, + tb.OnDocument, tb.OnVideo, tb.OnAnimation, tb.OnVoice, tb.OnAudio, tb.OnSticker, tb.OnVideoNote, + } + for _, e := range endpoints { + for _, a := range allowed { + if e == a { + return true + } + } + } + return false +} + +// lnbitsAvailableInterceptor stops a request with a maintenance message while +// LNbits is down, instead of letting it hang and then fail with a confusing +// error or wrong data. It runs before the lock interceptor, so nothing needs +// to be unlocked when it stops the request. +func (bot TipBot) lnbitsAvailableInterceptor(ctx intercept.Context) (intercept.Context, error) { + if bot.Client.Available() { + return ctx, nil + } + ctx, _ = bot.localizerInterceptor(ctx) + bot.sendMaintenanceNotice(ctx) + return ctx, errLNbitsUnavailable +} + +// sendMaintenanceNotice tells the user that BitcoinDeepa is under maintenance, +// in the way that fits the update type. +func (bot TipBot) sendMaintenanceNotice(ctx intercept.Context) { + switch { + case ctx.Message() != nil: + m := ctx.Message() + // In groups, only answer commands. Plain chat messages also pass + // through the bot and must not trigger a reply each. + if !m.Private() && !strings.HasPrefix(m.Text, "/") { + return + } + bot.trySendMessage(m.Chat, Translate(ctx, "maintenanceMessage")) + case ctx.Callback() != nil: + err := bot.Telegram.Respond(ctx.Callback(), &tb.CallbackResponse{ + CallbackID: ctx.Callback().ID, + Text: TranslateUser(ctx, "maintenanceMessage"), + ShowAlert: true, + }) + if err != nil { + log.Errorf("[maintenance] could not answer callback: %v", err) + } + case ctx.Query() != nil: + bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "maintenanceTitle"), TranslateUser(ctx, "maintenanceMessage")) + } +} + +// maintenanceBalanceMessage is the /balance reply while LNbits is down. It adds +// the last balance the bot saw, so users can see their funds are still there. +func maintenanceBalanceMessage(ctx intercept.Context, lastKnownMsat int64) string { + msg := Translate(ctx, "maintenanceMessage") + if lastKnownMsat > 0 { + msg += "\n\n" + fmt.Sprintf(Translate(ctx, "maintenanceLastBalanceMessage"), utils.FormatSats(lastKnownMsat/1000)) + } + return msg +} diff --git a/translations/en.toml b/translations/en.toml index 8d03600f..687f7f92 100644 --- a/translations/en.toml +++ b/translations/en.toml @@ -190,6 +190,9 @@ confirmSendMessage = """Do you want to pay to %s?\n\nšø Amount: %s""" confirmSendAppendMemo = """\nāļø %s""" sendCancelledMessage = """š« Send cancelled.""" errorTryLaterMessage = """š« Error. Please try again later.""" +maintenanceTitle = """š Under maintenance""" +maintenanceMessage = """š BitcoinDeepa is under maintenance. Your funds are safe. Please try again in a few minutes.""" +maintenanceLastBalanceMessage = """Last known balance: %s""" sendSyntaxErrorMessage = """Did you enter an amount and a recipient? You can use the /send command to either send to Telegram users like %s or to a Lightning address like BitcoinDeepaBot@bitcoindeepa.com.""" sendHelpText = """š Oops, that didn't work. %s