-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathhandlers.go
445 lines (352 loc) · 12 KB
/
handlers.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
package handlers
import (
"database/sql"
"fmt"
"log"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/YuriyNasretdinov/social-net/db"
"github.com/YuriyNasretdinov/social-net/events"
"github.com/YuriyNasretdinov/social-net/protocol"
)
const (
dateFormat = "2006-01-02"
maxTimelineLength = 1 << 16
maxMessageLength = 1 << 16
)
type (
WebsocketCtx struct {
SeqId int
UserId uint64
Listener chan interface{}
UserName string
}
)
func (ctx *WebsocketCtx) ProcessGetMessages(req *protocol.RequestGetMessages) protocol.Reply {
dateEnd := req.DateEnd
if dateEnd == "" {
dateEnd = fmt.Sprint(time.Now().UnixNano())
}
limit := req.Limit
if limit > protocol.MAX_MESSAGES_LIMIT {
limit = protocol.MAX_MESSAGES_LIMIT
}
if limit <= 0 {
return &protocol.ResponseError{UserMsg: "Limit must be greater than 0"}
}
rows, err := db.GetMessagesStmt.Query(ctx.UserId, req.UserTo, dateEnd, limit)
if err != nil {
return &protocol.ResponseError{UserMsg: "Cannot select messages", Err: err}
}
reply := new(protocol.ReplyMessagesList)
reply.Messages = make([]protocol.Message, 0)
defer rows.Close()
for rows.Next() {
var msg protocol.Message
if err = rows.Scan(&msg.Id, &msg.Text, &msg.Ts, &msg.IsOut); err != nil {
return &protocol.ResponseError{UserMsg: "Cannot select messages", Err: err}
}
msg.UserFrom = fmt.Sprint(req.UserTo)
reply.Messages = append(reply.Messages, msg)
}
return reply
}
func (ctx *WebsocketCtx) ProcessGetUsersList(req *protocol.RequestGetUsersList) protocol.Reply {
limit := req.Limit
if limit > protocol.MAX_USERS_LIST_LIMIT {
limit = protocol.MAX_USERS_LIST_LIMIT
}
if limit <= 0 {
return &protocol.ResponseError{UserMsg: "Limit must be greater than 0"}
}
var rows *sql.Rows
var err error
if req.Search == "" {
rows, err = db.GetUsersListStmt.Query(req.MinId, limit)
if err != nil {
return &protocol.ResponseError{UserMsg: "Cannot select users", Err: err}
}
} else {
rows, err = db.GetUsersListWithSearchStmt.Query(req.MinId, "%"+req.Search+"%", limit)
if err != nil {
return &protocol.ResponseError{UserMsg: "Cannot select users", Err: err}
}
}
reply := new(protocol.ReplyUsersList)
reply.Users = make([]protocol.JSUserListInfo, 0)
potentialFriends := make([]string, 0)
defer rows.Close()
for rows.Next() {
var user protocol.JSUserListInfo
var potentialFriendId int64
if err = rows.Scan(&user.Name, &potentialFriendId); err != nil {
return &protocol.ResponseError{UserMsg: "Cannot select users", Err: err}
}
user.Id = fmt.Sprint(potentialFriendId)
reply.Users = append(reply.Users, user)
potentialFriends = append(potentialFriends, user.Id)
}
friendsMap := make(map[string]bool)
if len(potentialFriends) > 0 {
friendRows, err := db.Db.Query(`SELECT friend_user_id, request_accepted FROM friend
WHERE user_id = ` + fmt.Sprint(ctx.UserId) + ` AND friend_user_id IN(` + strings.Join(potentialFriends, ",") + `)`)
if err != nil {
return &protocol.ResponseError{UserMsg: "Cannot select users", Err: err}
}
defer friendRows.Close()
for friendRows.Next() {
var friendId string
var requestAccepted bool
if err = friendRows.Scan(&friendId, &requestAccepted); err != nil {
return &protocol.ResponseError{UserMsg: "Cannot select users", Err: err}
}
friendsMap[friendId] = requestAccepted
}
}
for i, user := range reply.Users {
reply.Users[i].FriendshipConfirmed, reply.Users[i].IsFriend = friendsMap[user.Id]
}
return reply
}
func (ctx *WebsocketCtx) ProcessGetFriends(req *protocol.RequestGetFriends) protocol.Reply {
limit := req.Limit
if limit > protocol.MAX_FRIENDS_LIMIT {
limit = protocol.MAX_FRIENDS_LIMIT
}
if limit <= 0 {
return &protocol.ResponseError{UserMsg: "Limit must be greater than 0"}
}
friendUserIds, err := db.GetUserFriends(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get friends", Err: err}
}
friendRequestUserIds, err := db.GetUserFriendsRequests(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get friends", Err: err}
}
reply := new(protocol.ReplyGetFriends)
reply.Users = make([]protocol.JSUserInfo, 0)
reply.FriendRequests = make([]protocol.JSUserInfo, 0)
friendUserIdsStr := make([]string, 0)
for _, userId := range friendUserIds {
userIdStr := fmt.Sprint(userId)
reply.Users = append(reply.Users, protocol.JSUserInfo{Id: userIdStr})
friendUserIdsStr = append(friendUserIdsStr, userIdStr)
}
for _, userId := range friendRequestUserIds {
userIdStr := fmt.Sprint(userId)
reply.FriendRequests = append(reply.FriendRequests, protocol.JSUserInfo{Id: userIdStr})
friendUserIdsStr = append(friendUserIdsStr, userIdStr)
}
userNames, err := db.GetUserNames(friendUserIdsStr)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get friends", Err: err}
}
for i, user := range reply.Users {
reply.Users[i].Name = userNames[user.Id]
}
for i, user := range reply.FriendRequests {
reply.FriendRequests[i].Name = userNames[user.Id]
}
return reply
}
func (ctx *WebsocketCtx) ProcessSendMessage(req *protocol.RequestSendMessage) protocol.Reply {
// TODO: verify that user has rights to send message to the specified person
var (
err error
now = time.Now().UnixNano()
)
if len(req.Text) == 0 {
return &protocol.ResponseError{UserMsg: "Message text must not be empty"}
} else if utf8.RuneCountInString(req.Text) > maxMessageLength {
return &protocol.ResponseError{UserMsg: fmt.Sprintf("Text cannot exceed %d characters", maxMessageLength)}
}
_, err = db.SendMessageStmt.Exec(ctx.UserId, req.UserTo, protocol.MSG_TYPE_OUT, req.Text, now)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not log outgoing message", Err: err}
}
_, err = db.SendMessageStmt.Exec(req.UserTo, ctx.UserId, protocol.MSG_TYPE_IN, req.Text, now)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not log incoming message", Err: err}
}
reply := new(protocol.ReplyGeneric)
reply.Success = true
events.EventsFlow <- &events.ControlEvent{
EvType: events.EVENT_NEW_MESSAGE,
Listener: ctx.Listener,
Info: &events.InternalEventNewMessage{
UserFrom: ctx.UserId,
UserFromName: ctx.UserName,
UserTo: req.UserTo,
Ts: fmt.Sprint(now),
Text: req.Text,
},
}
return reply
}
func (ctx *WebsocketCtx) ProcessAddFriend(req *protocol.RequestAddFriend) protocol.Reply {
var (
err error
friendId uint64
)
if friendId, err = strconv.ParseUint(req.FriendId, 10, 64); err != nil {
return &protocol.ResponseError{UserMsg: "Friend id is not numeric"}
}
if friendId == ctx.UserId {
return &protocol.ResponseError{UserMsg: "You cannot add yourself as a friend"}
}
if _, err = db.AddFriendsRequestStmt.Exec(ctx.UserId, friendId, 1); err != nil {
return &protocol.ResponseError{UserMsg: "Could not add user as a friend", Err: err}
}
if _, err = db.AddFriendsRequestStmt.Exec(friendId, ctx.UserId, 0); err != nil {
return &protocol.ResponseError{UserMsg: "Could not add user as a friend", Err: err}
}
ev := &events.EventFriendRequest{}
ev.UserId = friendId
ev.Type = "EVENT_FRIEND_REQUEST"
events.EventsFlow <- &events.ControlEvent{
EvType: events.EVENT_FRIEND_REQUEST,
Listener: ctx.Listener,
Reply: ev,
}
reply := new(protocol.ReplyGeneric)
reply.Success = true
return reply
}
func (ctx *WebsocketCtx) ProcessConfirmFriendship(req *protocol.RequestConfirmFriendship) protocol.Reply {
var (
err error
friendId uint64
)
if friendId, err = strconv.ParseUint(req.FriendId, 10, 64); err != nil {
return &protocol.ResponseError{UserMsg: "Friend id is not numeric"}
}
if _, err = db.ConfirmFriendshipStmt.Exec(ctx.UserId, friendId); err != nil {
return &protocol.ResponseError{UserMsg: "Could not confirm friendship", Err: err}
}
reply := new(protocol.ReplyGeneric)
reply.Success = true
return reply
}
func (ctx *WebsocketCtx) ProcessGetMessagesUsers(req *protocol.RequestGetMessagesUsers) protocol.Reply {
var (
err error
id uint64
ts string
)
rows, err := db.GetMessagesUsersStmt.Query(ctx.UserId, req.Limit)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get users list for messages", Err: err}
}
defer rows.Close()
reply := new(protocol.ReplyGetMessagesUsers)
reply.Users = make([]protocol.JSUserInfo, 0)
userIds := make([]string, 0)
usersMap := make(map[uint64]bool)
for rows.Next() {
if err := rows.Scan(&id, &ts); err != nil {
return &protocol.ResponseError{UserMsg: "Could not get users list for messages", Err: err}
}
usersMap[id] = true
userId := fmt.Sprint(id)
reply.Users = append(reply.Users, protocol.JSUserInfo{Id: userId})
userIds = append(userIds, userId)
}
friendIds, err := db.GetUserFriends(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get users list for messages", Err: err}
}
for _, friendId := range friendIds {
if usersMap[friendId] {
continue
}
userId := fmt.Sprint(friendId)
reply.Users = append(reply.Users, protocol.JSUserInfo{Id: userId})
userIds = append(userIds, userId)
}
userNames, err := db.GetUserNames(userIds)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get users list for messages", Err: err}
}
for i, user := range reply.Users {
reply.Users[i].Name = userNames[user.Id]
}
return reply
}
func (ctx *WebsocketCtx) ProcessGetProfile(req *protocol.RequestGetProfile) protocol.Reply {
reply := new(protocol.ReplyGetProfile)
userIdStr := fmt.Sprint(req.UserId)
userNames, err := db.GetUserNames([]string{userIdStr})
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get user profile", Err: err}
}
if len(userNames) == 0 {
return &protocol.ResponseError{UserMsg: "No such user", Err: err}
}
reply.Name = userNames[userIdStr]
row, err := db.GetProfileStmt.Query(req.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get user profile", Err: err}
}
defer row.Close()
var birthdate time.Time
if !row.Next() {
return reply
}
err = row.Scan(&reply.Name, &birthdate, &reply.Sex, &reply.Description, &reply.CityId, &reply.FamilyPosition)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get user profile", Err: err}
}
reply.Birthdate = birthdate.Format(dateFormat)
city, err := db.GetCityInfo(reply.CityId)
if err != nil {
log.Printf("Could not get city by id=%d for user id=%d", reply.CityId, req.UserId)
city = &db.City{}
}
reply.FriendsCount, err = db.GetUserFriendsCount(req.UserId)
if err != nil {
log.Printf("Could not get friends count for user %d: %s", req.UserId, err.Error())
}
reply.IsFriend, reply.RequestAccepted, err = db.IsUserFriend(ctx.UserId, req.UserId)
if err != nil {
log.Printf("Could not get information about friendship for user %d: %s", req.UserId, err.Error())
}
reply.CityName = city.Name
return reply
}
func (ctx *WebsocketCtx) ProcessUpdateProfile(req *protocol.RequestUpdateProfile) protocol.Reply {
reply := new(protocol.ReplyGeneric)
reply.Success = true
if req.CityName == "" || req.Birthdate == "" || req.Name == "" {
return &protocol.ResponseError{UserMsg: "All fields must be filled in"}
}
var cityId uint64
city, err := db.GetCityInfoByName(req.CityName)
if err != nil {
res := db.AddCityStmt.QueryRow(req.CityName, 0, 0)
if err = res.Scan(&cityId); err != nil {
return &protocol.ResponseError{UserMsg: "Could not update user profile", Err: err}
}
} else {
cityId = city.Id
}
row, err := db.GetProfileStmt.Query(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not update user profile", Err: err}
}
defer row.Close()
if !row.Next() {
_, err := db.AddProfileStmt.Exec(&ctx.UserId, &req.Name, &req.Birthdate, &req.Sex, "", &cityId, &req.FamilyPosition)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not update user profile", Err: err}
}
} else {
_, err := db.UpdateProfileStmt.Exec(&req.Name, &req.Birthdate, &req.Sex, "", &cityId, &req.FamilyPosition, &ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not update user profile", Err: err}
}
}
return reply
}