meowlib/client/peerstorage.go

240 lines
6.0 KiB
Go
Raw Normal View History

package client
//
// Storage
//
import (
"crypto/sha256"
"encoding/json"
2024-05-28 14:28:10 +02:00
"errors"
"path/filepath"
2024-05-28 14:28:10 +02:00
"sort"
"forge.redroom.link/yves/meowlib"
"github.com/dgraph-io/badger"
2024-05-28 16:47:04 +02:00
"github.com/google/uuid"
)
type PeerStorage struct {
DbFile string `json:"db_file,omitempty"`
db *badger.DB
2024-05-27 18:38:38 +02:00
cache map[string]*Peer
}
2024-05-28 14:28:10 +02:00
// Open the badger database from struct PeerStorage
func (ps *PeerStorage) open() error {
2024-05-28 16:47:04 +02:00
if ps.DbFile == "" {
ps.DbFile = uuid.New().String()
2024-05-28 17:25:10 +02:00
GetConfig().GetIdentity().Save()
2024-05-28 16:47:04 +02:00
}
if ps.cache == nil {
ps.cache = make(map[string]*Peer)
}
opts := badger.DefaultOptions(filepath.Join(GetConfig().StoragePath, GetConfig().GetIdentity().Uuid, ps.DbFile))
opts.Logger = nil
var err error
ps.db, err = badger.Open(opts)
if err != nil {
return err
}
return nil
}
2024-05-28 14:28:10 +02:00
// Store function StorePeer stores a peer in the badger database with Peer.Uid as key
func (ps *PeerStorage) StorePeer(peer *Peer) error {
err := ps.open()
if err != nil {
return err
}
defer ps.close()
// first marshal the Peer to bytes with protobuf
jsonsrv, err := json.Marshal(peer)
if err != nil {
return err
}
password := GetConfig().memoryPassword
if peer.dbPassword != "" {
password = peer.dbPassword
}
data, err := meowlib.SymEncrypt(password, jsonsrv)
if err != nil {
return err
}
shakey := sha256.Sum256([]byte(peer.Uid))
key := shakey[:]
2024-05-28 16:47:04 +02:00
// add it to cache
ps.cache[peer.Uid] = peer
// then store it in the database
return ps.db.Update(func(txn *badger.Txn) error {
return txn.Set(key, data)
})
}
2024-05-28 14:28:10 +02:00
// LoadPeer function loads a Peer from the badger database with Peer.GetUid() as key
func (ps *PeerStorage) LoadPeer(uid string, password string) (*Peer, error) {
var peer Peer
err := ps.open()
if err != nil {
return nil, err
}
defer ps.close()
shakey := sha256.Sum256([]byte(uid))
key := shakey[:]
err = ps.db.View(func(txn *badger.Txn) error {
item, err := txn.Get(key)
if err != nil {
return err
}
return item.Value(func(val []byte) error {
jsonsrv, err := meowlib.SymDecrypt(password, val)
if err != nil {
return err
}
return json.Unmarshal(jsonsrv, &peer)
})
})
return &peer, err
}
2024-05-28 14:28:10 +02:00
// DeletePeer function deletes a Peer from the badger database with Peer.GetUid() as key
func (ps *PeerStorage) DeletePeer(uid string) error {
err := ps.open()
if err != nil {
return err
}
defer ps.close()
shakey := sha256.Sum256([]byte(uid))
key := shakey[:]
return ps.db.Update(func(txn *badger.Txn) error {
return txn.Delete(key)
})
}
2024-05-28 14:28:10 +02:00
// LoadPeers function loads Peers from the badger database with a specific password
func (ps *PeerStorage) LoadPeers(password string) ([]*Peer, error) {
var peers []*Peer
err := ps.open()
if err != nil {
return nil, err
}
defer ps.close()
err = ps.db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchSize = 10
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
var sc Peer
err := item.Value(func(val []byte) error {
jsonsrv, err := meowlib.SymDecrypt(password, val)
if err != nil {
return err
}
return json.Unmarshal(jsonsrv, &sc)
})
2024-05-28 18:39:32 +02:00
if err == nil {
peers = append(peers, &sc)
2024-05-28 14:28:10 +02:00
ps.cache[sc.Uid] = &sc
}
}
return nil
})
2024-05-28 14:28:10 +02:00
// Sort peers based on peer.Name
sort.Slice(peers, func(i, j int) bool {
return peers[i].Name < peers[j].Name
})
return peers, err
}
2024-05-28 14:28:10 +02:00
// GetPeers function returns all peers from the cache as a sorted array
func (ps *PeerStorage) GetPeers() ([]*Peer, error) {
peers := make([]*Peer, 0, len(ps.cache))
for _, peer := range ps.cache {
peers = append(peers, peer)
}
2024-05-28 14:28:10 +02:00
// Sort peers based on peer.Name
sort.Slice(peers, func(i, j int) bool {
return peers[i].Name < peers[j].Name
})
2024-05-28 14:28:10 +02:00
return peers, nil
}
2024-05-28 14:28:10 +02:00
// close the badger database
func (ps *PeerStorage) close() {
ps.db.Close()
}
2024-05-28 14:28:10 +02:00
func (ps *PeerStorage) GetFromPublicKey(publickey string) *Peer {
for _, peer := range ps.cache {
if peer.ContactPublicKey == publickey {
return peer
}
}
return nil
}
func (ps *PeerStorage) GetFromInvitationId(invitationId string) *Peer {
for _, peer := range ps.cache {
if peer.InvitationId == invitationId {
return peer
}
}
return nil
}
func (ps *PeerStorage) GetFromMyLookupKey(publickey string) *Peer {
for _, peer := range ps.cache {
if peer.MyLookupKp.Public == publickey {
return peer
}
}
return nil
}
func (ps *PeerStorage) GetFromName(name string) *Peer {
for _, peer := range ps.cache {
if peer.Name == name {
return peer
}
}
return nil
}
func (ps *PeerStorage) GetFromUid(uid string) *Peer {
return ps.cache[uid]
}
// Checks if the received contact card is an answer to an invitation, returns true if it is, and the proposed and received nicknames
func (ps *PeerStorage) CheckInvitation(ReceivedContact *meowlib.ContactCard) (isAnswer bool, proposedNick string, receivedNick string, invitationMessage string) {
// invitation Id found, this is an answer to an invitation
for _, p := range ps.cache {
if p.InvitationId == ReceivedContact.InvitationId {
return true, p.Name, ReceivedContact.Name, ReceivedContact.InvitationMessage
}
}
// it's an invitation
return false, "", ReceivedContact.Name, ReceivedContact.InvitationMessage
}
// Finalizes an invitation, returns nil if successful
func (ps *PeerStorage) FinalizeInvitation(ReceivedContact *meowlib.ContactCard) error {
for i, p := range ps.cache {
if p.InvitationId == ReceivedContact.InvitationId {
//id.Peers[i].Name = ReceivedContact.Name
ps.cache[i].ContactEncryption = ReceivedContact.EncryptionPublicKey
ps.cache[i].ContactLookupKey = ReceivedContact.LookupPublicKey
ps.cache[i].ContactPublicKey = ReceivedContact.ContactPublicKey
srvs := []string{}
for srv := range ReceivedContact.PullServers {
srvs = append(srvs, ReceivedContact.PullServers[srv].GetUid())
}
ps.cache[i].ContactPullServers = srvs
ps.StorePeer(ps.cache[i])
return nil
}
}
return errors.New("no matching contact found for invitationId " + ReceivedContact.InvitationId)
}