mirror of
https://git.mills.io/saltyim/saltyim.git
synced 2024-07-03 00:33:38 +00:00
![mlctrez](/assets/img/avatar_default.png)
Co-authored-by: James Mills <prologic@shortcircuit.net.au> Co-authored-by: James Mills <james@mills.io> Co-authored-by: mlctrez <mlctrez@gmail.com> Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/77 Co-authored-by: mlctrez <mlctrez@noreply@mills.io> Co-committed-by: mlctrez <mlctrez@noreply@mills.io>
66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
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{}}
|
|
}
|