Skip to content

Commit 01666e6

Browse files
committed
Merge remote-tracking branch 'origin/save-history-on-server' into collab-post-ms6
2 parents 73a9287 + 95c92f9 commit 01666e6

File tree

4 files changed

+193
-119
lines changed

4 files changed

+193
-119
lines changed

collab/main.go

Lines changed: 92 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package main
22

33
import (
4-
verify "collab/verify"
4+
"collab/verify"
55
"context"
66
"encoding/json"
77
"io"
@@ -15,6 +15,15 @@ import (
1515
"github.com/gorilla/websocket"
1616
)
1717

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+
1827
var upgrader = websocket.Upgrader{
1928
CheckOrigin: func(r *http.Request) bool {
2029
return true
@@ -37,10 +46,12 @@ type Hub struct {
3746
}
3847

3948
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"`
4455
}
4556

4657
func verifyToken(token string) (bool, string) {
@@ -127,10 +138,19 @@ func (h *Hub) Run() {
127138
case message := <-h.broadcast:
128139
h.mutex.Lock()
129140
// Update the current workspace for this RoomID
130-
h.workspaces[message.RoomID] = string(message.Content)
141+
h.workspaces[message.RoomID] = message.Content
131142
for client := range h.clients {
132143
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+
)
134154
if err != nil {
135155
log.Printf("Error sending message: %v", err)
136156
client.conn.Close()
@@ -165,7 +185,6 @@ func serveWs(
165185
return
166186
}
167187

168-
169188
client := &Client{conn: conn, roomID: roomID}
170189
hub.register <- client
171190

@@ -214,27 +233,35 @@ func handleMessages(
214233
break
215234
}
216235

217-
var msgData map[string]interface{}
236+
log.Printf("Raw message received: %s", string(message))
237+
238+
var msgData Message
218239
if err := json.Unmarshal(message, &msgData); err != nil {
219240
log.Printf("Failed to parse message: %v", err)
220241
continue
221242
}
222243

244+
log.Printf("Raw message parsed: %s", msgData)
223245

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 == "" {
227249
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)
232258
client.conn.Close()
233259
break
234260
}
235261
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) {
238265
log.Println(
239266
"failed to find a matching room from match hash, proceeding with persistence check",
240267
)
@@ -247,18 +274,29 @@ func handleMessages(
247274
isSuccess = true
248275
}
249276
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+
254285
client.conn.Close()
255286
break
256287
}
257288
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+
262300
log.Println("Client authenticated successfully")
263301
}
264302
// i can comment out this whole block and it would work
@@ -277,55 +315,67 @@ func handleMessages(
277315
// hub.broadcast <- request
278316
// }
279317

280-
if msgData["type"] == "close_session" {
318+
if msgData.Type == CLOSE_SESSION {
281319
closeMessage := Message{
282320
RoomID: client.roomID,
283-
Content: []byte("The session has been closed by a user."),
321+
Content: "The session has been closed by a user.",
284322
}
285-
targetId := msgData["userId"].(string)
323+
targetId := msgData.UserID
286324
data, err := persistMappings.Conn.HGetAll(context.Background(), targetId).Result()
287325
if err != nil {
288326
log.Printf("Error retrieving data for userID %s: %v", targetId, err)
289327
} else {
290328
_, err1 := persistMappings.Conn.Del(context.Background(), targetId).Result()
291329
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)
293331
}
294332
_, err2 := persistMappings.Conn.Del(context.Background(), data["otherUser"]).Result()
295333
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)
297335
}
298336
}
299337
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)
300348
}
301-
302-
// Broadcast the message to other clients
303-
userID, _ := msgData["userId"].(string)
304-
hub.broadcast <- Message{RoomID: client.roomID, Content: message, UserID: userID}
305349
}
306350
}
307351

352+
type ClientWorkspace struct {
353+
Clients int `json:"clients"`
354+
Workspace string `json:"workspace"`
355+
}
356+
308357
// Status endpoint that shows the number of clients and the current color for each roomID
309358
func statusHandler(hub *Hub) gin.HandlerFunc {
359+
310360
return func(c *gin.Context) {
311361
hub.mutex.Lock()
312362
defer hub.mutex.Unlock()
313363

314-
status := make(map[string]interface{})
364+
status := make(map[string]ClientWorkspace)
315365
for client := range hub.clients {
316366
roomID := client.roomID
317367
currentStatus, ok := status[roomID]
318368
if !ok {
319369
// 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],
323373
}
324374
} else {
325375
// 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],
329379
}
330380
}
331381
}

peerprep/app/questions/[question]/[roomID]/question.tsx

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ interface Props {
1212
authToken?: string;
1313
userId?: string;
1414
matchHash?: string;
15-
1615
}
1716

1817
interface DifficultyChipProps {
@@ -29,7 +28,13 @@ function DifficultyChip({ diff }: DifficultyChipProps) {
2928
);
3029
}
3130

32-
function QuestionBlock({ question, roomID, authToken, userId, matchHash }: Props) {
31+
function QuestionBlock({
32+
question,
33+
roomID,
34+
authToken,
35+
userId,
36+
matchHash,
37+
}: Props) {
3338
return (
3439
<>
3540
<div className={styles.qn_container}>
@@ -64,7 +69,6 @@ function QuestionBlock({ question, roomID, authToken, userId, matchHash }: Props
6469
</div>
6570
<div className={styles.editor_container}>
6671
<CollabEditor
67-
question={question}
6872
roomID={roomID}
6973
authToken={authToken}
7074
matchHash={matchHash}

peerprep/app/questions/[question]/question.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ function QuestionBlock({ question }: Props) {
8484
}
8585
</div>
8686
<div className={styles.editor_container}>
87-
<CollabEditor question={question} />
87+
<CollabEditor />
8888
</div>
8989
</>
9090
);

0 commit comments

Comments
 (0)