forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline_friend.go
454 lines (396 loc) · 13.5 KB
/
pipeline_friend.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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright 2017 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 (
"database/sql"
"errors"
"github.com/lib/pq"
"github.com/satori/go.uuid"
"go.uber.org/zap"
)
func (p *pipeline) querySocialGraph(logger *zap.Logger, filterQuery string, params []interface{}) ([]*User, error) {
users := []*User{}
query := `
SELECT id, handle, fullname, avatar_url,
lang, location, timezone, metadata,
created_at, users.updated_at, last_online_at
FROM users ` + filterQuery
rows, err := p.db.Query(query, params...)
if err != nil {
logger.Error("Could not execute social graph query", zap.String("query", query), zap.Error(err))
return nil, err
}
defer rows.Close()
var id []byte
var handle sql.NullString
var fullname sql.NullString
var avatarURL sql.NullString
var lang sql.NullString
var location sql.NullString
var timezone sql.NullString
var metadata []byte
var createdAt sql.NullInt64
var updatedAt sql.NullInt64
var lastOnlineAt sql.NullInt64
for rows.Next() {
err = rows.Scan(&id, &handle, &fullname, &avatarURL, &lang, &location, &timezone, &metadata, &createdAt, &updatedAt, &lastOnlineAt)
if err != nil {
logger.Error("Could not execute social graph query", zap.Error(err))
return nil, err
}
users = append(users, &User{
Id: id,
Handle: handle.String,
Fullname: fullname.String,
AvatarUrl: avatarURL.String,
Lang: lang.String,
Location: location.String,
Timezone: timezone.String,
Metadata: metadata,
CreatedAt: createdAt.Int64,
UpdatedAt: updatedAt.Int64,
LastOnlineAt: lastOnlineAt.Int64,
})
}
if err = rows.Err(); err != nil {
logger.Error("Could not execute social graph query", zap.Error(err))
return nil, err
}
return users, nil
}
func (p *pipeline) addFacebookFriends(logger *zap.Logger, userID []byte, accessToken string) {
var tx *sql.Tx
var err error
defer func() {
if err != nil {
logger.Error("Could not import friends from Facebook", zap.Error(err))
if tx != nil {
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
}
} else {
if tx != nil {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
} else {
logger.Info("Imported friends")
}
}
}
}()
fbFriends, err := p.socialClient.GetFacebookFriends(accessToken)
if err != nil {
return
}
tx, err = p.db.Begin()
if err != nil {
return
}
friendAddedCounter := 0
for _, fbFriend := range fbFriends {
var friendID []byte
err = tx.QueryRow("SELECT id FROM users WHERE facebook_id = $1", fbFriend.ID).Scan(&friendID)
if err != nil {
return
}
updatedAt := nowMs()
_, err = tx.Exec(`
INSERT INTO user_edge (source_id, position, updated_at, destination_id, state)
VALUES ($1, $2, $2, $3, 0), ($3, $2, $2, $1, 0)`,
userID, updatedAt, friendID)
if err != nil {
return
}
friendAddedCounter++
_, err = tx.Exec(`UPDATE user_edge_metadata SET count = count + 1, updated_at = $1 WHERE source_id = $2`, updatedAt, friendID)
}
_, err = tx.Exec(`UPDATE user_edge_metadata SET count = $1, updated_at = $2 WHERE source_id = $3`, friendAddedCounter, nowMs(), userID)
}
func (p *pipeline) getFriends(filterQuery string, userID []byte) ([]*Friend, error) {
query := `
SELECT id, handle, fullname, avatar_url,
lang, location, timezone, metadata,
created_at, users.updated_at, last_online_at, state
FROM users, user_edge ` + filterQuery
rows, err := p.db.Query(query, userID)
if err != nil {
return nil, err
}
defer rows.Close()
friends := make([]*Friend, 0)
for rows.Next() {
var id []byte
var handle sql.NullString
var fullname sql.NullString
var avatarURL sql.NullString
var lang sql.NullString
var location sql.NullString
var timezone sql.NullString
var metadata []byte
var createdAt sql.NullInt64
var updatedAt sql.NullInt64
var lastOnlineAt sql.NullInt64
var state sql.NullInt64
err = rows.Scan(&id, &handle, &fullname, &avatarURL, &lang, &location, &timezone, &metadata, &createdAt, &updatedAt, &lastOnlineAt, &state)
if err != nil {
return nil, err
}
friends = append(friends, &Friend{
User: &User{
Id: id,
Handle: handle.String,
Fullname: fullname.String,
AvatarUrl: avatarURL.String,
Lang: lang.String,
Location: location.String,
Timezone: timezone.String,
Metadata: metadata,
CreatedAt: createdAt.Int64,
UpdatedAt: updatedAt.Int64,
LastOnlineAt: lastOnlineAt.Int64,
},
Type: state.Int64,
})
}
return friends, nil
}
func (p *pipeline) friendAdd(l *zap.Logger, session *session, envelope *Envelope) {
addFriendRequest := envelope.GetFriendAdd()
if len(addFriendRequest.UserId) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID must be present"))
return
}
friendID, err := uuid.FromBytes(addFriendRequest.UserId)
if err != nil {
l.Warn("Could not add friend", zap.Error(err))
session.Send(ErrorMessageBadInput(envelope.CollationId, "Invalid User ID"))
return
}
logger := l.With(zap.String("friend_id", friendID.String()))
friendIDBytes := friendID.Bytes()
if friendID == session.userID {
logger.Warn("Cannot add self", zap.Error(err))
session.Send(ErrorMessageBadInput(envelope.CollationId, "Cannot add self"))
return
}
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not add friend", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to add friend"))
return
}
defer func() {
if err != nil {
logger.Error("Could not add friend", zap.Error(err))
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to add friend"))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to add friend"))
} else {
logger.Info("Added friend")
session.Send(&Envelope{CollationId: envelope.CollationId})
}
}
}()
updatedAt := nowMs()
// Mark an invite as accepted, if one was in place.
res, err := tx.Exec(`
UPDATE user_edge SET state = 0, updated_at = $3
WHERE (source_id = $1 AND destination_id = $2 AND state = 2)
OR (source_id = $2 AND destination_id = $1 AND state = 1)
`, friendIDBytes, session.userID.Bytes(), updatedAt)
if err != nil {
return
}
// If both edges were updated, it was accepting an invite was successful.
if rowsAffected, _ := res.RowsAffected(); rowsAffected == 2 {
return
}
// If no edge updates took place, it's a new invite being set up.
res, err = tx.Exec(`
INSERT INTO user_edge (source_id, destination_id, state, position, updated_at)
SELECT source_id, destination_id, state, position, updated_at
FROM (VALUES
($1::BYTEA, $2::BYTEA, 2, $3::BIGINT, $3::BIGINT),
($2::BYTEA, $1::BYTEA, 1, $3::BIGINT, $3::BIGINT)
) AS ue(source_id, destination_id, state, position, updated_at)
WHERE EXISTS (SELECT id FROM users WHERE id = $2::BYTEA)
`, session.userID.Bytes(), friendIDBytes, updatedAt)
if err != nil {
return
}
// An invite was successfully added if both components were inserted.
if rowsAffected, _ := res.RowsAffected(); rowsAffected != 2 {
err = errors.New("user ID not found or unavailable")
return
}
// Update the user edge metadata counts.
res, err = tx.Exec(`
UPDATE user_edge_metadata
SET count = count + 1, updated_at = $1
WHERE source_id = $2
OR source_id = $3`,
updatedAt, session.userID.Bytes(), friendIDBytes)
if err != nil {
return
}
if rowsAffected, _ := res.RowsAffected(); rowsAffected != 2 {
err = errors.New("could not update user friend counts")
return
}
}
func (p *pipeline) friendRemove(l *zap.Logger, session *session, envelope *Envelope) {
removeFriendRequest := envelope.GetFriendRemove()
if len(removeFriendRequest.UserId) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID must be present"))
return
}
friendID, err := uuid.FromBytes(removeFriendRequest.UserId)
if err != nil {
l.Warn("Could not add friend", zap.Error(err))
session.Send(ErrorMessageBadInput(envelope.CollationId, "Invalid User ID"))
return
}
logger := l.With(zap.String("friend_id", friendID.String()))
friendIDBytes := friendID.Bytes()
if friendID == session.userID {
logger.Warn("Cannot remove self", zap.Error(err))
session.Send(ErrorMessageBadInput(envelope.CollationId, "Cannot remove self"))
return
}
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not remove friend", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to remove friend"))
return
}
defer func() {
if err != nil {
logger.Error("Could not remove friend", zap.Error(err))
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to remove friend"))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to remove friend"))
} else {
logger.Info("Removed friend")
session.Send(&Envelope{CollationId: envelope.CollationId})
}
}
}()
updatedAt := nowMs()
res, err := tx.Exec("DELETE FROM user_edge WHERE source_id = $1 AND destination_id = $2", session.userID.Bytes(), friendIDBytes)
rowsAffected, _ := res.RowsAffected()
if err == nil && rowsAffected > 0 {
_, err = tx.Exec("UPDATE user_edge_metadata SET count = count - 1, updated_at = $2 WHERE source_id = $1", session.userID.Bytes(), updatedAt)
}
if err != nil {
return
}
res, err = tx.Exec("DELETE FROM user_edge WHERE source_id = $1 AND destination_id = $2", friendIDBytes, session.userID.Bytes())
rowsAffected, _ = res.RowsAffected()
if err == nil && rowsAffected > 0 {
_, err = tx.Exec("UPDATE user_edge_metadata SET count = count - 1, updated_at = $2 WHERE source_id = $1", friendIDBytes, updatedAt)
}
}
func (p *pipeline) friendBlock(l *zap.Logger, session *session, envelope *Envelope) {
blockUserRequest := envelope.GetFriendBlock()
if len(blockUserRequest.UserId) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID must be present"))
return
}
userID, err := uuid.FromBytes(blockUserRequest.UserId)
if err != nil {
l.Warn("Could not block user", zap.Error(err))
session.Send(ErrorMessageBadInput(envelope.CollationId, "Invalid User ID"))
return
}
logger := l.With(zap.String("user_id", userID.String()))
userIDBytes := userID.Bytes()
if userID == session.userID {
logger.Warn("Cannot block self", zap.Error(err))
session.Send(ErrorMessageBadInput(envelope.CollationId, "Cannot block self"))
return
}
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not block user", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to block friend"))
return
}
defer func() {
if err != nil {
if _, ok := err.(*pq.Error); ok {
logger.Error("Could not block user", zap.Error(err))
} else {
logger.Warn("Could not block user", zap.Error(err))
}
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not block user"))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not block user"))
} else {
logger.Info("User blocked")
session.Send(&Envelope{CollationId: envelope.CollationId})
}
}
}()
res, err := tx.Exec("UPDATE user_edge SET state = 3, updated_at = $3 WHERE source_id = $1 AND destination_id = $2",
session.userID.Bytes(), userIDBytes, nowMs())
if err != nil {
return
}
if rowsAffected, _ := res.RowsAffected(); rowsAffected == 0 {
err = errors.New("Could not block user. User ID may not exist")
return
}
// Delete opposite relationship if user hasn't blocked you already
res, err = tx.Exec("DELETE FROM user_edge WHERE source_id = $1 AND destination_id = $2 AND state != 3",
userIDBytes, session.userID.Bytes())
if err != nil {
return
}
if rowsAffected, _ := res.RowsAffected(); rowsAffected == 1 {
_, err = tx.Exec("UPDATE user_edge_metadata SET count = count - 1, updated_at = $2 WHERE source_id = $1", userIDBytes, nowMs())
}
}
func (p *pipeline) friendsList(logger *zap.Logger, session *session, envelope *Envelope) {
friends, err := p.getFriends("WHERE id = destination_id AND source_id = $1", session.userID.Bytes())
if err != nil {
logger.Error("Could not get friends", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not get friends"))
return
}
session.Send(&Envelope{CollationId: envelope.CollationId, Payload: &Envelope_Friends{Friends: &TFriends{Friends: friends}}})
}