You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bit4sat/api/download.go

113 lines
2.3 KiB
Go

package api
import (
"fmt"
"log"
"net/http"
"git.sp4ke.com/sp4ke/bit4sat/ln"
"git.sp4ke.com/sp4ke/bit4sat/storage"
"git.sp4ke.com/sp4ke/bit4sat/utils"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
func DownloadHandler(c *gin.Context) {
dlId := c.Param("dlId")
// Get upload id for dl id
upId, err := storage.GetUploadIdForDlId(dlId)
if err != nil {
utils.JSONErr(c, http.StatusNotFound, "this file does not exist anymore")
return
}
// Get the upload session
session, err := SessionStore.Get(c.Request, DlSessionKey)
if err != nil {
utils.JSONErrPriv(c, http.StatusInternalServerError, err)
return
}
dlSess, exists := session.Values["session-id"]
log.Printf("%#v", dlSess)
// Test if we are alread in a download session
if !exists {
// This is a new download session
log.Println("new download session")
// Create a unique session id for this download session
sessId, err := storage.GetShortId()
if err != nil {
utils.JSONErrPriv(c, http.StatusInternalServerError, err)
return
}
log.Printf("going to generate invoice for %s", upId)
session.AddFlash(sessId, "session-id")
session.Save(c.Request, c.Writer)
if err != nil {
utils.JSONErrPriv(c, http.StatusInternalServerError, err)
return
}
//TODO: use fee asked by uploader
//
// Get upload fee asked by uploader
//
invoiceOpts := ln.InvoiceOpts{
Amount: 100,
Curr: ln.CurSat,
Memo: fmt.Sprintf("bit4sat download: %s", sessId),
}
invoice, err := ln.NewInvoice(invoiceOpts)
if err != nil {
utils.JSONErrPriv(c, http.StatusInternalServerError, err)
return
}
// This is a returning download session to pay the invoice
//
c.JSON(http.StatusPaymentRequired, gin.H{
"invoice_rhash": invoice.RHash,
})
} else {
log.Printf("continue download session id: %s", dlSess)
session.Flashes("session-id")
err = session.Save(c.Request, c.Writer)
if err != nil {
utils.JSONErrPriv(c, http.StatusInternalServerError, err)
return
}
c.Status(http.StatusOK)
}
return
}
func TestDownHandler(c *gin.Context) {
sess := sessions.Default(c)
test := sess.Get("test")
log.Printf("%#v", test)
if test != nil {
sess.Clear()
sess.Save()
c.String(http.StatusOK, "I remember you")
} else {
sess.Set("test", 1)
sess.Save()
c.String(http.StatusOK, "i dont remember you")
}
return
}