From 14963269dc63bf038163a851e521d6815ab5f514 Mon Sep 17 00:00:00 2001 From: Julio Capote Date: Sat, 7 Jan 2023 17:54:38 -0500 Subject: avatar support --- models/avatar.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 models/avatar.go (limited to 'models/avatar.go') diff --git a/models/avatar.go b/models/avatar.go new file mode 100644 index 0000000..65c690f --- /dev/null +++ b/models/avatar.go @@ -0,0 +1,71 @@ +package models + +import ( + "bytes" + "encoding/gob" + "fmt" + + "git.capotej.com/capotej/communique/config" + "github.com/dgraph-io/badger/v3" +) + +type Avatar struct { + Handler config.Handler + ContentType string + Bytes []byte +} + +// used for lookup purposes (count, collect, find) +func NewAvatar(h config.Handler) *Avatar { + aso := &Avatar{Handler: h} + return aso +} + +func CreateAvatar(h config.Handler, contentType string, bytes []byte) (*Avatar, error) { + aso := &Avatar{ + Handler: h, + ContentType: contentType, + Bytes: bytes, + } + return aso, nil +} + +func (a *Avatar) Name() string { + return "Avatar" +} + +func (a *Avatar) Key() string { + keyBase := fmt.Sprintf("avatars:%s", a.Handler.Name) + return keyBase +} + +func (a *Avatar) DedupKey() string { + return a.Key() +} + +func (a *Avatar) Keybase() string { + return a.Key() +} + +func (a *Avatar) SaveDedup(txn *badger.Txn) error { + txn.Discard() // nothing to do here + return nil +} + +func (a *Avatar) Save(txn *badger.Txn) error { + if a.Bytes == nil { + return fmt.Errorf("bytes not set") + } + if a.ContentType == "" { + return fmt.Errorf("content type not set") + } + + var network bytes.Buffer + enc := gob.NewEncoder(&network) + err := enc.Encode(a) + if err != nil { + return fmt.Errorf("could not encode Avatar: %w", err) + } + e := badger.NewEntry([]byte(a.Key()), network.Bytes()) + return txn.SetEntry(e) +} -- cgit v1.2.3