package telegram import ( "bytes" "context" "fmt" "strings" tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors" "github.com/LightningTipBot/LightningTipBot/internal/lnbits" "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash/export" "github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex" "github.com/LightningTipBot/LightningTipBot/internal/storage" "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" log "github.com/sirupsen/logrus" tb "gopkg.in/lightningtipbot/telebot.v3" ) var ( btnBatchExportPDF = (&tb.ReplyMarkup{}).Data("", "lnc_exp_pdf") btnBatchExportJSON = (&tb.ReplyMarkup{}).Data("", "lnc_exp_json") btnBatchExportCSV = (&tb.ReplyMarkup{}).Data("", "lnc_exp_csv") btnBatchRefresh = (&tb.ReplyMarkup{}).Data("", "lnc_brefresh") btnBatchReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_breclaim") ) // parseBatchCommand reads "/notes x [memo]". ok is false // when the text is not a batch command. func parseBatchCommand(text string) (amount int64, count int, memo string, ok bool) { parts := strings.Fields(text) if len(parts) < 4 { return 0, 0, "", false } sep := strings.ToLower(parts[2]) if sep != "x" && sep != "×" && sep != "*" { return 0, 0, "", false } amount, err := GetAmount(parts[1]) if err != nil { return 0, 0, "", false } var n int if _, err := fmt.Sscanf(parts[3], "%d", &n); err != nil || n < 1 { return 0, 0, "", false } return amount, n, GetMemoFromCommand(text, 4), true } // noteBatchStart quotes a batch and shows the confirm dialog privately. func (bot *TipBot) noteBatchStart(ctx intercept.Context, user *lnbits.User, amount int64, count int, memo string) (intercept.Context, error) { m := ctx.Message() svc := bot.LNURLCash if !m.Private() { NewMessage(m, WithDuration(0, bot)) } mint, ok := svc.Mints().ForUser(user.Name) if !ok { bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage")) return ctx, tiperrors.Create(tiperrors.UnknownError) } q, err := svc.Quote(ctx, mint, amount*1000, count) if err == nil { err = svc.CheckCaps(ctx, user.Name, q, false) } if err != nil { if _, ok := bot.sendPrivate(m.Sender, lnurlcashErrorText(ctx, err)); !ok && !m.Private() { bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) } return ctx, err } confirm := &NoteConfirm{Base: storage.New(storage.ID(fmt.Sprintf("lnc-%d-%s", m.Sender.ID, RandStringRunes(6)))), UserName: user.Name, Quote: q, Memo: memo, LanguageCode: user.Telegram.LanguageCode, ValueMsat: q.ValueMsat, Count: count} if _, ok := bot.sendPrivate(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID)); !ok { bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) } return ctx, confirm.Set(confirm, bot.Bunt) } // createBatchFromConfirm runs after Create was pressed on a batch dialog. func (bot *TipBot) createBatchFromConfirm(ctx intercept.Context, c *NoteConfirm, params lnurlcash.CreateParams, msg *tb.Message) (intercept.Context, error) { total := c.Count key := "lnc-progress-" + c.ID params.Progress = func(done, total int) { bot.tryEditStack(msg, key, fmt.Sprintf(TranslateUser(ctx, "notesBatchProgressMessage"), done, total, MakeProgressbar(int64(done), int64(total)))) } batch, live, err := bot.LNURLCash.Create(ctx, params) if err != nil && len(live) == 0 { bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{}) return ctx, err } text := fmt.Sprintf(TranslateUser(ctx, "notesBatchCreatedMessage"), len(live), total, lnurlcash.ShortID(batch.ID)) if err != nil { text += "\n" + fmt.Sprintf(TranslateUser(ctx, "notesBatchPartialMessage"), lnurlcashErrorText(ctx, err)) } text += "\n\n" + TranslateUser(ctx, "notesBatchFormatMessage") bot.tryEditMessage(msg, text, batchKeyboard(ctx, batch.ID)) return ctx, nil } // batchKeyboard offers the export formats and the batch actions. func batchKeyboard(ctx context.Context, batchID string) *tb.ReplyMarkup { menu := &tb.ReplyMarkup{} cfg := bot_lnurlcash_cfg() var formats []tb.Btn if cfg.HasFormat("pdf") { formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportPdfButton"), "lnc_exp_pdf", batchID)) } if cfg.HasFormat("json") { formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportJsonButton"), "lnc_exp_json", batchID)) } if cfg.HasFormat("csv") { formats = append(formats, menu.Data(TranslateUser(ctx, "notesExportCsvButton"), "lnc_exp_csv", batchID)) } rows := []tb.Row{} if len(formats) > 0 { rows = append(rows, menu.Row(formats...)) } rows = append(rows, menu.Row( menu.Data(TranslateUser(ctx, "notesRefreshButton"), "lnc_brefresh", batchID), menu.Data(TranslateUser(ctx, "notesReclaimUnclaimedButton"), "lnc_breclaim", batchID))) menu.Inline(rows...) return menu } // batchViewText renders a batch with its counts. func (bot *TipBot) batchViewText(ctx context.Context, b *lnurlcash.Batch) string { sum, _ := bot.LNURLCash.Summarize(b.ID) text := fmt.Sprintf(TranslateUser(ctx, "notesBatchOpenMessage"), lnurlcash.ShortID(b.ID), b.Count, formatSat(b.ValueMsat), b.MintID, b.CreatedAt.UTC().Format("2 Jan 06 15:04"), sum.Live, sum.Claimed, sum.Reclaimed, sum.Failed+sum.Pending) if b.Memo != "" { text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), b.Memo) } return text } // loadOwnBatch loads the batch behind a callback and checks ownership. func (bot *TipBot) loadOwnBatch(ctx intercept.Context) (*lnurlcash.Batch, error) { b, err := bot.LNURLCash.Store().Batch(ctx.Data()) if err != nil { return nil, tiperrors.Create(tiperrors.NotActiveError) } if b.UserName != LoadUser(ctx).Name { return nil, lnurlcash.ErrNotOwner } return b, nil } func (bot *TipBot) batchExportHandler(format string) intercept.Func { return func(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } if !bot_lnurlcash_cfg().HasFormat(format) { return ctx, nil } b, err := bot.loadOwnBatch(ctx) if err != nil { return ctx, err } // files only ever go to the private chat if msg := ctx.Callback().Message; msg != nil && !msg.Private() { return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) } data, err := bot.LNURLCash.ExportBatch(b.ID, LoadUser(ctx).Name) if err != nil { bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err)) return ctx, err } var buf bytes.Buffer var mime string switch format { case "pdf": err, mime = export.PDF(&buf, data), "application/pdf" case "json": err, mime = export.JSON(&buf, data), "application/json" case "csv": err, mime = export.CSV(&buf, data), "text/csv" } if err != nil { log.Errorf("[lnurlcash] export %s of %s: %v", format, b.ID, err) bot.trySendMessageEditable(ctx.Sender(), TranslateUser(ctx, "noteErrorMessage")) return ctx, err } doc := &tb.Document{File: tb.File{FileReader: &buf}, FileName: fmt.Sprintf("notes-%s.%s", lnurlcash.ShortID(b.ID), format), MIME: mime, Caption: fmt.Sprintf(TranslateUser(ctx, "notesExportCaption"), len(data.Notes), lnurlcash.ShortID(b.ID))} bot.trySendMessageEditable(ctx.Sender(), doc) return ctx, nil } } // batchRefreshHandler probes every live note of the batch and re-renders it. func (bot *TipBot) batchRefreshHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } b, err := bot.loadOwnBatch(ctx) if err != nil { return ctx, err } notes, _ := bot.LNURLCash.Store().NotesInBatch(b.ID) for _, n := range notes { if n.Kind == lnurlcash.KindUser && n.State == lnurlcash.NoteLive { _, _, _ = bot.LNURLCash.Status(ctx, n) } } b, _ = bot.LNURLCash.Store().Batch(b.ID) bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID)) return ctx, nil } // batchReclaimHandler reclaims every unclaimed note of the batch. func (bot *TipBot) batchReclaimHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } mutex.LockWithContext(ctx, ctx.Data()) defer mutex.UnlockWithContext(ctx, ctx.Data()) b, err := bot.loadOwnBatch(ctx) if err != nil { return ctx, err } sent, err := bot.LNURLCash.ReclaimBatch(ctx, b.ID, LoadUser(ctx).Name) text := fmt.Sprintf(TranslateUser(ctx, "notesBatchReclaimMessage"), sent) if err != nil { text += "\n" + lnurlcashErrorText(ctx, err) } bot.trySendMessageEditable(ctx.Sender(), text) b, _ = bot.LNURLCash.Store().Batch(b.ID) bot.tryEditMessage(ctx.Callback().Message, bot.batchViewText(ctx, b), batchKeyboard(ctx, b.ID)) return ctx, nil }