well-goknown/lightningpub/well-known.go

87 lines
2.5 KiB
Go

package lightningpub
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"git.devvul.com/asara/gologger"
"git.devvul.com/asara/well-goknown/config"
"github.com/jmoiron/sqlx"
)
var (
DB *sqlx.DB
)
type lnurlp struct {
Tag string `json:"tag"`
Callback string `json:"callback"`
MaxSendable int64 `json:"maxSendable"`
MinSendable int64 `json:"minSendable"`
Metadata string `json:"metadata"`
AllowsNostr bool `json:"allowsNostr"`
NostrPubkey string `json:"nostrPubkey"`
}
func GetLnurlp(w http.ResponseWriter, r *http.Request) {
l := gologger.Get(config.GetConfig().LogLevel).With().Caller().Logger()
// normalize domain
domain, _, err := net.SplitHostPort(r.Host)
if err != nil {
domain = r.Host
}
name := r.PathValue("name")
var lnwallet string
err = DB.QueryRow("SELECT wallet FROM lnwallets WHERE name=$1 AND domain=$2", name, domain).Scan(&lnwallet)
if err != nil {
l.Debug().Msgf("user (%s@%s) doesn't exist: %s", name, domain, err.Error())
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
//upstreamUrl := fmt.Sprintf("https://%s/api/guest/lnurl_pay/info?k1=%s", domain, lnwallet)
upstreamUrl := fmt.Sprintf("https://%s/api/guest/lnurl_pay/info?k1=%s", domain, lnwallet)
upstreamPayload, err := http.Get(upstreamUrl)
if err != nil {
l.Debug().Msgf("user (%s@%s) doesn't exist: %s", name, domain, err.Error())
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
defer upstreamPayload.Body.Close()
body, err := ioutil.ReadAll(upstreamPayload.Body)
if err != nil {
l.Debug().Msgf("user (%s@%s) doesn't exist: %s", name, domain, err.Error())
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
lnurlpReturn := lnurlp{}
err = json.Unmarshal(body, &lnurlpReturn)
if err != nil {
l.Debug().Msgf("user (%s@%s) doesn't exist: %s", name, domain, err.Error())
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
m := fmt.Sprintf("[[\"text/plain\", \"ln address payment to a user on the devvul server\"],[\"text/identifier\", \"%s@%s\"]]", name, domain)
lnurlpReturn.Metadata = m
ret, err := json.Marshal(lnurlpReturn)
if err != nil {
l.Debug().Msgf("user (%s@%s) doesn't exist: %s", name, domain, err.Error())
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
l.Debug().Msgf("returning lnwallet for %s@%s", name, domain)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(ret)
return
}