2023-01-19 05:44:06 +00:00
|
|
|
package v1
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"image/png"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
"github.com/hay-kot/homebox/backend/internal/web/adapters"
|
2023-04-09 18:39:43 +00:00
|
|
|
"github.com/hay-kot/httpkit/errchain"
|
2023-01-19 05:44:06 +00:00
|
|
|
"github.com/yeqown/go-qrcode/v2"
|
|
|
|
"github.com/yeqown/go-qrcode/writer/standard"
|
|
|
|
|
|
|
|
_ "embed"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed assets/QRIcon.png
|
|
|
|
var qrcodeLogo []byte
|
|
|
|
|
|
|
|
// HandleGenerateQRCode godoc
|
|
|
|
//
|
2023-03-07 06:18:58 +00:00
|
|
|
// @Summary Create QR Code
|
2023-01-19 05:44:06 +00:00
|
|
|
// @Tags Items
|
|
|
|
// @Produce json
|
|
|
|
// @Param data query string false "data to be encoded into qrcode"
|
|
|
|
// @Success 200 {string} string "image/jpeg"
|
|
|
|
// @Router /v1/qrcode [GET]
|
|
|
|
// @Security Bearer
|
2023-03-21 04:32:10 +00:00
|
|
|
func (ctrl *V1Controller) HandleGenerateQRCode() errchain.HandlerFunc {
|
|
|
|
type query struct {
|
|
|
|
// 4,296 characters is the maximum length of a QR code
|
|
|
|
Data string `schema:"data" validate:"required,max=4296"`
|
|
|
|
}
|
2023-01-19 05:44:06 +00:00
|
|
|
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) error {
|
2023-03-21 04:32:10 +00:00
|
|
|
q, err := adapters.DecodeQuery[query](r)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-01-19 05:44:06 +00:00
|
|
|
|
|
|
|
image, err := png.Decode(bytes.NewReader(qrcodeLogo))
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
qrc, err := qrcode.New(q.Data)
|
2023-01-19 05:44:06 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
toWriteCloser := struct {
|
|
|
|
io.Writer
|
|
|
|
io.Closer
|
|
|
|
}{
|
|
|
|
Writer: w,
|
|
|
|
Closer: io.NopCloser(nil),
|
|
|
|
}
|
|
|
|
|
|
|
|
qrwriter := standard.NewWithWriter(toWriteCloser, standard.WithLogoImage(image))
|
|
|
|
|
|
|
|
// Return the QR code as a jpeg image
|
|
|
|
w.Header().Set("Content-Type", "image/jpeg")
|
|
|
|
w.Header().Set("Content-Disposition", "attachment; filename=qrcode.jpg")
|
|
|
|
return qrc.Save(qrwriter)
|
|
|
|
}
|
|
|
|
}
|