package storage import ( "sort" "sync" "github.com/maxence-charriere/go-app/v9/pkg/app" ) const ( ContactsKey = "saltyim-contacts" ) type Contacts interface { Add(addr string) Remove(addr string) List() []string } type contacts struct { state StateOperations lock *sync.Mutex } func readContacts(state StateOperations) map[string]interface{} { contacts := make(map[string]interface{}) state.GetState(ContactsKey, &contacts) return contacts } func updateContacts(state StateOperations, contacts map[string]interface{}) { state.SetState(ContactsKey, contacts, app.Persist, app.Encrypt) } func (c *contacts) Add(addr string) { c.lock.Lock() defer c.lock.Unlock() contacts := readContacts(c.state) contacts[addr] = true updateContacts(c.state, contacts) } func (c *contacts) Remove(addr string) { c.lock.Lock() defer c.lock.Unlock() contacts := make(map[string]interface{}) c.state.GetState(ContactsKey, &contacts) delete(contacts, addr) updateContacts(c.state, contacts) } func (c *contacts) List() []string { c.lock.Lock() defer c.lock.Unlock() contacts := readContacts(c.state) var result []string for s := range contacts { result = append(result, s) } sort.Strings(result) return result } func ContactsLocalStorage(state StateOperations) Contacts { return &contacts{state: state, lock: &sync.Mutex{}} }