2023-09-22 13:18:42 +00:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2024-06-05 16:32:09 +00:00
|
|
|
"sync"
|
2023-09-22 13:18:42 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
|
|
"github.com/ethereum/go-ethereum/event"
|
|
|
|
"github.com/status-im/status-go/services/wallet/walletevent"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Client expects a single event with all states
|
|
|
|
type StatusNotification map[string]State // id -> State
|
|
|
|
|
|
|
|
type StatusNotifier struct {
|
2024-06-05 16:32:09 +00:00
|
|
|
statuses *sync.Map // id -> Status
|
2023-09-22 13:18:42 +00:00
|
|
|
eventType walletevent.EventType
|
|
|
|
feed *event.Feed
|
|
|
|
}
|
|
|
|
|
2024-06-05 16:32:09 +00:00
|
|
|
func NewStatusNotifier(statuses *sync.Map, eventType walletevent.EventType, feed *event.Feed) *StatusNotifier {
|
2023-09-22 13:18:42 +00:00
|
|
|
n := StatusNotifier{
|
|
|
|
statuses: statuses,
|
|
|
|
eventType: eventType,
|
|
|
|
feed: feed,
|
|
|
|
}
|
|
|
|
|
2024-06-05 16:32:09 +00:00
|
|
|
statuses.Range(func(_, value interface{}) bool {
|
|
|
|
value.(*Status).SetStateChangeCb(n.notify)
|
|
|
|
return true
|
|
|
|
})
|
2023-09-22 13:18:42 +00:00
|
|
|
|
|
|
|
return &n
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *StatusNotifier) notify(state State) {
|
|
|
|
// state is ignored, as client expects all valid states in
|
|
|
|
// a single event, so we fetch them from the map
|
|
|
|
if n.feed != nil {
|
|
|
|
statusMap := make(StatusNotification)
|
2024-06-05 16:32:09 +00:00
|
|
|
n.statuses.Range(func(id, value interface{}) bool {
|
|
|
|
state := value.(*Status).GetState()
|
2023-09-22 13:18:42 +00:00
|
|
|
if state.Value == StateValueUnknown {
|
2024-06-05 16:32:09 +00:00
|
|
|
return true
|
2023-09-22 13:18:42 +00:00
|
|
|
}
|
2024-06-05 16:32:09 +00:00
|
|
|
statusMap[id.(string)] = state
|
|
|
|
return true
|
|
|
|
})
|
2023-09-22 13:18:42 +00:00
|
|
|
|
|
|
|
encodedMessage, err := json.Marshal(statusMap)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
n.feed.Send(walletevent.Event{
|
|
|
|
Type: n.eventType,
|
|
|
|
Accounts: []common.Address{},
|
|
|
|
Message: string(encodedMessage),
|
|
|
|
At: time.Now().Unix(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|