Compare commits

..
Author SHA1 Message Date
gohumble 2cfbacf704 update GetUserStrMd 2022-06-13 08:34:27 +02:00
gohumble df8e198b2e update GetUserStr 2022-06-12 22:25:19 +02:00
6 changed files with 175 additions and 79 deletions
+3 -13
View File
@@ -1,9 +1,6 @@
package lnbits
import (
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
"time"
"github.com/imroc/req"
@@ -43,8 +40,8 @@ func (c *Client) GetUser(userId string) (user User, err error) {
return
}
// CreateUserWithWallet creates new user with wallet
func (c *Client) CreateUserWithWallet(userName, walletName, adminId string, email string) (user User, err error) {
// CreateUserWithInitialWallet creates new user with initial wallet
func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId string, email string) (wal User, err error) {
resp, err := req.Post(c.url+"/usermanager/api/v1/users", c.header, req.BodyJSON(struct {
WalletName string `json:"wallet_name"`
AdminId string `json:"admin_id"`
@@ -61,14 +58,7 @@ func (c *Client) CreateUserWithWallet(userName, walletName, adminId string, emai
err = reqErr
return
}
err = resp.ToJSON(&user)
res := gjson.Get(resp.String(), "wallets.0")
if res.Index == 0 {
err = fmt.Errorf("could not create initial wallet")
return
}
user.Wallet = &Wallet{}
err = json.Unmarshal([]byte(res.Raw), user.Wallet)
err = resp.ToJSON(&wal)
return
}
-5
View File
@@ -20,11 +20,6 @@ type Client struct {
InvoiceKey string
}
// User is a bot user containing lnbits and telegram information.
// This struct is used for orm persistence.
// Users are created, by talking to the bot or by receiving funds (tips, receive, faucet)
// The initialized flag is set true, if user already talked to the bot.
// This is used for the '<- talk to this bot' message when sending tips to new users.
type User struct {
ID string `json:"id"`
Name string `json:"name" gorm:"primaryKey"`
+2 -2
View File
@@ -74,9 +74,9 @@ func newTelegramBot() *tb.Bot {
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
func (bot TipBot) initBotWallet() error {
botWalletInitialisation.Do(func() {
_, err := bot.userWithInitWallet(bot.Telegram.Me)
_, err := bot.initWallet(bot.Telegram.Me)
if err != nil {
log.Errorln(fmt.Sprintf("[initBotWallet] ❌ 🧨 ❌ Could not initialize bot wallet: %s", err.Error()))
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
return
}
})
+63 -43
View File
@@ -4,16 +4,20 @@ import (
"context"
stderrors "errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/gorm"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/gorm"
)
func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error) {
@@ -25,7 +29,7 @@ func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error)
// bot.helpHandler(m)
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(ctx.Sender()), ctx.Sender().ID)
walletCreationMsg := bot.trySendMessageEditable(ctx.Sender(), Translate(ctx, "startSettingWalletMessage"))
user, err := bot.userWithInitWallet(ctx.Sender())
user, err := bot.initWallet(ctx.Sender())
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
@@ -44,58 +48,74 @@ func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error)
return ctx, nil
}
// userWithInitWallet will ensure that lnbits.User is initialized.
// Initialized users have already talked to the bot,
// therefor they are able to receive messages from the bot.
func (bot TipBot) userWithInitWallet(tguser *tb.User) (*lnbits.User, error) {
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
user, err := GetUser(tguser, bot)
if err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
user, err = bot.createWallet(tguser)
if err != nil {
return user, err
}
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
return user, fmt.Errorf("[initWallet] error updating user: %v", err)
}
return user, nil
if stderrors.Is(err, gorm.ErrRecordNotFound) {
user = &lnbits.User{Telegram: tguser}
err = bot.createWallet(user)
if err != nil {
return user, err
}
return nil, err
}
if !user.Initialized {
// set user initialized
user, err := GetUser(tguser, bot)
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return user, err
}
} else if !user.Initialized {
// update all tip tooltips (with the "initialize me" message) that this user might have received before
tipTooltipInitializedHandler(user.Telegram, bot)
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
return user, fmt.Errorf("[initWallet] error updating user: %v", err)
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return user, err
}
} else if user.Initialized {
// wallet is already initialized
return user, nil
} else {
err = fmt.Errorf("could not initialize wallet")
return user, err
}
// wallet is already initialized
return user, nil
}
// createWallet will create a wallet for any telegram user.
func (bot TipBot) createWallet(u *tb.User) (*lnbits.User, error) {
userStr := GetUserStr(u)
user, err := bot.Client.CreateUserWithWallet(strconv.FormatInt(u.ID, 10),
fmt.Sprintf("%d (%s)", u.ID, userStr),
func (bot TipBot) createWallet(user *lnbits.User) error {
UserStr := GetUserStr(user.Telegram)
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
internal.Configuration.Lnbits.AdminId,
userStr)
UserStr)
if err != nil {
return nil, fmt.Errorf("[createWallet] Create wallet error: %v", err)
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
user.Telegram = u
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.AnonIDSha256 = str.AnonIdSha256(&user)
user.UUID = str.UUIDSha256(&user)
user.Wallet = &lnbits.Wallet{}
user.ID = u.ID
user.Name = u.Name
wallet, err := bot.Client.Wallets(*user)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
user.Wallet = &wallet[0]
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.AnonIDSha256 = str.AnonIdSha256(user)
user.UUID = str.UUIDSha256(user)
user.Initialized = false
user.CreatedAt = time.Now()
err = UpdateUserRecord(&user, bot)
err = UpdateUserRecord(user, bot)
if err != nil {
return nil, fmt.Errorf("[createWallet] Update user record error: %v", err)
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
log.Errorln(errormsg)
return err
}
return &user, nil
return nil
}
+21 -16
View File
@@ -27,28 +27,27 @@ func ResetUserState(user *lnbits.User, bot *TipBot) {
}
func GetUserStr(user *tb.User) string {
userStr := fmt.Sprintf("@%s", user.Username)
// if user does not have a username
if len(userStr) < 2 && user.FirstName != "" {
userStr = fmt.Sprintf("%s", user.FirstName)
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("%d", user.ID)
if len(user.Username) == 0 {
if user.FirstName != "" {
return fmt.Sprintf("%s", user.FirstName)
} else {
return fmt.Sprintf("%d", user.ID)
}
}
return userStr
return fmt.Sprintf("@%s", user.Username)
}
func GetUserStrMd(user *tb.User) string {
userStr := fmt.Sprintf("@%s", user.Username)
// if user does not have a username
if len(userStr) < 2 && user.FirstName != "" {
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
return userStr
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
return userStr
if len(user.Username) == 0 {
if user.FirstName != "" {
return fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
} else {
return fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
}
} else {
// escape only if user has a username
return str.MarkdownEscape(userStr)
return str.MarkdownEscape(fmt.Sprintf("@%s", user.Username))
}
}
@@ -100,14 +99,20 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
if _, exists := bot.UserExists(tbUser); exists {
return nil, fmt.Errorf("user already exists")
}
user := &lnbits.User{Telegram: tbUser}
userStr := GetUserStr(tbUser)
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
user, err := bot.createWallet(tbUser)
err := bot.createWallet(user)
if err != nil {
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
log.Errorln(errmsg)
return user, err
}
// todo: remove this. we're doing this already in bot.createWallet().
err = UpdateUserRecord(user, *bot)
if err != nil {
return nil, err
}
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
return user, nil
}
+86
View File
@@ -0,0 +1,86 @@
package telegram
import (
tb "gopkg.in/lightningtipbot/telebot.v3"
"testing"
)
func TestGetUserStr(t *testing.T) {
type args struct {
user *tb.User
}
tests := []struct {
name string
args args
want string
}{
{name: "NoUserName", args: args{user: &tb.User{FirstName: "BotUser", ID: 12351241}}, want: "BotUser"},
{name: "UserName", args: args{user: &tb.User{Username: "Username", FirstName: "BotUser", ID: 12351241}}, want: "@Username"},
{name: "NoUserName", args: args{user: &tb.User{Username: "", FirstName: "", ID: 12351241}}, want: "12351241"},
{name: "NoUserName", args: args{user: &tb.User{Username: "Username", FirstName: "", ID: 12351241}}, want: "@Username"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GetUserStr(tt.args.user); got != tt.want {
t.Errorf("GetUserStr() = %v, want %v", got, tt.want)
}
})
}
}
func BenchmarkGetUserName(b *testing.B) {
benchmarkGetUserStr(&tb.User{Username: "dawg", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrNoUsername(b *testing.B) {
benchmarkGetUserStr(&tb.User{Username: "", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrNoFirstName(b *testing.B) {
benchmarkGetUserStr(&tb.User{Username: "", ID: 1235123, FirstName: ""}, b)
}
func benchmarkGetUserStr(s *tb.User, b *testing.B) {
for n := 0; n < b.N; n++ {
GetUserStr(s)
}
}
func TestGetUserStrMd(t *testing.T) {
type args struct {
user *tb.User
}
tests := []struct {
name string
args args
want string
}{
{name: "NoUserName", args: args{user: &tb.User{FirstName: "BotUser", ID: 12351241}}, want: "[BotUser](tg://user?id=12351241)"},
{name: "UserName", args: args{user: &tb.User{Username: "Username", FirstName: "BotUser", ID: 12351241}}, want: "@Username"},
{name: "NoUserName", args: args{user: &tb.User{Username: "", FirstName: "", ID: 12351241}}, want: "[12351241](tg://user?id=12351241)"},
{name: "NoUserName", args: args{user: &tb.User{Username: "Username", FirstName: "", ID: 12351241}}, want: "@Username"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GetUserStrMd(tt.args.user); got != tt.want {
t.Errorf("GetUserStr() = %v, want %v", got, tt.want)
}
})
}
}
func BenchmarkGetUserStrMdName(b *testing.B) {
benchmarkGetUserStrMd(&tb.User{Username: "dawg", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrMdNoUsername(b *testing.B) {
benchmarkGetUserStrMd(&tb.User{Username: "", ID: 1235123, FirstName: "adolf"}, b)
}
func BenchmarkGetUserStrMdNoFirstName(b *testing.B) {
benchmarkGetUserStrMd(&tb.User{Username: "", ID: 1235123, FirstName: ""}, b)
}
func benchmarkGetUserStrMd(s *tb.User, b *testing.B) {
for n := 0; n < b.N; n++ {
GetUserStrMd(s)
}
}