-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotification.go
More file actions
385 lines (318 loc) · 9.4 KB
/
notification.go
File metadata and controls
385 lines (318 loc) · 9.4 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package mongodb
import (
"context"
"log"
"regexp"
"time"
"github.com/sinfo/deck2/src/config"
"github.com/sinfo/deck2/src/models"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
// NotificationsType contains database information on Notifications
type NotificationsType struct {
Collection *mongo.Collection
}
var tagRegexCompiler, _ = regexp.Compile(`@[a-zA-Z0-9\.]+`)
// Notify creates a notification and adds it to every subscriber
func (n *NotificationsType) Notify(author primitive.ObjectID, data CreateNotificationData) {
event, err := Events.GetCurrentEvent()
if err != nil {
return
}
if !config.Production {
members, err := Teams.GetMembersByRole(models.RoleAdmin)
if err != nil {
log.Println("error fetching admins: " + err.Error())
} else {
for _, s := range members {
n.NotifyMember(s, data)
}
}
}
// notify subscribers
if data.Company != nil {
company, err := Companies.GetCompany(*data.Company)
if err != nil {
return
}
for _, participation := range company.Participations {
if participation.Event == event.ID {
for _, subscriber := range participation.Subscribers {
// notify authors only if not running on production mode
if config.Production && subscriber == author {
continue
}
n.NotifyMember(subscriber, data)
}
break
}
}
}
if data.Speaker != nil {
speaker, err := Speakers.GetSpeaker(*data.Speaker)
if err != nil {
return
}
for _, participation := range speaker.Participations {
if participation.Event == event.ID {
for _, subscriber := range participation.Subscribers {
// notify authors only if not running on production mode
if config.Production && subscriber == author {
continue
}
n.NotifyMember(subscriber, data)
}
break
}
}
}
// Notify coordination teams: coordination logic lives in separate collection
// Find coordination teams that include the author as a coordinated member
// and notify those coordination teams' coordinators only.
coordTeams, err := CoordinationTeams.GetCoordinationTeamsByMember(author)
if err == nil {
for _, coordTeam := range coordTeams {
if coordTeam.Coordinator == nil {
continue
}
// do not notify the author themselves in production
if config.Production && coordTeam.Coordinator.Member == author {
continue
}
n.NotifyMember(coordTeam.Coordinator.Member, data)
}
}
// notified tagged member
var post *models.Post
if data.Thread != nil && data.Post == nil {
thread, err := Threads.GetThread(*data.Thread)
if err != nil {
return
}
post, err = Posts.GetPost(thread.Entry)
if err != nil {
return
}
} else if data.Post != nil {
post, err = Posts.GetPost(*data.Post)
if err != nil {
return
}
}
if post == nil {
return
}
for _, tag := range tagRegexCompiler.FindAll([]byte(post.Text), -1) {
if taggedMember, err := Members.GetMemberBySinfoID(string(tag)[1:]); err == nil {
data.Kind = models.NotificationKindTagged
data.Post = &post.ID
n.NotifyMember(taggedMember.ID, data)
}
}
}
// CreateNotificationData holds data needed to create a notification
type CreateNotificationData struct {
Kind models.NotificationKind
Post *primitive.ObjectID
Thread *primitive.ObjectID
Speaker *primitive.ObjectID
Company *primitive.ObjectID
Meeting *primitive.ObjectID
Session *primitive.ObjectID
}
// NotifyMember adds a notification to a member
func (n *NotificationsType) NotifyMember(memberID primitive.ObjectID, data CreateNotificationData) {
ctx = context.Background()
notification := &models.Notification{
Kind: data.Kind,
Member: memberID,
Post: data.Post,
Thread: data.Thread,
Speaker: data.Speaker,
Company: data.Company,
Meeting: data.Meeting,
Session: data.Session,
}
if err := notification.Validate(); err != nil {
log.Println("invalid notification: ", err.Error())
return
}
signature := notification.Hash()
// check if there is already a notification with this signature
if err := n.Collection.FindOne(ctx, bson.M{"signature": signature}).Decode(notification); err == nil {
return
}
insertData := bson.M{
"member": memberID,
"kind": data.Kind,
"post": data.Post,
"thread": data.Thread,
"speaker": data.Speaker,
"company": data.Company,
"meeting": data.Meeting,
"session": data.Session,
"signature": signature,
"date": time.Now().UTC(),
}
insertResult, err := n.Collection.InsertOne(ctx, insertData)
if err != nil {
log.Println("unable to insert created notification: ", err.Error())
return
}
_, err = n.GetNotification(insertResult.InsertedID.(primitive.ObjectID))
if err != nil {
log.Println("unable to retrieve created notification: ", err.Error())
return
}
}
// GetNotification finds a notification with specified id.
func (n *NotificationsType) GetNotification(id primitive.ObjectID) (*models.Notification, error) {
ctx = context.Background()
var notification models.Notification
if err := n.Collection.FindOne(ctx, bson.M{"_id": id}).Decode(¬ification); err != nil {
return nil, err
}
return ¬ification, nil
}
// GetMemberNotifications gets all notifications for a member
func (n *NotificationsType) GetMemberNotifications(memberID primitive.ObjectID) ([]map[string]interface{}, error) {
ctx = context.Background()
var notifications = make([]map[string]interface{}, 0)
filter := bson.M{
"member": memberID,
}
cur, err := n.Collection.Find(ctx, filter)
if err != nil {
return nil, err
}
type savedNotif struct {
notifMap map[string]interface{}
speakerID *primitive.ObjectID
companyID *primitive.ObjectID
}
var saved = make([]savedNotif, 0)
speakerSet := make(map[primitive.ObjectID]struct{})
companySet := make(map[primitive.ObjectID]struct{})
for cur.Next(ctx) {
// decode into models.Notification first
var notification models.Notification
err := cur.Decode(¬ification)
if err != nil {
return nil, err
}
// build a JSON-friendly map for the response
notifMap := map[string]interface{}{
"id": notification.ID.Hex(),
"kind": notification.Kind,
"signature": notification.Signature,
"member": notification.Member.Hex(),
"date": notification.Date.Format(time.RFC3339),
}
if notification.Post != nil {
notifMap["post"] = notification.Post.Hex()
}
if notification.Thread != nil {
notifMap["thread"] = notification.Thread.Hex()
}
if notification.Meeting != nil {
notifMap["meeting"] = notification.Meeting.Hex()
}
if notification.Session != nil {
notifMap["session"] = notification.Session.Hex()
}
var sID *primitive.ObjectID
var cID *primitive.ObjectID
if notification.Speaker != nil {
sID = notification.Speaker
// tentatively store the hex (fallback) until we embed
notifMap["speaker"] = notification.Speaker.Hex()
speakerSet[*sID] = struct{}{}
}
if notification.Company != nil {
cID = notification.Company
notifMap["company"] = notification.Company.Hex()
companySet[*cID] = struct{}{}
}
saved = append(saved, savedNotif{notifMap: notifMap, speakerID: sID, companyID: cID})
}
// If we encountered speaker or company IDs, fetch them in batch and embed
var speakersByID = make(map[primitive.ObjectID]*models.Speaker)
var companiesByID = make(map[primitive.ObjectID]*models.Company)
if len(speakerSet) > 0 {
ids := make([]primitive.ObjectID, 0, len(speakerSet))
for id := range speakerSet {
ids = append(ids, id)
}
// batch find speakers
spCur, err := Speakers.Collection.Find(ctx, bson.M{"_id": bson.M{"$in": ids}})
if err == nil {
for spCur.Next(ctx) {
var sp models.Speaker
if err := spCur.Decode(&sp); err == nil {
speakersByID[sp.ID] = &sp
}
}
spCur.Close(ctx)
}
}
if len(companySet) > 0 {
ids := make([]primitive.ObjectID, 0, len(companySet))
for id := range companySet {
ids = append(ids, id)
}
// batch find companies
coCur, err := Companies.Collection.Find(ctx, bson.M{"_id": bson.M{"$in": ids}})
if err == nil {
for coCur.Next(ctx) {
var co models.Company
if err := coCur.Decode(&co); err == nil {
companiesByID[co.ID] = &co
}
}
coCur.Close(ctx)
}
}
// build final notifications embedding the fetched objects when available
for _, s := range saved {
if s.speakerID != nil {
if sp, ok := speakersByID[*s.speakerID]; ok {
s.notifMap["speaker"] = sp
}
}
if s.companyID != nil {
if co, ok := companiesByID[*s.companyID]; ok {
s.notifMap["company"] = co
}
}
notifications = append(notifications, s.notifMap)
}
if err := cur.Err(); err != nil {
return nil, err
}
cur.Close(ctx)
return notifications, nil
}
// DeleteNotification deletes a notification by its ID.
func (n *NotificationsType) DeleteNotification(notificationID primitive.ObjectID) (*models.Notification, error) {
ctx = context.Background()
var notification models.Notification
err := n.Collection.FindOneAndDelete(ctx, bson.M{"_id": notificationID}).Decode(¬ification)
if err != nil {
return nil, err
}
return ¬ification, nil
}
// DeleteAllMemberNotifications deletes all notifications for a member
func (n *NotificationsType) DeleteAllMemberNotifications(memberID primitive.ObjectID) (int64, error) {
ctx = context.Background()
filter := bson.M{
"member": memberID,
}
deleteResult, err := n.Collection.DeleteMany(ctx, filter)
if err != nil {
return 0, err
}
return deleteResult.DeletedCount, nil
}