package telegram import ( "context" "errors" "fmt" "strconv" tiperrors "github.com/LightningTipBot/LightningTipBot/internal/errors" "github.com/LightningTipBot/LightningTipBot/internal/lnbits" "github.com/LightningTipBot/LightningTipBot/internal/lnurlcash" "github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex" "github.com/LightningTipBot/LightningTipBot/internal/storage" "github.com/LightningTipBot/LightningTipBot/internal/str" "github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept" log "github.com/sirupsen/logrus" tb "gopkg.in/lightningtipbot/telebot.v3" ) // NoteConfirm is the pending "create a note" dialog in private chat. type NoteConfirm struct { *storage.Base UserName string `json:"user_name"` Quote lnurlcash.Quote `json:"quote"` Memo string `json:"memo"` LanguageCode string `json:"languagecode"` ValueMsat int64 `json:"value_msat"` Count int `json:"count"` } var ( btnNoteCreate = (&tb.ReplyMarkup{}).Data("", "lnc_create") btnNoteMint = (&tb.ReplyMarkup{}).Data("", "lnc_mint") btnNoteCancel = (&tb.ReplyMarkup{}).Data("", "lnc_cancel") btnNoteStatus = (&tb.ReplyMarkup{}).Data("", "lnc_status") btnNoteReclaim = (&tb.ReplyMarkup{}).Data("", "lnc_reclaim") btnNoteQR = (&tb.ReplyMarkup{}).Data("", "lnc_qr") ) // noteCommandUser resolves the sender for a note command. In a group a user // without a wallet is told to start a private chat; in private chat the // start flow runs. func (bot *TipBot) noteCommandUser(ctx intercept.Context) (*lnbits.User, bool) { user := LoadUser(ctx) m := ctx.Message() if user == nil || user.Wallet == nil || !user.Initialized { if m.Private() { _, _ = bot.startHandler(ctx) return nil, false } bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) return nil, false } return user, true } // noteHandler handles /note [memo]. func (bot *TipBot) noteHandler(ctx intercept.Context) (intercept.Context, error) { if !bot.lnurlcashReady(ctx) { return ctx, nil } m := ctx.Message() user, ok := bot.noteCommandUser(ctx) if !ok { return ctx, tiperrors.Create(tiperrors.UserNoWalletError) } amount, err := decodeAmountFromCommand(m.Text) if err != nil || amount <= 0 { if m.Private() { bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteHelpMessage")) } else { NewMessage(m, WithDuration(0, bot)) bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteHelpMessage")) } return ctx, tiperrors.Create(tiperrors.InvalidSyntaxError) } memo := GetMemoFromCommand(m.Text, 2) svc := bot.LNURLCash mint, ok := svc.Mints().ForUser(user.Name) if !ok { bot.trySendMessage(m.Sender, TranslateUser(ctx, "noteMintUnavailableMessage")) return ctx, tiperrors.Create(tiperrors.UnknownError) } q, err := svc.Quote(ctx, mint, amount*1000, 1) if err == nil { err = svc.CheckCaps(ctx, user.Name, q, !m.Private()) } if err != nil { text := lnurlcashErrorText(ctx, err) if m.Private() { bot.trySendMessage(m.Sender, text) } else { NewMessage(m, WithDuration(0, bot)) bot.sendPrivate(m.Sender, text) } return ctx, err } if !m.Private() { return bot.createNoteInGroup(ctx, user, q, memo) } 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: 1} bot.trySendMessageEditable(m.Sender, noteConfirmText(ctx, confirm), noteConfirmKeyboard(ctx, confirm.ID)) return ctx, confirm.Set(confirm, bot.Bunt) } func noteConfirmText(ctx context.Context, c *NoteConfirm) string { q := c.Quote text := fmt.Sprintf(TranslateUser(ctx, "noteConfirmMessage"), q.Count, formatSat(q.ValueMsat), formatSat(q.FeeMsat), formatSat(q.GrossMsat), q.MintName) if c.Memo != "" { text += fmt.Sprintf(TranslateUser(ctx, "noteViewMemo"), str.MarkdownEscape(c.Memo)) } return text } func noteConfirmKeyboard(ctx context.Context, id string) *tb.ReplyMarkup { menu := &tb.ReplyMarkup{} menu.Inline( menu.Row(menu.Data(TranslateUser(ctx, "noteCreateButton"), "lnc_create", id)), menu.Row(menu.Data(TranslateUser(ctx, "noteChangeMintButton"), "lnc_mint", id), menu.Data(TranslateUser(ctx, "noteCancelButton"), "lnc_cancel", id)), ) return menu } // loadNoteConfirm loads the dialog behind a callback and checks ownership. func (bot *TipBot) loadNoteConfirm(ctx intercept.Context) (*NoteConfirm, error) { tx := &NoteConfirm{Base: storage.New(storage.ID(ctx.Data()))} got, err := tx.Get(tx, bot.Bunt) if err != nil { return nil, err } c := got.(*NoteConfirm) if c.UserName != LoadUser(ctx).Name { return nil, tiperrors.Create(tiperrors.UnknownError) } if !c.Active { return nil, tiperrors.Create(tiperrors.NotActiveError) } return c, nil } // noteCreateHandler runs when the user pressed Create. func (bot *TipBot) noteCreateHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } mutex.LockWithContext(ctx, ctx.Data()) defer mutex.UnlockWithContext(ctx, ctx.Data()) c, err := bot.loadNoteConfirm(ctx) if err != nil { return ctx, err } _ = c.Inactivate(c, bot.Bunt) user := LoadUser(ctx) msg := ctx.Callback().Message bot.tryEditMessage(msg, TranslateUser(ctx, "noteCreatingMessage"), &tb.ReplyMarkup{}) params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: c.Quote, Memo: c.Memo} if c.Count > 1 { return bot.createBatchFromConfirm(ctx, c, params, msg) } _, live, err := bot.LNURLCash.Create(ctx, params) if err != nil && len(live) == 0 { bot.tryEditMessage(msg, lnurlcashErrorText(ctx, err), &tb.ReplyMarkup{}) return ctx, err } bot.tryDeleteMessage(msg) bot.sendNoteCreated(ctx, user.Telegram, live[0]) return ctx, nil } // sendNoteCreated sends the QR and the note text with its buttons. func (bot *TipBot) sendNoteCreated(ctx context.Context, to *tb.User, n *lnurlcash.Note) { bot.sendNoteQR(to, n) lnurlw, _, err := bot.LNURLCash.NoteStrings(n) if err != nil { log.Errorf("[lnurlcash] note strings: %v", err) return } text := fmt.Sprintf(TranslateUser(ctx, "noteCreatedMessage"), formatSat(n.ReportedMsat), lnurlcash.ShortID(n.ID), lnurlw) bot.trySendMessageEditable(to, text, noteKeyboard(ctx, n, false)) } // noteMintHandler cycles the dialog to the next usable mint and re-quotes. func (bot *TipBot) noteMintHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } mutex.LockWithContext(ctx, ctx.Data()) defer mutex.UnlockWithContext(ctx, ctx.Data()) c, err := bot.loadNoteConfirm(ctx) if err != nil { return ctx, err } mints := bot.LNURLCash.Mints().All() var usable []*lnurlcash.Mint for _, m := range mints { if m.Usable() { usable = append(usable, m) } } if len(usable) < 2 { bot.trySendMessage(ctx.Sender(), TranslateUser(ctx, "noteOnlyOneMintMessage")) return ctx, nil } next := usable[0] for i, m := range usable { if m.ID == c.Quote.MintID { next = usable[(i+1)%len(usable)] break } } q, err := bot.LNURLCash.Quote(ctx, next, c.ValueMsat, c.Count) if err != nil { bot.trySendMessage(ctx.Sender(), lnurlcashErrorText(ctx, err)) return ctx, err } c.Quote = q bot.tryEditMessage(ctx.Callback().Message, noteConfirmText(ctx, c), noteConfirmKeyboard(ctx, c.ID)) return ctx, c.Set(c, bot.Bunt) } // noteCancelHandler runs when the user pressed Cancel. func (bot *TipBot) noteCancelHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } mutex.LockWithContext(ctx, ctx.Data()) defer mutex.UnlockWithContext(ctx, ctx.Data()) c, err := bot.loadNoteConfirm(ctx) if err != nil { return ctx, err } bot.tryEditMessage(ctx.Callback().Message, TranslateUser(ctx, "noteCancelledMessage"), &tb.ReplyMarkup{}) return ctx, c.Inactivate(c, bot.Bunt) } // createNoteInGroup creates a note without a confirm step, posts it in the // group and sends the receipt privately. func (bot *TipBot) createNoteInGroup(ctx intercept.Context, user *lnbits.User, q lnurlcash.Quote, memo string) (intercept.Context, error) { m := ctx.Message() receipt, ok := bot.sendPrivate(m.Sender, TranslateUser(ctx, "noteCreatingMessage")) if !ok { bot.tryReplyMessage(m, Translate(ctx, "lnurlcashStartPrivateFirstMessage")) return ctx, tiperrors.Create(tiperrors.NoPrivateChatError) } params := lnurlcash.CreateParams{User: user.Name, LanguageCode: user.Telegram.LanguageCode, Quote: q, Memo: memo, ChatID: m.Chat.ID} _, live, err := bot.LNURLCash.Create(ctx, params) if err != nil && len(live) == 0 { bot.tryEditMessage(receipt, lnurlcashErrorText(ctx, err)) return ctx, err } n := live[0] _, bech, err := bot.LNURLCash.NoteStrings(n) if err != nil { return ctx, err } qr, err := qrcodeEncode(bech) if err != nil { return ctx, err } caption := fmt.Sprintf(Translate(ctx, "noteGroupMessage"), formatSat(n.ReportedMsat), GetUserStrMd(m.Sender), bech) if memo != "" { caption += fmt.Sprintf(Translate(ctx, "noteViewMemo"), str.MarkdownEscape(memo)) } post := bot.tryReplyMessage(m, &tb.Photo{File: tb.File{FileReader: qr}, Caption: caption}) if post != nil { _ = bot.LNURLCash.Store().UpdateNote(n.ID, map[string]interface{}{"chat_id": post.Chat.ID, "message_id": strconv.Itoa(post.ID)}) } lnurlw, _, _ := bot.LNURLCash.NoteStrings(n) text := fmt.Sprintf(TranslateUser(ctx, "noteReceiptMessage"), formatSat(n.ReportedMsat), formatSat(q.FeeMsat), q.MintName, lnurlcash.ShortID(n.ID), lnurlw) bot.tryEditMessage(receipt, text, noteKeyboard(ctx, n, false)) log.Infof("[lnurlcash] %s created group note %s (%d msat) in chat %d", GetUserStr(m.Sender), n.ID, n.ReportedMsat, m.Chat.ID) return ctx, nil } // noteStatusHandler answers the Check status button. func (bot *TipBot) noteStatusHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } n, err := bot.loadOwnNote(ctx) if err != nil { return ctx, err } state, value, err := bot.LNURLCash.Status(ctx, n) var text string switch { case errors.Is(err, lnurlcashgoPending()): text = TranslateUser(ctx, "noteStatusPendingMessage") case err != nil: text = TranslateUser(ctx, "noteMintUnavailableMessage") case state == lnurlcash.NoteClaimed: text = TranslateUser(ctx, "noteStatusClaimedMessage") case state == lnurlcash.NoteLive: text = fmt.Sprintf(TranslateUser(ctx, "noteStatusLiveMessage"), formatSat(value)) default: text = fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, state)) } bot.trySendMessageEditable(ctx.Sender(), text) if ctx.Callback().Message != nil { _, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false)) } return ctx, nil } // noteReclaimHandler answers the Reclaim button. func (bot *TipBot) noteReclaimHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } n, err := bot.loadOwnNote(ctx) if err != nil { return ctx, err } n, err = bot.LNURLCash.Reclaim(ctx, n.ID) if err != nil { bot.trySendMessageEditable(ctx.Sender(), lnurlcashErrorText(ctx, err)) return ctx, err } bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteReclaimRequestedMessage"), formatSat(n.ReportedMsat))) if ctx.Callback().Message != nil { _, _ = bot.Telegram.EditReplyMarkup(ctx.Callback().Message, noteKeyboard(ctx, n, false)) } (&lnurlcashNotifier{bot: bot}).GroupNoteState(n) return ctx, nil } // noteQRHandler answers the Show QR button. func (bot *TipBot) noteQRHandler(ctx intercept.Context) (intercept.Context, error) { if bot.LNURLCash == nil { return ctx, nil } n, err := bot.loadOwnNote(ctx) if err != nil { return ctx, err } if n.State != lnurlcash.NoteLive { bot.trySendMessageEditable(ctx.Sender(), fmt.Sprintf(TranslateUser(ctx, "noteStatusOtherMessage"), noteStateText(ctx, n.State))) return ctx, nil } bot.sendNoteCreated(ctx, ctx.Sender(), n) return ctx, nil } // lnurlcashgoPending is the library's pending sentinel, kept behind a // function so this file does not import the library for one value. func lnurlcashgoPending() error { return lnurlcash.ErrNotePending }