6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-07-03 00:33:38 +00:00
prologic-saltyim/internal/pwa/storage/contacts.go
mlctrez 969a263d06 support for contacts, multiple chat threads, and persistence (#77)
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>
2022-03-28 21:49:01 +00:00

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{}}
}