forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core_channel.go
358 lines (325 loc) · 11.2 KB
/
core_channel.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
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
// 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"
"fmt"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/golang/protobuf/ptypes/wrappers"
"github.com/heroiclabs/nakama/api"
"github.com/lib/pq"
"github.com/pkg/errors"
"go.uber.org/zap"
)
var (
ErrChannelIdInvalid = errors.New("invalid channel id")
ErrChannelCursorInvalid = errors.New("invalid channel cursor")
ErrChannelGroupNotFound = errors.New("group not found")
)
// Wrapper type to avoid allocating a stream struct when the input is invalid.
type ChannelIdToStreamResult struct {
Stream PresenceStream
}
type channelMessageListCursor struct {
StreamMode uint8
StreamSubject string
StreamDescriptor string
StreamLabel string
CreateTime int64
Id string
Forward bool
IsNext bool
}
func ChannelMessagesList(ctx context.Context, logger *zap.Logger, db *sql.DB, caller uuid.UUID, stream PresenceStream, channelId string, limit int, forward bool, cursor string) (*api.ChannelMessageList, error) {
var incomingCursor *channelMessageListCursor
if cursor != "" {
if cb, err := base64.StdEncoding.DecodeString(cursor); err != nil {
return nil, ErrChannelCursorInvalid
} else {
incomingCursor = &channelMessageListCursor{}
if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil {
return nil, ErrChannelCursorInvalid
}
}
if forward != incomingCursor.Forward {
// Cursor is for a different channel message list direction.
return nil, ErrChannelCursorInvalid
} else if stream.Mode != incomingCursor.StreamMode {
// Stream mode does not match.
return nil, ErrChannelCursorInvalid
} else if stream.Subject.String() != incomingCursor.StreamSubject {
// Stream subject does not match.
return nil, ErrChannelCursorInvalid
} else if stream.Descriptor.String() != incomingCursor.StreamDescriptor {
// Stream descriptor does not match.
return nil, ErrChannelCursorInvalid
} else if stream.Label != incomingCursor.StreamLabel {
// Stream label does not match.
return nil, ErrChannelCursorInvalid
}
}
// If it's a group, check membership.
if !uuid.Equal(uuid.Nil, caller) && stream.Mode == StreamModeGroup {
allowed, err := groupCheckUserPermission(ctx, logger, db, stream.Subject, caller, 2)
if err != nil {
return nil, err
}
if !allowed {
return nil, ErrChannelGroupNotFound
}
}
query := `SELECT id, code, sender_id, username, content, create_time, update_time FROM message
WHERE stream_mode = $1 AND stream_subject = $2::UUID AND stream_descriptor = $3::UUID AND stream_label = $4`
if incomingCursor == nil {
// Ascending doesn't need an ordering clause.
if !forward {
query += " ORDER BY create_time DESC, id DESC"
}
} else {
if (forward && incomingCursor.IsNext) || (!forward && !incomingCursor.IsNext) {
// Forward and next page == backwards and previous page.
query += " AND (stream_mode, stream_subject, stream_descriptor, stream_label, create_time, id) > ($1, $2::UUID, $3::UUID, $4, $6, $7)"
} else {
// Forward and previous page == backwards and next page.
query += " AND (stream_mode, stream_subject, stream_descriptor, stream_label, create_time, id) < ($1, $2::UUID, $3::UUID, $4, $6, $7) ORDER BY create_time DESC, id DESC"
}
}
query += " LIMIT $5"
params := []interface{}{stream.Mode, stream.Subject, stream.Descriptor, stream.Label, limit + 1}
if incomingCursor != nil {
params = append(params, time.Unix(incomingCursor.CreateTime, 0).UTC(), incomingCursor.Id)
}
rows, err := db.QueryContext(ctx, query, params...)
if err != nil {
logger.Error("Error listing channel messages", zap.Error(err))
return nil, err
}
defer rows.Close()
messages := make([]*api.ChannelMessage, 0, limit)
var nextCursor, prevCursor *channelMessageListCursor
var dbId string
var dbCode int32
var dbSenderId string
var dbUsername string
var dbContent string
var dbCreateTime pq.NullTime
var dbUpdateTime pq.NullTime
for rows.Next() {
if len(messages) >= limit {
nextCursor = &channelMessageListCursor{
StreamMode: stream.Mode,
StreamSubject: stream.Subject.String(),
StreamDescriptor: stream.Descriptor.String(),
StreamLabel: stream.Label,
CreateTime: dbCreateTime.Time.Unix(),
Id: dbId,
Forward: forward,
IsNext: true,
}
break
}
err = rows.Scan(&dbId, &dbCode, &dbSenderId, &dbUsername, &dbContent, &dbCreateTime, &dbUpdateTime)
if err != nil {
logger.Error("Error parsing listed channel messages", zap.Error(err))
return nil, err
}
messages = append(messages, &api.ChannelMessage{
ChannelId: channelId,
MessageId: dbId,
Code: &wrappers.Int32Value{Value: dbCode},
SenderId: dbSenderId,
Username: dbUsername,
Content: dbContent,
CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()},
UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()},
Persistent: &wrappers.BoolValue{Value: true},
})
// There can only be a previous page if this is a paginated listing.
if incomingCursor != nil && prevCursor == nil {
prevCursor = &channelMessageListCursor{
StreamMode: stream.Mode,
StreamSubject: stream.Subject.String(),
StreamDescriptor: stream.Descriptor.String(),
StreamLabel: stream.Label,
CreateTime: dbCreateTime.Time.Unix(),
Id: dbId,
Forward: forward,
IsNext: false,
}
}
}
if incomingCursor != nil && !incomingCursor.IsNext {
// If this was a previous page listing, flip the results to their normal order and swap the cursors.
nextCursor, nextCursor.IsNext, prevCursor, prevCursor.IsNext = prevCursor, prevCursor.IsNext, nextCursor, nextCursor.IsNext
for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 {
messages[i], messages[j] = messages[j], messages[i]
}
}
var nextCursorStr string
if nextCursor != nil {
cursorBuf := new(bytes.Buffer)
if gob.NewEncoder(cursorBuf).Encode(nextCursor); err != nil {
logger.Error("Error creating channel messages list next cursor", zap.Error(err))
return nil, err
}
nextCursorStr = base64.StdEncoding.EncodeToString(cursorBuf.Bytes())
}
var prevCursorStr string
if prevCursor != nil {
cursorBuf := new(bytes.Buffer)
if gob.NewEncoder(cursorBuf).Encode(prevCursor); err != nil {
logger.Error("Error creating channel messages list previous cursor", zap.Error(err))
return nil, err
}
prevCursorStr = base64.StdEncoding.EncodeToString(cursorBuf.Bytes())
}
return &api.ChannelMessageList{
Messages: messages,
NextCursor: nextCursorStr,
PrevCursor: prevCursorStr,
}, nil
}
func GetChannelMessages(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID) ([]*api.ChannelMessage, error) {
query := "SELECT id, code, username, stream_mode, stream_subject, stream_descriptor, stream_label, content, create_time, update_time FROM message WHERE sender_id = $1::UUID"
rows, err := db.QueryContext(ctx, query, userID)
if err != nil {
logger.Error("Error listing channel messages for user", zap.String("user_id", userID.String()), zap.Error(err))
return nil, err
}
defer rows.Close()
messages := make([]*api.ChannelMessage, 0, 100)
var dbId string
var dbCode int32
var dbUsername string
var dbStreamMode uint8
var dbStreamSubject string
var dbStreamDescriptor string
var dbStreamLabel string
var dbContent string
var dbCreateTime pq.NullTime
var dbUpdateTime pq.NullTime
for rows.Next() {
err = rows.Scan(&dbId, &dbCode, &dbUsername, &dbStreamMode, &dbStreamSubject, &dbStreamDescriptor, &dbStreamLabel, &dbContent, &dbCreateTime, &dbUpdateTime)
if err != nil {
logger.Error("Error parsing listed channel messages for user", zap.String("user_id", userID.String()), zap.Error(err))
return nil, err
}
channelId, err := StreamToChannelId(PresenceStream{
Mode: dbStreamMode,
Subject: uuid.FromStringOrNil(dbStreamSubject),
Descriptor: uuid.FromStringOrNil(dbStreamDescriptor),
Label: dbStreamLabel,
})
if err != nil {
logger.Error("Error processing listed channel messages for user", zap.String("user_id", userID.String()), zap.Error(err))
return nil, err
}
messages = append(messages, &api.ChannelMessage{
ChannelId: channelId,
MessageId: dbId,
Code: &wrappers.Int32Value{Value: dbCode},
SenderId: userID.String(),
Username: dbUsername,
Content: dbContent,
CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()},
UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()},
Persistent: &wrappers.BoolValue{Value: true},
})
}
return messages, nil
}
func ChannelIdToStream(channelId string) (*ChannelIdToStreamResult, error) {
if channelId == "" {
return nil, ErrChannelIdInvalid
}
components := strings.SplitN(channelId, ".", 4)
if len(components) != 4 {
return nil, ErrChannelIdInvalid
}
stream := PresenceStream{
Mode: StreamModeChannel,
}
// Parse and assign mode.
switch components[0] {
case "2":
// StreamModeChannel.
// Expect no subject or descriptor.
if components[1] != "" || components[2] != "" {
return nil, ErrChannelIdInvalid
}
// Label.
if l := len(components[3]); l < 1 || l > 64 {
return nil, ErrChannelIdInvalid
}
stream.Label = components[3]
case "3":
// Expect no descriptor or label.
if components[2] != "" || components[3] != "" {
return nil, ErrChannelIdInvalid
}
// Subject.
var err error
if components[1] != "" {
if stream.Subject, err = uuid.FromString(components[1]); err != nil {
return nil, ErrChannelIdInvalid
}
}
// Mode.
stream.Mode = StreamModeGroup
case "4":
// Expect lo label.
if components[3] != "" {
return nil, ErrChannelIdInvalid
}
// Subject.
var err error
if components[1] != "" {
if stream.Subject, err = uuid.FromString(components[1]); err != nil {
return nil, ErrChannelIdInvalid
}
}
// Descriptor.
if components[2] != "" {
if stream.Descriptor, err = uuid.FromString(components[2]); err != nil {
return nil, ErrChannelIdInvalid
}
}
// Mode.
stream.Mode = StreamModeDM
default:
return nil, ErrChannelIdInvalid
}
return &ChannelIdToStreamResult{Stream: stream}, nil
}
func StreamToChannelId(stream PresenceStream) (string, error) {
if stream.Mode != StreamModeChannel && stream.Mode != StreamModeGroup && stream.Mode != StreamModeDM {
return "", ErrChannelIdInvalid
}
subject := ""
if stream.Subject != uuid.Nil {
subject = stream.Subject.String()
}
descriptor := ""
if stream.Descriptor != uuid.Nil {
descriptor = stream.Descriptor.String()
}
return fmt.Sprintf("%v.%v.%v.%v", stream.Mode, subject, descriptor, stream.Label), nil
}