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 ()
@@ -140,9 +160,6 @@ func (h *Hub) Run() {
140
160
}
141
161
h .mutex .Unlock ()
142
162
}
143
-
144
-
145
-
146
163
}
147
164
}
148
165
@@ -165,7 +182,6 @@ func serveWs(
165
182
return
166
183
}
167
184
168
-
169
185
client := & Client {conn : conn , roomID : roomID }
170
186
hub .register <- client
171
187
@@ -214,27 +230,35 @@ func handleMessages(
214
230
break
215
231
}
216
232
217
- var msgData map [string ]interface {}
233
+ log .Printf ("Raw message received: %s" , string (message ))
234
+
235
+ var msgData Message
218
236
if err := json .Unmarshal (message , & msgData ); err != nil {
219
237
log .Printf ("Failed to parse message: %v" , err )
220
238
continue
221
239
}
222
240
241
+ log .Printf ("Raw message parsed: %s" , msgData )
223
242
224
- if msgData [ "type" ] == "auth" {
225
- token , tokenOk := msgData [ "token" ].( string )
226
- if ! tokenOk {
243
+ if msgData . Type == AUTH {
244
+ token := msgData . Token
245
+ if token == "" {
227
246
log .Println ("Authentication failed - no token attached" )
228
- client .conn .WriteMessage (
229
- websocket .TextMessage ,
230
- []byte ("Authentication failed" ),
231
- )
247
+
248
+ msg := Message {
249
+ Type : AUTH_FAIL ,
250
+ RoomID : client .roomID ,
251
+ Content : "Authentication failed - no token attached" ,
252
+ }
253
+ msgJson , _ := json .Marshal (msg )
254
+ client .conn .WriteMessage (websocket .TextMessage , msgJson )
232
255
client .conn .Close ()
233
256
break
234
257
}
235
258
isSuccess := false
236
- match , matchOk := msgData ["matchHash" ].(string )
237
- if matchOk && ! authenticateClient (token , match , client , roomMappings , persistMappings ) {
259
+ match := msgData .MatchHash
260
+ if match != "" &&
261
+ ! authenticateClient (token , match , client , roomMappings , persistMappings ) {
238
262
log .Println (
239
263
"failed to find a matching room from match hash, proceeding with persistence check" ,
240
264
)
@@ -247,70 +271,91 @@ func handleMessages(
247
271
isSuccess = true
248
272
}
249
273
if ! isSuccess {
250
- client .conn .WriteMessage (
251
- websocket .TextMessage ,
252
- []byte ("Authentication failed" ),
253
- )
274
+ msg := Message {
275
+ Type : AUTH_FAIL ,
276
+ RoomID : client .roomID ,
277
+ Content : "Authentication failed" ,
278
+ }
279
+ msgJson , _ := json .Marshal (msg )
280
+ client .conn .WriteMessage (websocket .TextMessage , msgJson )
281
+
254
282
client .conn .Close ()
255
283
break
256
284
}
257
285
client .authenticated = true
258
- client .conn .WriteMessage (
259
- websocket .TextMessage ,
260
- []byte ("Auth Success" ),
261
- )
262
- log .Println ("Client authenticated successfully" )
263
- }
264
286
265
- if msgData ["type" ] == "close_session" {
287
+ serverContent := hub .workspaces [client .roomID ]
288
+
289
+ newMsg := Message {
290
+ Type : AUTH_SUCCESS ,
291
+ RoomID : client .roomID ,
292
+ Content : serverContent ,
293
+ }
294
+ msgJson , _ := json .Marshal (newMsg )
295
+ client .conn .WriteMessage (websocket .TextMessage , msgJson )
296
+
297
+ log .Println ("Client authenticated successfully" )
298
+ } else if msgData .Type == CLOSE_SESSION {
266
299
closeMessage := Message {
267
300
RoomID : client .roomID ,
268
- Content : [] byte ( "The session has been closed by a user." ) ,
301
+ Content : "The session has been closed by a user." ,
269
302
}
270
- targetId := msgData [ "userId" ].( string )
303
+ targetId := msgData . UserID
271
304
data , err := persistMappings .Conn .HGetAll (context .Background (), targetId ).Result ()
272
305
if err != nil {
273
306
log .Printf ("Error retrieving data for userID %s: %v" , targetId , err )
274
307
} else {
275
308
_ , err1 := persistMappings .Conn .Del (context .Background (), targetId ).Result ()
276
309
if err1 != nil {
277
- log .Printf ("Error deleting data for userID %s: %v" , targetId , err1 );
310
+ log .Printf ("Error deleting data for userID %s: %v" , targetId , err1 )
278
311
}
279
312
_ , err2 := persistMappings .Conn .Del (context .Background (), data ["otherUser" ]).Result ()
280
313
if err2 != nil {
281
- log .Printf ("Error deleting data for other user %s: %v" , data ["otherUser" ], err2 );
314
+ log .Printf ("Error deleting data for other user %s: %v" , data ["otherUser" ], err2 )
282
315
}
283
316
}
284
317
hub .broadcast <- closeMessage
318
+ } else if msgData .Type == CONTENT_CHANGE {
319
+ // Broadcast the message to other clients
320
+ hub .broadcast <- Message {
321
+ RoomID : client .roomID ,
322
+ Content : msgData .Content ,
323
+ Type : msgData .Type ,
324
+ UserID : msgData .UserID ,
325
+ }
326
+ } else {
327
+ log .Printf ("Unknown message type: %s" , msgData .Type )
285
328
}
286
-
287
- // Broadcast the message to other clients
288
- userID , _ := msgData ["userId" ].(string )
289
- hub .broadcast <- Message {RoomID : client .roomID , Content : message , UserID : userID }
290
329
}
291
330
}
292
331
332
+ type ClientWorkspace struct {
333
+ Clients int `json:"clients"`
334
+ Workspace string `json:"workspace"`
335
+ }
336
+
293
337
// Status endpoint that shows the number of clients and the current color for each roomID
294
338
func statusHandler (hub * Hub ) gin.HandlerFunc {
339
+
295
340
return func (c * gin.Context ) {
296
341
hub .mutex .Lock ()
297
342
defer hub .mutex .Unlock ()
298
343
299
- status := make (map [string ]interface {} )
344
+ status := make (map [string ]ClientWorkspace )
300
345
for client := range hub .clients {
301
346
roomID := client .roomID
302
347
currentStatus , ok := status [roomID ]
303
348
if ! ok {
304
349
// Initialize status for a new roomID
305
- status [roomID ] = map [ string ] interface {} {
306
- "clients" : 1 ,
307
- "workspace" : hub .workspaces [roomID ],
350
+ status [roomID ] = ClientWorkspace {
351
+ Clients : 1 ,
352
+ Workspace : hub .workspaces [roomID ],
308
353
}
309
354
} else {
310
355
// Update the client count for an existing roomID
311
- status [roomID ] = map [ string ] interface {} {
312
- "clients" : currentStatus .( map [ string ] interface {})[ "clients" ].( int ) + 1 ,
313
- "workspace" : hub .workspaces [roomID ],
356
+ status [roomID ] = ClientWorkspace {
357
+ Clients : currentStatus .Clients + 1 ,
358
+ Workspace : hub .workspaces [roomID ],
314
359
}
315
360
}
316
361
}
0 commit comments