forked from heroiclabs/nakama
/
core_notification.go
216 lines (188 loc) · 6.9 KB
/
core_notification.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
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"context"
"database/sql"
"encoding/base64"
"encoding/gob"
"strconv"
"strings"
"github.com/gofrs/uuid"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/heroiclabs/nakama/api"
"github.com/heroiclabs/nakama/rtapi"
"github.com/lib/pq"
"go.uber.org/zap"
"time"
)
const (
NotificationCodeDmRequest int32 = -1
NotificationCodeFriendRequest int32 = -2
NotificationCodeFriendAccept int32 = -3
NotificationCodeGroupAdd int32 = -4
NotificationCodeGroupJoinRequest int32 = -5
NotificationCodeFriendJoinGame int32 = -6
)
type notificationCacheableCursor struct {
NotificationID []byte
CreateTime int64
}
func NotificationSend(ctx context.Context, logger *zap.Logger, db *sql.DB, messageRouter MessageRouter, notifications map[uuid.UUID][]*api.Notification) error {
persistentNotifications := make(map[uuid.UUID][]*api.Notification)
for userID, ns := range notifications {
for _, userNotification := range ns {
// Select persistent notifications for storage.
if userNotification.Persistent {
if pun := persistentNotifications[userID]; pun == nil {
persistentNotifications[userID] = []*api.Notification{userNotification}
} else {
persistentNotifications[userID] = append(pun, userNotification)
}
}
}
}
// Store any persistent notifications.
if len(persistentNotifications) > 0 {
if err := NotificationSave(ctx, logger, db, persistentNotifications); err != nil {
return err
}
}
// Deliver live notifications to connected users.
for userID, ns := range notifications {
messageRouter.SendToStream(logger, PresenceStream{Mode: StreamModeNotifications, Subject: userID}, &rtapi.Envelope{
Message: &rtapi.Envelope_Notifications{
Notifications: &rtapi.Notifications{
Notifications: ns,
},
},
})
}
return nil
}
func NotificationList(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, limit int, cursor string, nc *notificationCacheableCursor) (*api.NotificationList, error) {
params := []interface{}{userID}
limitQuery := " "
if limit > 0 {
params = append(params, limit)
limitQuery = " LIMIT $2"
}
cursorQuery := " "
if nc != nil && nc.NotificationID != nil {
cursorQuery = " AND (user_id, create_time, id) > ($1::UUID, $3::TIMESTAMPTZ, $4::UUID)"
params = append(params, pq.NullTime{Time: time.Unix(0, nc.CreateTime).UTC(), Valid: true}, uuid.FromBytesOrNil(nc.NotificationID))
}
rows, err := db.QueryContext(ctx, `
SELECT id, subject, content, code, sender_id, create_time
FROM notification
WHERE user_id = $1`+cursorQuery+`
ORDER BY create_time ASC`+limitQuery, params...)
if err != nil {
logger.Error("Could not retrieve notifications.", zap.Error(err))
return nil, err
}
notifications := make([]*api.Notification, 0)
var lastCreateTime int64
for rows.Next() {
no := &api.Notification{Persistent: true, CreateTime: ×tamp.Timestamp{}}
var createTime pq.NullTime
if err := rows.Scan(&no.Id, &no.Subject, &no.Content, &no.Code, &no.SenderId, &createTime); err != nil {
rows.Close()
logger.Error("Could not scan notification from database.", zap.Error(err))
return nil, err
}
lastCreateTime = createTime.Time.UnixNano()
no.CreateTime.Seconds = createTime.Time.Unix()
if no.SenderId == uuid.Nil.String() {
no.SenderId = ""
}
notifications = append(notifications, no)
}
rows.Close()
notificationList := &api.NotificationList{}
cursorBuf := new(bytes.Buffer)
if len(notifications) == 0 {
if len(cursor) > 0 {
notificationList.CacheableCursor = cursor
} else {
newCursor := ¬ificationCacheableCursor{NotificationID: nil, CreateTime: 0}
if err := gob.NewEncoder(cursorBuf).Encode(newCursor); err != nil {
logger.Error("Could not create new cursor.", zap.Error(err))
return nil, err
}
notificationList.CacheableCursor = base64.RawURLEncoding.EncodeToString(cursorBuf.Bytes())
}
} else {
lastNotification := notifications[len(notifications)-1]
newCursor := ¬ificationCacheableCursor{
NotificationID: uuid.FromStringOrNil(lastNotification.Id).Bytes(),
CreateTime: lastCreateTime,
}
if err := gob.NewEncoder(cursorBuf).Encode(newCursor); err != nil {
logger.Error("Could not create new cursor.", zap.Error(err))
return nil, err
}
notificationList.Notifications = notifications
notificationList.CacheableCursor = base64.RawURLEncoding.EncodeToString(cursorBuf.Bytes())
}
return notificationList, nil
}
func NotificationDelete(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, notificationIDs []string) error {
statements := make([]string, 0, len(notificationIDs))
params := make([]interface{}, 0, len(notificationIDs)+1)
params = append(params, userID)
for _, id := range notificationIDs {
statement := "$" + strconv.Itoa(len(params)+1)
statements = append(statements, statement)
params = append(params, id)
}
query := "DELETE FROM notification WHERE user_id = $1 AND id IN (" + strings.Join(statements, ", ") + ")"
logger.Debug("Delete notification query", zap.String("query", query), zap.Any("params", params))
_, err := db.ExecContext(ctx, query, params...)
if err != nil {
logger.Error("Could not delete notifications.", zap.Error(err))
return err
}
return nil
}
func NotificationSave(ctx context.Context, logger *zap.Logger, db *sql.DB, notifications map[uuid.UUID][]*api.Notification) error {
statements := make([]string, 0, len(notifications))
params := make([]interface{}, 0, len(notifications))
counter := 0
for userID, no := range notifications {
for _, un := range no {
statement := "$" + strconv.Itoa(counter+1) +
",$" + strconv.Itoa(counter+2) +
",$" + strconv.Itoa(counter+3) +
",$" + strconv.Itoa(counter+4) +
",$" + strconv.Itoa(counter+5) +
",$" + strconv.Itoa(counter+6)
counter = counter + 6
statements = append(statements, "("+statement+")")
params = append(params, un.Id)
params = append(params, userID)
params = append(params, un.Subject)
params = append(params, un.Content)
params = append(params, un.Code)
params = append(params, un.SenderId)
}
}
query := "INSERT INTO notification (id, user_id, subject, content, code, sender_id) VALUES " + strings.Join(statements, ", ")
if _, err := db.ExecContext(ctx, query, params...); err != nil {
logger.Error("Could not save notifications.", zap.Error(err))
return err
}
return nil
}