Session fixes, working upload scenario

master
Chakib Benziane 5 years ago
parent fd7cec6600
commit 314e3b7624

@ -18,6 +18,9 @@ func sessionHandler(c *gin.Context) {
session := sessions.Default(c) session := sessions.Default(c)
lastUp := session.Get(storage.SessLastUploadName) lastUp := session.Get(storage.SessLastUploadName)
session.Clear()
session.Save()
if lastUp != nil { if lastUp != nil {
// Get upload status // Get upload status

@ -51,7 +51,7 @@ func NewAPI() *API {
panic(err) panic(err)
} }
router.Use(sessions.Sessions("websocket-session", sessionStore)) router.Use(sessions.Sessions("bit4sat-session", sessionStore))
// //
// //

@ -0,0 +1,2 @@
//TODO: cache price rates for faster invoices
package btc

@ -5,7 +5,7 @@ const (
WatchInvoicesChannelName = "watch_invoices" WatchInvoicesChannelName = "watch_invoices"
WebsocketPubSubPrefix = "websocket_update" WebsocketPubSubPrefix = "websocket_update"
UploadUpdateChannelPrefix = "upload_update" UploadUpdateChannelPrefix = "upload_update"
InvoicePaidChannelPrefix = "invoice:paid" InvoicePaidChannelPrefix = "invoice@paid"
) )
// PubSub event types // PubSub event types

@ -56,7 +56,7 @@ func PollPaidInvoice(invoiceId string, invoicePaidChan chan<- *Invoice, errorCha
watchPaidChannel := make(chan radix.PubSubMessage) watchPaidChannel := make(chan radix.PubSubMessage)
busName := fmt.Sprintf("%s_*", bus.InvoicePaidChannelPrefix) busName := fmt.Sprintf("%s:*", bus.InvoicePaidChannelPrefix)
err := db.DB.RedisPubSub.PSubscribe(watchPaidChannel, busName) err := db.DB.RedisPubSub.PSubscribe(watchPaidChannel, busName)
if err != nil { if err != nil {
@ -66,8 +66,14 @@ func PollPaidInvoice(invoiceId string, invoicePaidChan chan<- *Invoice, errorCha
for { for {
msg := <-watchPaidChannel msg := <-watchPaidChannel
//log.Printf("received message on %s", msg.Channel)
targetInvoiceId := strings.Split(msg.Channel, "_")[1] split := strings.Split(msg.Channel, ":")
if len(split) != 2 {
errorChan <- fmt.Errorf("error in pubsub channel parsing %s", msg.Channel)
}
targetInvoiceId := strings.Split(msg.Channel, ":")[1]
//log.Printf("target invoice is %s", targetInvoiceId)
if targetInvoiceId == invoiceId { if targetInvoiceId == invoiceId {
invoice := Invoice{} invoice := Invoice{}
@ -84,6 +90,7 @@ func PollPaidInvoice(invoiceId string, invoicePaidChan chan<- *Invoice, errorCha
} }
} }
} }
func PollPaidInvoiceTMP(invoiceId string, invoiceChan chan<- *Invoice, errorChan chan<- error) { func PollPaidInvoiceTMP(invoiceId string, invoiceChan chan<- *Invoice, errorChan chan<- error) {

@ -4,6 +4,7 @@ import (
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"strconv" "strconv"
"time" "time"
@ -92,6 +93,7 @@ type Invoice struct {
Msatoshi float64 `json:"msatoshi"` Msatoshi float64 `json:"msatoshi"`
Payreq string `json:"payreq"` Payreq string `json:"payreq"`
RHash string `json:"rhash"` RHash string `json:"rhash"`
PreImage string `json:"-"` // used as secret admin token
Status string `json:"status"` Status string `json:"status"`
PaidAt timestamp `json:"paid_at"` PaidAt timestamp `json:"paid_at"`
CreatedAt timestamp `json:"created_at"` CreatedAt timestamp `json:"created_at"`
@ -112,12 +114,14 @@ func (i *Invoice) UnmarshalBinary(b []byte) error {
// Create new Invoice from lnrpc.Invoice // Create new Invoice from lnrpc.Invoice
func InvoiceFromLndIn(lndInvoice *lnrpc.Invoice) *Invoice { func InvoiceFromLndIn(lndInvoice *lnrpc.Invoice) *Invoice {
log.Println(hex.EncodeToString(lndInvoice.RPreimage))
invoice := Invoice{ invoice := Invoice{
AddIndex: lndInvoice.AddIndex, AddIndex: lndInvoice.AddIndex,
Description: lndInvoice.GetMemo(), Description: lndInvoice.GetMemo(),
Msatoshi: float64(lndInvoice.Value * 1000), Msatoshi: float64(lndInvoice.Value * 1000),
Payreq: lndInvoice.PaymentRequest, Payreq: lndInvoice.PaymentRequest,
RHash: hex.EncodeToString(lndInvoice.RHash), RHash: hex.EncodeToString(lndInvoice.RHash),
PreImage: hex.EncodeToString(lndInvoice.RPreimage),
CreatedAt: timestamp(time.Unix(lndInvoice.CreationDate, 0)), CreatedAt: timestamp(time.Unix(lndInvoice.CreationDate, 0)),
Status: InvoiceStatus[UnPaid], Status: InvoiceStatus[UnPaid],
} }

@ -81,6 +81,7 @@ func (ctrl UploadCtrl) New(c *gin.Context) {
// Set the uploadId as last upload for session // Set the uploadId as last upload for session
session.Set(SessLastUploadName, uploadId) session.Set(SessLastUploadName, uploadId)
//session.AddFlash(SessLastUploadName, uploadId)
session.Save() session.Save()
// If not free upload generate a an invoice // If not free upload generate a an invoice
@ -94,6 +95,13 @@ func (ctrl UploadCtrl) New(c *gin.Context) {
return return
} }
// Save the secret admin token
err = SetUploadAdminToken(uploadId, invoice.PreImage)
if err != nil {
utils.JSONErrPriv(c, http.StatusInternalServerError, err)
return
}
// Update Upload Invoice // Update Upload Invoice
err = SetUploadInvoice(uploadId, invoice) err = SetUploadInvoice(uploadId, invoice)
if err != nil { if err != nil {
@ -263,10 +271,23 @@ func (ctrl UploadCtrl) PollStatus(c *gin.Context) {
return return
} }
// get the secret admin token
token, err := GetUploadAdminToken(uploadId)
if err != nil {
utils.JSONErrPriv(c, http.StatusInternalServerError, err)
return
}
// Clear the session
session := sessions.Default(c)
session.Clear()
session.Save()
// invoice was paid // invoice was paid
c.JSON(http.StatusAccepted, gin.H{ c.JSON(http.StatusAccepted, gin.H{
"status": uploadStatus, "status": uploadStatus,
"invoice": invoice, "invoice": invoice,
"admin_token": token,
}) })
return return
@ -421,8 +442,8 @@ func (ctrl UploadCtrl) Upload(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"status": http.StatusOK, "status": http.StatusOK,
"result": "uploaded",
"store_status": UpStored, "store_status": UpStored,
"upload_id": uploadId,
}) })
} }

@ -261,6 +261,19 @@ func GetUploadStatus(id string) (status UpStatus, err error) {
return return
} }
func SetUploadAdminToken(uploadId, token string) error {
key := fmt.Sprintf("upload_admin_%s", uploadId)
return DB.Redis.Do(radix.FlatCmd(nil, "SET", key, token))
}
func GetUploadAdminToken(uploadId string) (string, error) {
var token string
key := fmt.Sprintf("upload_admin_%s", uploadId)
err := DB.Redis.Do(radix.FlatCmd(&token, "GET", key))
return token, err
}
func SetUploadInvoice(uploadId string, invoice *ln.Invoice) error { func SetUploadInvoice(uploadId string, invoice *ln.Invoice) error {
uploadInvoiceKey := fmt.Sprintf("upload_%s_invoice", uploadId) uploadInvoiceKey := fmt.Sprintf("upload_%s_invoice", uploadId)

@ -46,13 +46,14 @@ func WatchInvoice() {
// Get the last invoice index cursor // Get the last invoice index cursor
cursor := getLastSettledInvoiceIndex() cursor := getLastSettledInvoiceIndex()
log.Println(cursor)
ctxb := context.Background() ctxb := context.Background()
client, cleanUp := lndrpc.GetClient() client, cleanUp := lndrpc.GetClient()
defer cleanUp() defer cleanUp()
subscription := &lnrpc.InvoiceSubscription{} subscription := &lnrpc.InvoiceSubscription{
SettleIndex: cursor,
}
invoiceStream, err := client.SubscribeInvoices(ctxb, subscription) invoiceStream, err := client.SubscribeInvoices(ctxb, subscription)
if err != nil { if err != nil {
@ -155,7 +156,7 @@ func handleSettledInvoice(invoice *lnrpc.Invoice) {
// publish invoice was updated to upload_id_paid channel // publish invoice was updated to upload_id_paid channel
log.Printf("Notifying invoice paid %s", uploadId) log.Printf("Notifying invoice paid %s", uploadId)
key := fmt.Sprintf("%s_%s", bus.InvoicePaidChannelPrefix, key := fmt.Sprintf("%s:%s", bus.InvoicePaidChannelPrefix,
newInvoice.RHash) newInvoice.RHash)
err = db.DB.Redis.Do(radix.FlatCmd(nil, "PUBLISH", err = db.DB.Redis.Do(radix.FlatCmd(nil, "PUBLISH",

Loading…
Cancel
Save