This commit is contained in:
80
invitationinitpayload.go
Normal file
80
invitationinitpayload.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package meowlib
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/makiuchi-d/gozxing"
|
||||
"github.com/makiuchi-d/gozxing/qrcode"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"image/png"
|
||||
)
|
||||
|
||||
func (p *InvitationInitPayload) Serialize() ([]byte, error) {
|
||||
return proto.Marshal(p)
|
||||
}
|
||||
|
||||
func (p *InvitationInitPayload) Compress() ([]byte, error) {
|
||||
out, err := p.Serialize()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var b bytes.Buffer
|
||||
gz, err := gzip.NewWriterLevel(&b, gzip.BestCompression)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := gz.Write(out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
func NewInvitationInitPayloadFromCompressed(compressed []byte) (*InvitationInitPayload, error) {
|
||||
p := &InvitationInitPayload{}
|
||||
reader := bytes.NewReader(compressed)
|
||||
gzreader, err := gzip.NewReader(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
output, err := io.ReadAll(gzreader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := proto.Unmarshal(output, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *InvitationInitPayload) WriteCompressed(filename string) error {
|
||||
out, err := p.Compress()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(filename, out, 0600)
|
||||
}
|
||||
|
||||
func (p *InvitationInitPayload) WriteQr(filename string) error {
|
||||
data, err := p.Compress()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
qwriter := qrcode.NewQRCodeWriter()
|
||||
code, err := qwriter.Encode(string(data), gozxing.BarcodeFormat_QR_CODE, 512, 512, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
return png.Encode(file, code)
|
||||
}
|
||||
Reference in New Issue
Block a user