forked from AplaProject/go-apla
/
notificator.go
257 lines (207 loc) · 6.29 KB
/
notificator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// MIT License
//
// Copyright (c) 2016 GenesisCommunity
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package notificator
import (
"encoding/json"
"sync"
"github.com/GenesisCommunity/go-genesis/packages/consts"
"github.com/GenesisCommunity/go-genesis/packages/converter"
"github.com/GenesisCommunity/go-genesis/packages/model"
"github.com/GenesisCommunity/go-genesis/packages/publisher"
log "github.com/sirupsen/logrus"
)
type notificationRecord struct {
EcosystemID int64 `json:"ecosystem"`
RoleID int64 `json:"role_id"`
RecordsCount int64 `json:"count"`
}
type lastMessagesKey struct {
system int64
user int64
}
type lastMessages struct {
mu sync.RWMutex
stats map[lastMessagesKey][]notificationRecord
}
func newLastMessages() *lastMessages {
return &lastMessages{
stats: map[lastMessagesKey][]notificationRecord{},
}
}
func (lm *lastMessages) get(system, user int64) ([]notificationRecord, bool) {
lm.mu.RLock()
defer lm.mu.RUnlock()
res, ok := lm.stats[lastMessagesKey{system: system, user: user}]
return res, ok
}
func (lm *lastMessages) set(system, user int64, newStats []notificationRecord) {
lm.mu.Lock()
defer lm.mu.Unlock()
lm.stats[lastMessagesKey{system: system, user: user}] = newStats
}
func (lm *lastMessages) delete(system, user int64) {
lm.mu.Lock()
defer lm.mu.Unlock()
delete(lm.stats, lastMessagesKey{system: system, user: user})
}
var (
systemUsers map[int64]*[]int64
mu sync.Mutex
lastMessagesStats *lastMessages
)
func init() {
systemUsers = make(map[int64]*[]int64)
lastMessagesStats = newLastMessages()
}
// AddUser add user to send notifications
func AddUser(userID, systemID int64) {
mu.Lock()
defer mu.Unlock()
val, ok := systemUsers[systemID]
if ok {
*val = append(*val, userID)
return
}
val = &[]int64{userID}
systemUsers[systemID] = val
}
// UpdateNotifications send stats about unreaded messages to centrifugo for ecosystem
func UpdateNotifications(ecosystemID int64, users []int64) {
notificationsStats, err := getEcosystemNotificationStats(ecosystemID, users)
if err != nil {
return
}
for _, user := range users {
oldStats, _ := lastMessagesStats.get(ecosystemID, user)
var newStats []notificationRecord
if ns, _ := notificationsStats[user]; ns != nil {
newStats = *ns
} else {
newStats = nil
}
if !statsChanged(oldStats, newStats) {
continue
}
if len(newStats) == 0 {
for i := range oldStats {
oldStats[i].RecordsCount = 0
}
lastMessagesStats.delete(ecosystemID, user)
sendUserStats(user, oldStats)
continue
}
lastMessagesStats.set(ecosystemID, user, newStats)
sendUserStats(user, newStats)
}
}
func getEcosystemNotificationStats(ecosystemID int64, users []int64) (map[int64]*[]notificationRecord, error) {
result, err := model.GetNotificationsCount(ecosystemID, users)
if err != nil {
log.WithFields(log.Fields{"type": consts.DBError, "error": err}).Error("getting notification count")
return nil, err
}
return parseRecipientNotification(result, ecosystemID), nil
}
// SendNotifications send stats about unreaded messages to centrifugo
func SendNotifications() {
for ecosystemID, users := range systemUsers {
UpdateNotifications(ecosystemID, *users)
}
}
func parseRecipientNotification(rows []map[string]string, systemID int64) map[int64]*[]notificationRecord {
recipientNotifications := make(map[int64]*[]notificationRecord)
for _, r := range rows {
recipientID := converter.StrToInt64(r["recipient_id"])
if recipientID == 0 {
continue
}
roleID := converter.StrToInt64(r["role_id"])
count := converter.StrToInt64(r["cnt"])
roleNotifications := notificationRecord{
EcosystemID: systemID,
RoleID: roleID,
RecordsCount: count,
}
nr, ok := recipientNotifications[recipientID]
if ok {
*nr = append(*nr, roleNotifications)
continue
}
records := []notificationRecord{
roleNotifications,
}
recipientNotifications[recipientID] = &records
}
return recipientNotifications
}
func statsChanged(source, new []notificationRecord) bool {
if len(source) != len(new) {
return true
}
if len(new) == 0 {
return false
}
var newRole bool
for _, nRec := range new {
newRole = true
for _, sRec := range source {
if sRec.RoleID == nRec.RoleID {
newRole = false
if sRec.RecordsCount != nRec.RecordsCount {
return true
}
}
}
if newRole {
return true
}
}
return false
}
func sendUserStats(user int64, stats []notificationRecord) {
rawStats, err := json.Marshal(stats)
if err != nil {
log.WithFields(log.Fields{"type": consts.JSONMarshallError, "error": err}).Error("notification statistic")
}
ok, err := publisher.Write(user, string(rawStats))
if err != nil {
log.WithFields(log.Fields{"type": consts.IOError, "error": err}).Error("writing to centrifugo")
}
if !ok {
log.WithFields(log.Fields{"type": consts.CentrifugoError, "error": err}).Error("writing to centrifugo")
}
}
// SendNotificationsByRequest send stats by systemUsers one time
func SendNotificationsByRequest(systemUsers map[int64][]int64) {
for ecosystemID, users := range systemUsers {
stats, err := getEcosystemNotificationStats(ecosystemID, users)
if err != nil {
continue
}
for user, notifications := range stats {
if notifications == nil {
continue
}
sendUserStats(user, *notifications)
}
}
}