package storage import ( "crypto/sha256" "fmt" "sort" "sync" "github.com/maxence-charriere/go-app/v9/pkg/app" ) const ( ConversationsKey = "saltyim-conversations-%x" ) type Conversations interface { Read() []string Append(line string) Update(lines []string) Delete() } type conversations struct { state StateOperations lock *sync.Mutex addr string } func (c *conversations) Read() []string { return readConversations(c.state, c.addr) } func (c *conversations) Update(lines []string) { updateConversations(c.state, c.addr, lines) } func (c *conversations) Append(line string) { existingLines := readConversations(c.state, c.addr) // TODO: map would be more efficient for finding existing messages for _, existingLine := range existingLines { if line == existingLine { return } } conversationLines := append(existingLines, line) sort.Strings(conversationLines) c.Update(conversationLines) } func (c *conversations) Delete() { c.state.DelState(conversationKey(c.addr)) } func readConversations(state StateOperations, addr string) []string { var conversations []string state.GetState(conversationKey(addr), &conversations) return conversations } func conversationKey(addr string) string { return fmt.Sprintf(ConversationsKey, sha256.Sum256([]byte(addr))) } func updateConversations(state StateOperations, addr string, conversations []string) { state.SetState(conversationKey(addr), conversations, app.Persist, app.Encrypt) } func ConversationsLocalStorage(state StateOperations, addr string) Conversations { return &conversations{state: state, lock: &sync.Mutex{}, addr: addr} }