forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline_friend.go
499 lines (432 loc) · 15 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// 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"
"encoding/json"
"fmt"
"github.com/lib/pq"
"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 sql.NullString
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.String,
Handle: handle.String,
Fullname: fullname.String,
AvatarUrl: avatarURL.String,
Lang: lang.String,
Location: location.String,
Timezone: timezone.String,
Metadata: string(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 string, handle string, fbid string, accessToken string) {
var tx *sql.Tx
var err error
ts := nowMs()
friendUserIDs := make([]interface{}, 0)
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.Debug("Imported friends from Facebook")
// Send out notifications.
if len(friendUserIDs) != 0 {
content, err := json.Marshal(map[string]interface{}{"handle": handle, "facebook_id": fbid})
if err != nil {
logger.Warn("Failed to send Facebook friend join notifications", zap.Error(err))
return
}
subject := "Your friend has just joined the game"
expiresAt := ts + p.notificationService.expiryMs
notifications := make([]*NNotification, len(friendUserIDs))
for i, friendUserID := range friendUserIDs {
fid := friendUserID.(string)
notifications[i] = &NNotification{
Id: generateNewId(),
UserID: fid,
Subject: subject,
Content: content,
Code: NOTIFICATION_FRIEND_JOIN_GAME,
SenderID: userID,
CreatedAt: ts,
ExpiresAt: expiresAt,
Persistent: true,
}
}
err = p.notificationService.NotificationSend(notifications)
if err != nil {
logger.Warn("Failed to send Facebook friend join notifications", zap.Error(err))
}
}
}
}
}
}()
fbFriends, err := p.socialClient.GetFacebookFriends(accessToken)
if err != nil {
return
}
if len(fbFriends) == 0 {
return
}
tx, err = p.db.Begin()
if err != nil {
return
}
query := "SELECT id FROM users WHERE facebook_id IN ("
friends := make([]interface{}, len(fbFriends))
for i, fbFriend := range fbFriends {
if i != 0 {
query += ", "
}
query += fmt.Sprintf("$%v", i+1)
friends[i] = fbFriend.ID
}
query += ")"
rows, err := tx.Query(query, friends...)
if err != nil {
return
}
defer rows.Close()
queryEdge := "INSERT INTO user_edge (source_id, position, updated_at, destination_id, state) VALUES "
paramsEdge := []interface{}{userID, ts}
queryEdgeMetadata := "UPDATE user_edge_metadata SET count = count + 1, updated_at = $1 WHERE source_id IN ("
paramsEdgeMetadata := []interface{}{ts}
for rows.Next() {
var currentUser []byte
err = rows.Scan(¤tUser)
if err != nil {
return
}
if len(paramsEdge) != 2 {
queryEdge += ", "
}
paramsEdge = append(paramsEdge, currentUser)
queryEdge += fmt.Sprintf("($1, $2, $2, $%v, 0), ($%v, $2, $2, $1, 0)", len(paramsEdge), len(paramsEdge))
if len(paramsEdgeMetadata) != 1 {
queryEdgeMetadata += ", "
}
paramsEdgeMetadata = append(paramsEdgeMetadata, currentUser)
queryEdgeMetadata += fmt.Sprintf("$%v", len(paramsEdgeMetadata))
}
err = rows.Err()
if err != nil {
return
}
queryEdgeMetadata += ")"
// Check if any Facebook friends are already users, if not there are no new edges to handle.
if len(paramsEdge) <= 2 {
return
}
// Insert new friend relationship edges.
_, err = tx.Exec(queryEdge, paramsEdge...)
if err != nil {
return
}
// Update edge metadata for each user to increment count.
_, err = tx.Exec(queryEdgeMetadata, paramsEdgeMetadata...)
if err != nil {
return
}
// Update edge metadata for current user to bump count by number of new friends.
_, err = tx.Exec(`UPDATE user_edge_metadata SET count = $1, updated_at = $2 WHERE source_id = $3`, len(paramsEdge)-2, ts, userID)
if err != nil {
return
}
// Track the user IDs to notify their friend has joined the game.
friendUserIDs = paramsEdge[2:]
}
func (p *pipeline) getFriends(filterQuery string, userID string) ([]*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 sql.NullString
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.String,
Handle: handle.String,
Fullname: fullname.String,
AvatarUrl: avatarURL.String,
Lang: lang.String,
Location: location.String,
Timezone: timezone.String,
Metadata: string(metadata),
CreatedAt: createdAt.Int64,
UpdatedAt: updatedAt.Int64,
LastOnlineAt: lastOnlineAt.Int64,
},
State: state.Int64,
})
}
return friends, nil
}
func (p *pipeline) friendAdd(l *zap.Logger, session session, envelope *Envelope) {
e := envelope.GetFriendsAdd()
if len(e.Friends) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "At least one friend must be present"), true)
return
} else if len(e.Friends) > 1 {
l.Warn("There are more than one friend passed to the request - only processing the first item of the list.")
}
f := e.Friends[0]
switch f.Id.(type) {
case *TFriendsAdd_FriendsAdd_UserId:
p.friendAddById(l, session, envelope, f.GetUserId())
case *TFriendsAdd_FriendsAdd_Handle:
p.friendAddByHandle(l, session, envelope, f.GetHandle())
}
}
func (p *pipeline) friendAddById(l *zap.Logger, session session, envelope *Envelope, friendID string) {
if len(friendID) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID must be present"), true)
return
}
logger := l.With(zap.String("friend_id", friendID))
if friendID == session.UserID() {
logger.Warn("Cannot add self")
session.Send(ErrorMessageBadInput(envelope.CollationId, "Cannot add self"), true)
return
}
if err := friendAdd(logger, p.db, p.notificationService, session.UserID(), session.Handle(), friendID); err != nil {
logger.Error("Could not add friend", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to add friend"), true)
return
}
logger.Debug("Added friend")
session.Send(&Envelope{CollationId: envelope.CollationId}, true)
}
func (p *pipeline) friendAddByHandle(l *zap.Logger, session session, envelope *Envelope, friendHandle string) {
if friendHandle == "" || friendHandle == session.Handle() {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User handle must be present and not equal to user's handle"), true)
return
}
logger := l.With(zap.String("friend_handle", friendHandle))
if err := friendAddHandle(logger, p.db, p.notificationService, session.UserID(), session.Handle(), friendHandle); err != nil {
logger.Error("Could not add friend", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Failed to add friend"), true)
return
}
logger.Debug("Added friend")
session.Send(&Envelope{CollationId: envelope.CollationId}, true)
}
func (p *pipeline) friendRemove(l *zap.Logger, session session, envelope *Envelope) {
e := envelope.GetFriendsRemove()
if len(e.UserIds) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "At least one user ID must be present"), true)
return
} else if len(e.UserIds) > 1 {
l.Warn("There are more than one user ID passed to the request - only processing the first item of the list.")
}
friendID := e.UserIds[0]
if len(friendID) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID must be present"), true)
return
}
logger := l.With(zap.String("friend_id", friendID))
if friendID == session.UserID() {
logger.Warn("Cannot remove self")
session.Send(ErrorMessageBadInput(envelope.CollationId, "Cannot remove self"), true)
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"), true)
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"), true)
} 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"), true)
} else {
logger.Info("Removed friend")
session.Send(&Envelope{CollationId: envelope.CollationId}, true)
}
}
}()
updatedAt := nowMs()
res, err := tx.Exec("DELETE FROM user_edge WHERE source_id = $1 AND destination_id = $2", session.UserID(), friendID)
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(), updatedAt)
}
if err != nil {
return
}
res, err = tx.Exec("DELETE FROM user_edge WHERE source_id = $1 AND destination_id = $2", friendID, session.UserID())
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", friendID, updatedAt)
}
}
func (p *pipeline) friendBlock(l *zap.Logger, session session, envelope *Envelope) {
e := envelope.GetFriendsBlock()
if len(e.UserIds) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "At least one user ID must be present"), true)
return
} else if len(e.UserIds) > 1 {
l.Warn("There are more than one user ID passed to the request - only processing the first item of the list.")
}
userID := e.UserIds[0]
if len(userID) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID must be present"), true)
return
}
logger := l.With(zap.String("user_id", userID))
if userID == session.UserID() {
logger.Warn("Cannot block self")
session.Send(ErrorMessageBadInput(envelope.CollationId, "Cannot block self"), true)
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"), true)
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"), true)
} 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"), true)
} else {
logger.Info("User blocked")
session.Send(&Envelope{CollationId: envelope.CollationId}, true)
}
}
}()
res, err := tx.Exec("UPDATE user_edge SET state = 3, updated_at = $3 WHERE source_id = $1 AND destination_id = $2",
session.UserID(), userID, 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",
userID, session.UserID())
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", userID, 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())
if err != nil {
logger.Error("Could not get friends", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not get friends"), true)
return
}
session.Send(&Envelope{CollationId: envelope.CollationId, Payload: &Envelope_Friends{Friends: &TFriends{Friends: friends}}}, true)
}