cwtch/storage/profile_store.go

87 lines
1.8 KiB
Go
Raw Normal View History

2018-10-05 03:18:34 +00:00
package storage
2018-10-06 03:50:55 +00:00
import (
2019-01-21 20:11:40 +00:00
"cwtch.im/cwtch/event"
"cwtch.im/cwtch/model"
"encoding/json"
2018-10-06 03:50:55 +00:00
)
type profileStore struct {
2019-01-21 20:11:40 +00:00
fs FileStore
profile *model.Profile
eventManager *event.Manager
queue *event.Queue
}
2018-10-06 03:50:55 +00:00
// ProfileStore is an interface to managing the storage of Cwtch Profiles
type ProfileStore interface {
2019-01-21 20:11:40 +00:00
Save() error
Init(name string)
Load() error
Shutdown()
GetProfileCopy() *model.Profile
}
2019-01-21 20:11:40 +00:00
// NewProfileStore returns a profile store backed by a filestore listening for events and saving them
func NewProfileStore(eventManager *event.Manager, filename string, password string) (ProfileStore, error) {
ps := &profileStore{fs: NewFileStore(filename, password), profile: nil, eventManager: eventManager}
err := ps.Load()
if err == nil {
ps.queue = event.NewEventQueue(100)
go ps.eventHandler()
ps.eventManager.Subscribe(event.BlockPeer, ps.queue.EventChannel)
}
return ps, err
}
2019-01-21 20:11:40 +00:00
func (ps *profileStore) Init(name string) {
ps.profile = model.GenerateNewProfile(name)
ps.Save()
}
func (ps *profileStore) Save() error {
bytes, _ := json.Marshal(ps.profile)
return ps.fs.Save(bytes)
}
// Load instantiates a cwtchPeer from the file store
2019-01-21 20:11:40 +00:00
func (ps *profileStore) Load() error {
decrypted, err := ps.fs.Load()
if err != nil {
2019-01-21 20:11:40 +00:00
return err
}
cp := new(model.Profile)
err = json.Unmarshal(decrypted, &cp)
if err == nil {
2019-01-21 20:11:40 +00:00
ps.profile = cp
return nil
}
2019-01-21 20:11:40 +00:00
return err
}
func (ps *profileStore) GetProfileCopy() *model.Profile {
return ps.profile.GetCopy()
}
func (ps *profileStore) eventHandler() {
for {
ev := ps.queue.Next()
switch ev.EventType {
case event.BlockPeer:
contact, exists := ps.profile.GetContact(ev.Data["Onion"])
if exists {
contact.Blocked = true
}
default:
return
}
ps.Save()
}
}
func (ps *profileStore) Shutdown() {
ps.queue.Shutdown()
2018-10-06 03:50:55 +00:00
}