86 lines
1.9 KiB
Go
86 lines
1.9 KiB
Go
package watchers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
|
|
"git.sp4ke.com/sp4ke/bit4sat/bus"
|
|
"git.sp4ke.com/sp4ke/bit4sat/db"
|
|
"git.sp4ke.com/sp4ke/bit4sat/ln"
|
|
"git.sp4ke.com/sp4ke/bit4sat/storage"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/mediocregopher/radix/v3"
|
|
)
|
|
|
|
type InvoiceWatcher struct {
|
|
listenWatchInvoice chan radix.PubSubMessage
|
|
invoicePaid chan *ln.Invoice
|
|
}
|
|
|
|
func (w *InvoiceWatcher) Run() {
|
|
if err := db.DB.RedisPubSub.Subscribe(w.listenWatchInvoice,
|
|
bus.WatchInvoicesChannelName); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
for {
|
|
select {
|
|
case msg := <-w.listenWatchInvoice:
|
|
log.Printf("checking new invoice %s", msg.Message)
|
|
|
|
invoice := ln.Invoice{}
|
|
err := json.Unmarshal(msg.Message, &invoice)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
//TODO: kill goroutine if listening websocket dies
|
|
go ln.PollPaidInvoice(&invoice, w.invoicePaid)
|
|
|
|
case invoice := <-w.invoicePaid:
|
|
log.Printf("recevied update for invoice <%s>", invoice.UploadId)
|
|
// Set upload status to UpWaitingStorage (paid)
|
|
err := storage.SetUploadStatus(invoice.UploadId, storage.UpWaitingStorage)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// Update Upload Invoice
|
|
err = storage.SetUploadInvoice(invoice.UploadId, invoice)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// publish invoice was updated to upload_id_paid channel
|
|
msg := bus.Message{}
|
|
msg.Type = bus.PaymentReceived
|
|
msg.UploadId = invoice.UploadId
|
|
msg.Data = gin.H{
|
|
"invoice": invoice,
|
|
}
|
|
|
|
msgJson, err := json.Marshal(msg)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
log.Printf("Notifying upload paid %s", invoice.UploadId)
|
|
key := fmt.Sprintf("%s_%s", bus.UploadUpdateChannelPrefix,
|
|
invoice.UploadId)
|
|
|
|
err = db.DB.Redis.Do(radix.FlatCmd(nil, "PUBLISH",
|
|
key, msgJson))
|
|
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func NewInvoiceWatcher() *InvoiceWatcher {
|
|
return &InvoiceWatcher{
|
|
listenWatchInvoice: make(chan radix.PubSubMessage),
|
|
invoicePaid: make(chan *ln.Invoice),
|
|
}
|
|
}
|