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: mlctrez <mlctrez@gmail.com> Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/157 Reviewed-by: James Mills <james@mills.io> Co-authored-by: mlctrez <mlctrez@noreply@mills.io> Co-committed-by: mlctrez <mlctrez@noreply@mills.io>
70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
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}
|
|
}
|