1
1
package main
2
2
3
3
import (
4
- verify "collab/verify"
4
+ "collab/verify"
5
5
"context"
6
6
"encoding/json"
7
7
"io"
@@ -15,6 +15,15 @@ import (
15
15
"github.com/gorilla/websocket"
16
16
)
17
17
18
+ // types
19
+ const (
20
+ AUTH = "auth"
21
+ AUTH_SUCCESS = "auth_success"
22
+ AUTH_FAIL = "auth_fail"
23
+ CLOSE_SESSION = "close_session"
24
+ CONTENT_CHANGE = "content_change"
25
+ )
26
+
18
27
var upgrader = websocket.Upgrader {
19
28
CheckOrigin : func (r * http.Request ) bool {
20
29
return true
@@ -37,10 +46,12 @@ type Hub struct {
37
46
}
38
47
39
48
type Message struct {
40
- Type string `json:"type"`
41
- RoomID string `json:"roomId"`
42
- Content []byte `json:"data"`
43
- UserID string `json:"userId"`
49
+ Type string `json:"type"`
50
+ RoomID string `json:"roomId"`
51
+ Content string `json:"data"`
52
+ UserID string `json:"userId"`
53
+ Token string `json:"token"`
54
+ MatchHash string `json:"matchHash"`
44
55
}
45
56
46
57
func verifyToken (token string ) (bool , string ) {
@@ -127,10 +138,19 @@ func (h *Hub) Run() {
127
138
case message := <- h .broadcast :
128
139
h .mutex .Lock ()
129
140
// Update the current workspace for this RoomID
130
- h .workspaces [message .RoomID ] = string ( message .Content )
141
+ h .workspaces [message .RoomID ] = message .Content
131
142
for client := range h .clients {
132
143
if client .roomID == message .RoomID {
133
- err := client .conn .WriteMessage (websocket .TextMessage , message .Content )
144
+
145
+ log .Println ("Original message: " , message )
146
+
147
+ msgJson , _ := json .Marshal (message )
148
+
149
+ log .Printf ("Sending message to client: %s" , msgJson )
150
+
151
+ err := client .conn .WriteMessage (websocket .TextMessage ,
152
+ msgJson ,
153
+ )
134
154
if err != nil {
135
155
log .Printf ("Error sending message: %v" , err )
136
156
client .conn .Close ()
@@ -165,7 +185,6 @@ func serveWs(
165
185
return
166
186
}
167
187
168
-
169
188
client := & Client {conn : conn , roomID : roomID }
170
189
hub .register <- client
171
190
@@ -214,27 +233,35 @@ func handleMessages(
214
233
break
215
234
}
216
235
217
- var msgData map [string ]interface {}
236
+ log .Printf ("Raw message received: %s" , string (message ))
237
+
238
+ var msgData Message
218
239
if err := json .Unmarshal (message , & msgData ); err != nil {
219
240
log .Printf ("Failed to parse message: %v" , err )
220
241
continue
221
242
}
222
243
244
+ log .Printf ("Raw message parsed: %s" , msgData )
223
245
224
- if msgData [ "type" ] == "auth" {
225
- token , tokenOk := msgData [ "token" ].( string )
226
- if ! tokenOk {
246
+ if msgData . Type == AUTH {
247
+ token := msgData . Token
248
+ if token == "" {
227
249
log .Println ("Authentication failed - no token attached" )
228
- client .conn .WriteMessage (
229
- websocket .TextMessage ,
230
- []byte ("Authentication failed" ),
231
- )
250
+
251
+ msg := Message {
252
+ Type : AUTH_FAIL ,
253
+ RoomID : client .roomID ,
254
+ Content : "Authentication failed - no token attached" ,
255
+ }
256
+ msgJson , _ := json .Marshal (msg )
257
+ client .conn .WriteMessage (websocket .TextMessage , msgJson )
232
258
client .conn .Close ()
233
259
break
234
260
}
235
261
isSuccess := false
236
- match , matchOk := msgData ["matchHash" ].(string )
237
- if matchOk && ! authenticateClient (token , match , client , roomMappings , persistMappings ) {
262
+ match := msgData .MatchHash
263
+ if match != "" &&
264
+ ! authenticateClient (token , match , client , roomMappings , persistMappings ) {
238
265
log .Println (
239
266
"failed to find a matching room from match hash, proceeding with persistence check" ,
240
267
)
@@ -247,18 +274,29 @@ func handleMessages(
247
274
isSuccess = true
248
275
}
249
276
if ! isSuccess {
250
- client .conn .WriteMessage (
251
- websocket .TextMessage ,
252
- []byte ("Authentication failed" ),
253
- )
277
+ msg := Message {
278
+ Type : AUTH_FAIL ,
279
+ RoomID : client .roomID ,
280
+ Content : "Authentication failed" ,
281
+ }
282
+ msgJson , _ := json .Marshal (msg )
283
+ client .conn .WriteMessage (websocket .TextMessage , msgJson )
284
+
254
285
client .conn .Close ()
255
286
break
256
287
}
257
288
client .authenticated = true
258
- client .conn .WriteMessage (
259
- websocket .TextMessage ,
260
- []byte ("Auth Success" ),
261
- )
289
+
290
+ serverContent := hub .workspaces [client .roomID ]
291
+
292
+ newMsg := Message {
293
+ Type : AUTH_SUCCESS ,
294
+ RoomID : client .roomID ,
295
+ Content : serverContent ,
296
+ }
297
+ msgJson , _ := json .Marshal (newMsg )
298
+ client .conn .WriteMessage (websocket .TextMessage , msgJson )
299
+
262
300
log .Println ("Client authenticated successfully" )
263
301
}
264
302
// i can comment out this whole block and it would work
@@ -277,55 +315,67 @@ func handleMessages(
277
315
// hub.broadcast <- request
278
316
// }
279
317
280
- if msgData [ "type" ] == "close_session" {
318
+ if msgData . Type == CLOSE_SESSION {
281
319
closeMessage := Message {
282
320
RoomID : client .roomID ,
283
- Content : [] byte ( "The session has been closed by a user." ) ,
321
+ Content : "The session has been closed by a user." ,
284
322
}
285
- targetId := msgData [ "userId" ].( string )
323
+ targetId := msgData . UserID
286
324
data , err := persistMappings .Conn .HGetAll (context .Background (), targetId ).Result ()
287
325
if err != nil {
288
326
log .Printf ("Error retrieving data for userID %s: %v" , targetId , err )
289
327
} else {
290
328
_ , err1 := persistMappings .Conn .Del (context .Background (), targetId ).Result ()
291
329
if err1 != nil {
292
- log .Printf ("Error deleting data for userID %s: %v" , targetId , err1 );
330
+ log .Printf ("Error deleting data for userID %s: %v" , targetId , err1 )
293
331
}
294
332
_ , err2 := persistMappings .Conn .Del (context .Background (), data ["otherUser" ]).Result ()
295
333
if err2 != nil {
296
- log .Printf ("Error deleting data for other user %s: %v" , data ["otherUser" ], err2 );
334
+ log .Printf ("Error deleting data for other user %s: %v" , data ["otherUser" ], err2 )
297
335
}
298
336
}
299
337
hub .broadcast <- closeMessage
338
+ } else if msgData .Type == CONTENT_CHANGE {
339
+ // Broadcast the message to other clients
340
+ hub .broadcast <- Message {
341
+ RoomID : client .roomID ,
342
+ Content : msgData .Content ,
343
+ Type : msgData .Type ,
344
+ UserID : msgData .UserID ,
345
+ }
346
+ } else {
347
+ log .Printf ("Unknown message type: %s" , msgData .Type )
300
348
}
301
-
302
- // Broadcast the message to other clients
303
- userID , _ := msgData ["userId" ].(string )
304
- hub .broadcast <- Message {RoomID : client .roomID , Content : message , UserID : userID }
305
349
}
306
350
}
307
351
352
+ type ClientWorkspace struct {
353
+ Clients int `json:"clients"`
354
+ Workspace string `json:"workspace"`
355
+ }
356
+
308
357
// Status endpoint that shows the number of clients and the current color for each roomID
309
358
func statusHandler (hub * Hub ) gin.HandlerFunc {
359
+
310
360
return func (c * gin.Context ) {
311
361
hub .mutex .Lock ()
312
362
defer hub .mutex .Unlock ()
313
363
314
- status := make (map [string ]interface {} )
364
+ status := make (map [string ]ClientWorkspace )
315
365
for client := range hub .clients {
316
366
roomID := client .roomID
317
367
currentStatus , ok := status [roomID ]
318
368
if ! ok {
319
369
// Initialize status for a new roomID
320
- status [roomID ] = map [ string ] interface {} {
321
- "clients" : 1 ,
322
- "workspace" : hub .workspaces [roomID ],
370
+ status [roomID ] = ClientWorkspace {
371
+ Clients : 1 ,
372
+ Workspace : hub .workspaces [roomID ],
323
373
}
324
374
} else {
325
375
// Update the client count for an existing roomID
326
- status [roomID ] = map [ string ] interface {} {
327
- "clients" : currentStatus .( map [ string ] interface {})[ "clients" ].( int ) + 1 ,
328
- "workspace" : hub .workspaces [roomID ],
376
+ status [roomID ] = ClientWorkspace {
377
+ Clients : currentStatus .Clients + 1 ,
378
+ Workspace : hub .workspaces [roomID ],
329
379
}
330
380
}
331
381
}
0 commit comments