-
Notifications
You must be signed in to change notification settings - Fork 181
/
chat-handler.go
370 lines (318 loc) · 9.85 KB
/
chat-handler.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
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package websocket
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"time"
"context"
"github.com/micro/protobuf/jsonpb"
"github.com/pydio/melody"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/auth"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/chat"
"github.com/pydio/cells/common/views"
)
const (
SessionRoomKey = "room"
)
type ChatHandler struct {
Websocket *melody.Melody
Pool *views.ClientsPool
}
func NewChatHandler(serviceCtx context.Context) *ChatHandler {
w := &ChatHandler{}
w.Pool = views.NewClientsPool(true)
w.InitHandlers(serviceCtx)
return w
}
func (c *ChatHandler) getChatClient() chat.ChatServiceClient {
return chat.NewChatServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_CHAT, defaults.NewClient())
}
func (c *ChatHandler) InitHandlers(serviceCtx context.Context) {
c.Websocket = melody.New()
c.Websocket.Config.MaxMessageSize = 2048
c.Websocket.HandleError(func(session *melody.Session, i error) {
if !strings.Contains(i.Error(), "close 1000 (normal)") {
log.Logger(serviceCtx).Debug("HandleError", zap.Error(i))
}
ClearSession(session)
})
c.Websocket.HandleClose(func(session *melody.Session, i int, i2 string) error {
ClearSession(session)
return nil
})
c.Websocket.HandleMessage(func(session *melody.Session, payload []byte) {
msg := &Message{}
e := json.Unmarshal(payload, msg)
if e == nil {
switch msg.Type {
case MsgSubscribe:
if msg.JWT == "" {
session.CloseWithMsg(NewErrorMessageString("Empty JWT"))
log.Logger(serviceCtx).Debug("empty jwt")
return
}
ctx := context.Background()
verifier := auth.DefaultJWTVerifier()
_, claims, e := verifier.Verify(ctx, msg.JWT)
if e != nil {
log.Logger(serviceCtx).Error("invalid jwt received from websocket connection")
session.CloseWithMsg(NewErrorMessage(e))
return
}
UpdateSessionFromClaims(session, claims, c.Pool)
return
case MsgUnsubscribe:
ClearSession(session)
return
}
}
chatMsg := &chat.WebSocketMessage{}
buff := bytes.NewBuffer(payload)
e = jsonpb.Unmarshal(buff, chatMsg)
marshaller := &jsonpb.Marshaler{}
if e == nil {
// SAVE CTX IN SESSION?
ctx := context.Background()
log.Logger(serviceCtx).Debug("Got Message", zap.Any("msg", chatMsg))
var userName string
if userData, ok := session.Get(SessionUsernameKey); !ok && userData != nil {
log.Logger(ctx).Error("Chat Message requires ws subscription first")
return
} else {
userName, ok = userData.(string)
if !ok {
log.Logger(ctx).Error("Chat Message requires ws subscription first")
return
}
}
switch chatMsg.Type {
case chat.WsMessageType_JOIN:
foundRoom, e1 := c.FindOrCreateRoom(ctx, chatMsg.Room, true)
log.Logger(serviceCtx).Debug("JOIN", zap.Any("msg", chatMsg), zap.Any("r", foundRoom), zap.Error(e1))
if e1 == nil {
session = c.roomsWithValue(session, foundRoom.Uuid)
}
if foundRoom == nil {
break
}
// Update Room Users
c.AppendUserToRoom(foundRoom, userName)
chatClient := c.getChatClient()
_, e := chatClient.PutRoom(ctx, &chat.PutRoomRequest{Room: foundRoom})
if e != nil {
log.Logger(ctx).Error("Error while putting room", zap.Error(e))
}
case chat.WsMessageType_LEAVE:
foundRoom, e1 := c.FindOrCreateRoom(ctx, chatMsg.Room, false)
if e1 == nil && foundRoom != nil {
c.RemoveUserFromRoom(foundRoom, userName)
c.getChatClient().PutRoom(ctx, &chat.PutRoomRequest{Room: foundRoom})
log.Logger(serviceCtx).Debug("LEAVE", zap.Any("msg", chatMsg), zap.Any("r", foundRoom))
session = c.roomsWithoutValue(session, foundRoom.Uuid)
}
case chat.WsMessageType_HISTORY:
// Must arrive AFTER a JOIN message
foundRoom, e1 := c.FindOrCreateRoom(ctx, chatMsg.Room, false)
if e1 != nil {
break
}
chatClient := c.getChatClient()
// List existing Messages
stream, e2 := chatClient.ListMessages(ctx, &chat.ListMessagesRequest{RoomUuid: foundRoom.Uuid})
if e2 == nil {
defer stream.Close()
for {
resp, e3 := stream.Recv()
if e3 != nil {
break
}
b := bytes.NewBuffer([]byte{})
marshaller.Marshal(b, resp.Message)
session.Write(b.Bytes())
}
}
case chat.WsMessageType_POST:
log.Logger(serviceCtx).Debug("POST", zap.Any("msg", chatMsg))
message := chatMsg.Message
message.Author = userName
message.Timestamp = time.Now().Unix()
_, e := c.getChatClient().PostMessage(ctx, &chat.PostMessageRequest{
Messages: []*chat.ChatMessage{message},
})
if e != nil {
log.Logger(ctx).Error("Error while posting message", zap.Any("msg", message), zap.Error(e))
}
case chat.WsMessageType_DELETE_MSG:
log.Logger(serviceCtx).Debug("Delete", zap.Any("msg", chatMsg))
message := chatMsg.Message
if message.Author == userName {
_, e := c.getChatClient().DeleteMessage(ctx, &chat.DeleteMessageRequest{
Messages: []*chat.ChatMessage{message},
})
if e != nil {
log.Logger(ctx).Error("Error while deleting message", zap.Any("msg", message), zap.Error(e))
}
}
}
} else {
log.Logger(serviceCtx).Debug("Could not unmarshal message", zap.Error(e))
}
})
}
func (c *ChatHandler) roomsHaveValue(session *melody.Session, roomUuid string) bool {
if key, ok := session.Get(SessionRoomKey); ok && key != nil {
rooms := key.([]string)
for _, v := range rooms {
if v == roomUuid {
return true
}
}
log.Logger(context.Background()).Debug("looking for rooms in session", zap.Any("rooms", rooms), zap.String("search", roomUuid))
}
return false
}
func (c *ChatHandler) roomsWithValue(session *melody.Session, roomUuid string) *melody.Session {
var rooms []string
if key, ok := session.Get(SessionRoomKey); ok && key != nil {
rooms = key.([]string)
}
found := false
for _, v := range rooms {
if v == roomUuid {
found = true
}
}
if !found {
rooms = append(rooms, roomUuid)
log.Logger(context.Background()).Debug("storing rooms to session", zap.Any("room", roomUuid), zap.Any("rooms", rooms))
session.Set(SessionRoomKey, rooms)
} else {
log.Logger(context.Background()).Debug("rooms to session already found", zap.Any("room", roomUuid), zap.Any("rooms", rooms))
}
return session
}
func (c *ChatHandler) roomsWithoutValue(session *melody.Session, roomUuid string) *melody.Session {
var rooms []string
if key, ok := session.Get(SessionRoomKey); ok && key != nil {
rooms = key.([]string)
}
var newRooms []string
for _, k := range rooms {
if k != roomUuid {
newRooms = append(newRooms, k)
}
}
log.Logger(context.Background()).Debug("removing room from session", zap.Any("room", roomUuid), zap.Any("rooms", newRooms))
session.Set(SessionRoomKey, newRooms)
return session
}
func (c *ChatHandler) FindOrCreateRoom(ctx context.Context, room *chat.ChatRoom, createIfNotExists bool) (*chat.ChatRoom, error) {
chatClient := c.getChatClient()
s, e := chatClient.ListRooms(ctx, &chat.ListRoomsRequest{
ByType: room.Type,
TypeObject: room.RoomTypeObject,
})
if e != nil {
return nil, e
}
defer s.Close()
for {
resp, rE := s.Recv()
if rE != nil {
break
}
if resp == nil {
continue
}
return resp.Room, nil
}
if !createIfNotExists {
return nil, nil
}
// if not returned yet, create
resp, e1 := chatClient.PutRoom(ctx, &chat.PutRoomRequest{Room: room})
if e1 != nil {
return nil, e1
}
if resp.Room == nil {
return nil, fmt.Errorf("nil room in response, this is not normal")
}
return resp.Room, nil
}
func (c *ChatHandler) AppendUserToRoom(room *chat.ChatRoom, userName string) {
uniq := map[string]string{}
for _, u := range room.Users {
uniq[u] = u
}
uniq[userName] = userName
room.Users = []string{}
for _, name := range uniq {
room.Users = append(room.Users, name)
}
}
func (c *ChatHandler) RemoveUserFromRoom(room *chat.ChatRoom, userName string) {
users := []string{}
for _, u := range room.Users {
if u != userName {
users = append(users, u)
}
}
room.Users = users
}
func (c *ChatHandler) BroadcastChatMessage(ctx context.Context, msg *chat.ChatEvent) error {
marshaller := &jsonpb.Marshaler{}
buff := bytes.NewBuffer([]byte{})
var compareRoomId string
if msg.Message != nil {
if msg.Details == "DELETE" {
wsMessage := &chat.WebSocketMessage{
Type: chat.WsMessageType_DELETE_MSG,
Message: msg.Message,
}
marshaller.Marshal(buff, wsMessage)
} else {
marshaller.Marshal(buff, msg.Message)
}
compareRoomId = msg.Message.RoomUuid
} else if msg.Room != nil {
compareRoomId = msg.Room.Uuid
wsMessage := &chat.WebSocketMessage{
Type: chat.WsMessageType_ROOM_UPDATE,
Room: msg.Room,
}
marshaller.Marshal(buff, wsMessage)
} else {
return fmt.Errorf("Event should provide at least a Msg or a Room")
}
return c.Websocket.BroadcastFilter(buff.Bytes(), func(session *melody.Session) bool {
if session.IsClosed() {
log.Logger(ctx).Error("Session is closed")
return false
}
return c.roomsHaveValue(session, compareRoomId)
})
}