WIP: adding downloadMyProfilePicture and botProfilePicture to LNURL Meta (#297)

* adding downloadMyProfilePicture and botProfilePicture to serveLNURLFirst (pay)

* fix image download to ram

* add downloadProfilePicture

* add cache and download limit

* error checks

* user picture

* empty entry bug check for uuid

* check

* fix example

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
This commit is contained in:
gohumble
2022-02-11 10:04:08 +01:00
committed by GitHub
co-authored by callebtc
parent 2b09fc95dd
commit 725af545ab
14 changed files with 244 additions and 26 deletions
+2 -1
View File
@@ -2,6 +2,7 @@ bot:
http_proxy: ""
lnurl_public_host_name: "mylnurl.com"
lnurl_server: "https://mylnurl.com"
lnurl_image: true
telegram:
message_dispose_duration: 10
api_key: "1234"
@@ -15,4 +16,4 @@ database:
db_path: "data/bot.db"
buntdb_path: "data/bunt.db"
transactions_path: "data/transactions.db"
shop_buntdb_path: "data/shop.db"
shop_buntdb_path: "data/shop.db"
+1
View File
@@ -12,6 +12,7 @@ require (
github.com/imroc/req v0.3.0
github.com/jinzhu/configor v1.2.1
github.com/makiuchi-d/gozxing v0.0.2
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
github.com/nicksnyder/go-i18n/v2 v2.1.2
github.com/orcaman/concurrent-map v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
+2
View File
@@ -365,6 +365,8 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/nicksnyder/go-i18n/v2 v2.1.2 h1:QHYxcUJnGHBaq7XbvgunmZ2Pn0focXFqTD61CkH146c=
github.com/nicksnyder/go-i18n/v2 v2.1.2/go.mod h1:d++QJC9ZVf7pa48qrsRWhMJ5pSHIPmS3OLqK1niyLxs=
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
+1
View File
@@ -22,6 +22,7 @@ type BotConfiguration struct {
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
}
type TelegramConfiguration struct {
+18
View File
@@ -42,3 +42,21 @@ func MigrateAnonIdSha265Hash(db *gorm.DB) error {
}
return nil
}
func MigrateUUIDSha265Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
pw := u.Wallet.ID
uuid := str.UUIDSha256(&u)
log.Infof("[MigrateUUIDSha265Hash] %s -> %s", pw, uuid)
u.UUID = uuid
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateUUIDSha265Hash] Error: Couldn't migrate user %s (%s)", u.Telegram.Username, pw)
log.Errorln(errmsg)
return tx.Error
}
}
return nil
}
+1
View File
@@ -31,6 +31,7 @@ type User struct {
UpdatedAt time.Time `json:"updated"`
AnonID string `json:"anon_id"`
AnonIDSha256 string `json:"anon_id_sha256"`
UUID string `json:"uuid"`
Banned bool `json:"banned"`
}
+95 -19
View File
@@ -10,6 +10,9 @@ import (
"strings"
"time"
"github.com/eko/gocache/store"
tb "gopkg.in/lightningtipbot/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -40,11 +43,13 @@ type Invoice struct {
PaidAt time.Time `json:"paid_at"`
}
type Lnurl struct {
telegram *tb.Bot
c *lnbits.Client
database *gorm.DB
callbackHostname *url.URL
buntdb *storage.DB
WebhookServer string
cache telegram.Cache
}
func New(bot *telegram.TipBot) Lnurl {
@@ -54,6 +59,8 @@ func New(bot *telegram.TipBot) Lnurl {
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
buntdb: bot.Bunt,
telegram: bot.Telegram,
cache: bot.Cache,
}
}
func (lnurlInvoice Invoice) Key() string {
@@ -103,6 +110,30 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
api.NotFoundHandler(writer, err)
}
}
func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
key := fmt.Sprintf("lnurl_metadata_%s", username)
// load metadata from cache
if m, err := w.cache.Get(key); err == nil {
return m.(lnurl.Metadata)
}
// otherwise, create new metadata
metadata := w.metaData(username)
// load the user profile picture
if internal.Configuration.Bot.LNURLSendImage {
// get the user from the database
user, tx := findUser(w.database, username)
if tx.Error == nil && user.Telegram != nil {
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
}
}
// save into cache
runtime.IgnoreError(w.cache.Set(key, metadata, &store.Options{Expiration: 12 * time.Hour}))
return metadata
}
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
@@ -112,7 +143,9 @@ func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error)
if err != nil {
return nil, err
}
metadata := w.metaData(username)
// produce the metadata including the image
metadata := w.getMetaDataCached(username)
return &lnurl.LNURLPayParams{
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
@@ -123,7 +156,6 @@ func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error)
EncodedMetadata: metadata.Encode(),
CommentAllowed: CommentAllowed,
}, nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
@@ -145,22 +177,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
}, fmt.Errorf("comment too long")
}
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := w.database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's anon_id
tx = w.database.Where("anon_id = ?", username).First(user)
} else if strings.HasPrefix(username, "0x") {
// asume it's anon_id_sha256
tx = w.database.Where("anon_id_sha256 = ?", username).First(user)
} else {
// assume it's a string @username
tx = w.database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
user, tx := findUser(w.database, username)
if tx.Error != nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
@@ -181,7 +198,8 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
var resp *lnurl.LNURLPayValues
// the same description_hash needs to be built in the second request
metadata := w.metaData(username)
metadata := w.getMetaDataCached(username)
descriptionHash, err := w.descriptionHash(metadata)
if err != nil {
return nil, err
@@ -242,8 +260,66 @@ func (w Lnurl) descriptionHash(metadata lnurl.Metadata) (string, error) {
// metaData returns the metadata that is sent in the first response
// and is used again in the second response to verify the description hash
func (w Lnurl) metaData(username string) lnurl.Metadata {
// this is a bit stupid but if the address is a UUID starting with 1x...
// we actually want to find the users username so it looks nicer in the
// metadata description
if strings.HasPrefix(username, "1x") {
user, _ := findUser(w.database, username)
if user.Telegram.Username != "" {
username = user.Telegram.Username
}
}
return lnurl.Metadata{
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
}
}
// addImageMetaData add images an image to the LNURL metadata
func addImageToMetaData(tb *tb.Bot, metadata *lnurl.Metadata, username string, user *tb.User) {
metadata.Image.Ext = "jpeg"
// if the username is anonymous, add the bot's avatar
if isAnonUsername(username) {
metadata.Image.Bytes = telegram.BotProfilePicture
return
}
// if the user has a profile picture, add it
picture, err := telegram.DownloadProfilePicture(tb, user)
if err != nil {
log.Errorf("[LNURL] Couldn't download user %s's profile picture: %v", username, err)
return
}
metadata.Image.Bytes = picture
}
func isAnonUsername(username string) bool {
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
return true
} else {
return strings.HasPrefix(username, "0x")
}
}
func findUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's anon_id
tx = database.Where("anon_id = ?", username).First(user)
} else if strings.HasPrefix(username, "0x") {
// asume it's anon_id_sha256
tx = database.Where("anon_id_sha256 = ?", username).First(user)
} else if strings.HasPrefix(username, "1x") {
// asume it's uuid
tx = database.Where("uuid = ?", username).First(user)
} else {
// assume it's a string @username
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
return user, tx
}
+7
View File
@@ -48,3 +48,10 @@ func AnonIdSha256(u *lnbits.User) string {
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
return anon_id
}
func UUIDSha256(u *lnbits.User) string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
return anon_id
}
+3
View File
@@ -121,6 +121,9 @@ func (bot *TipBot) Start() {
// register telegram handlers
bot.registerTelegramHandlers()
// download bot avatar once
bot.downloadMyProfilePicture()
// edit worker collects messages to edit and
// periodically edits them
bot.startEditWorker()
+19 -1
View File
@@ -70,6 +70,18 @@ func ColumnMigrationTasks(db *gorm.DB) error {
err = database.MigrateAnonIdSha265Hash(db)
}
// uuid migration (2022-02-11)
if !db.Migrator().HasColumn(&lnbits.User{}, "uuid") {
// first we need to auto migrate the user. This will create uuid column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running UUID database migrations ...")
// run the migration on uuid
err = database.MigrateUUIDSha265Hash(db)
}
// todo -- add more database field migrations here in the future
return err
}
@@ -209,7 +221,7 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
if user.AnonIDSha256 == "" {
debugStack()
user.AnonIDSha256 = str.AnonIdSha256(user)
log.Errorf("[UpdateUserRecord] AnonIDSha256 empty! Setting to: %s", user.AnonID)
log.Errorf("[UpdateUserRecord] AnonIDSha256 empty! Setting to: %s", user.AnonIDSha256)
}
// TODO -- Remove this after empty anon id bug is identified
if user.AnonID == "" {
@@ -217,6 +229,12 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
log.Errorf("[UpdateUserRecord] AnonID empty! Setting to: %s", user.AnonID)
}
// TODO -- Remove this after empty anon id bug is identified
if user.UUID == "" {
debugStack()
user.UUID = str.UUIDSha256(user)
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
}
tx := bot.Database.Save(user)
if tx.Error != nil {
+2 -2
View File
@@ -331,13 +331,13 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
}()
// build faucet message
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, GetUserStrMd(inlineFaucet.From.Telegram), inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
memo := inlineFaucet.Memo
if len(memo) > 0 {
inlineFaucet.Message = inlineFaucet.Message + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetAppendMemo"), memo)
}
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStr(bot.Telegram.Me))
}
// update message
log.Infoln(inlineFaucet.Message)
+14 -2
View File
@@ -95,6 +95,18 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) (context.Con
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
bot.tryDeleteMessage(statusMsg)
// display the metadata image from the first LNURL-p response
if len(payParams.LNURLPayParams.Metadata.Image.Bytes) > 0 {
bot.trySendMessage(m.Sender, &tb.Photo{
File: tb.File{FileReader: bytes.NewReader(payParams.LNURLPayParams.Metadata.Image.Bytes)},
Caption: fmt.Sprintf("%s", payParams.LNURLPayParams.Metadata.Description)})
} else if len(payParams.LNURLPayParams.Metadata.Description) > 0 {
// display the metadata text from the first LNURL-p response
// if there was no photo in the last step
bot.trySendMessage(m.Sender, fmt.Sprintf("`%s`", payParams.LNURLPayParams.Metadata.Description))
}
// ask whether to make payment
bot.lnurlPayHandler(ctx, m, *payParams)
case lnurl.LNURLWithdrawResponse:
@@ -128,7 +140,7 @@ func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error
}
func UserGetLNURL(user *lnbits.User) (string, error) {
name := fmt.Sprint(user.AnonIDSha256)
name := fmt.Sprint(user.UUID)
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
@@ -158,7 +170,7 @@ func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) (conte
}
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
// send the lnurl data to user
// send the lnurl QR code
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
return ctx, nil
}
+76 -1
View File
@@ -1,16 +1,21 @@
package telegram
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"image"
"image/jpeg"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
"github.com/nfnt/resize"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
@@ -79,3 +84,73 @@ func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) (context.Con
}
return ctx, nil
}
// DownloadProfilePicture downloads a profile picture from Telegram.
// This is a public function because it is used in another package (lnurl)
func DownloadProfilePicture(telegram *tb.Bot, user *tb.User) ([]byte, error) {
photo, err := ProfilePhotosOf(telegram, user)
if err != nil {
log.Errorf("[DownloadProfilePicture] %v", err)
return nil, err
}
if len(photo) == 0 {
log.Error("[DownloadProfilePicture] No profile picture found")
return nil, err
}
buf := new(bytes.Buffer)
reader, err := telegram.GetFile(&photo[0].File)
if err != nil {
log.Errorf("[DownloadProfilePicture] %v", err)
return nil, err
}
img, err := jpeg.Decode(reader)
if err != nil {
log.Errorf("[DownloadProfilePicture] %v", err)
return nil, err
}
// resize image
img = resize.Thumbnail(100, 100, img, resize.Lanczos3)
err = jpeg.Encode(buf, img, nil)
return buf.Bytes(), nil
}
var BotProfilePicture []byte
// downloadMyProfilePicture downloads the profile picture of the bot
// and saves it in `BotProfilePicture`
func (bot *TipBot) downloadMyProfilePicture() error {
picture, err := DownloadProfilePicture(bot.Telegram, bot.Telegram.Me)
if err != nil {
log.Errorf("[downloadMyProfilePicture] %v", err)
return err
}
BotProfilePicture = picture
return nil
}
// ProfilePhotosOf returns list of profile pictures for a user.
func ProfilePhotosOf(bot *tb.Bot, user *tb.User) ([]tb.Photo, error) {
params := map[string]interface {
}{
"user_id": user.Recipient(),
"limit": 1,
}
data, err := bot.Raw("getUserProfilePhotos", params)
if err != nil {
return nil, err
}
var resp struct {
Result struct {
Count int `json:"total_count"`
Photos []tb.Photo `json:"photos"`
}
}
if err := json.Unmarshal(data, &resp); err != nil {
return nil, err
}
return resp.Result.Photos, nil
}
+3
View File
@@ -103,8 +103,11 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
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)