Repository navigation
feat: add friend challenge with invite link and rematch #415
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
7113894
778e758
f4de606
53a3593
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,10 +2,13 @@ package routes | |
|
|
||
| import ( | ||
| "context" | ||
| "crypto/rand" | ||
| "encoding/hex" | ||
| "math" | ||
| "math/rand" | ||
| "math/big" | ||
| "net/http" | ||
| "strconv" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "arguehub/db" | ||
|
|
@@ -20,10 +23,14 @@ import ( | |
|
|
||
| // Room represents a debate room. | ||
| type Room struct { | ||
| ID string `json:"id" bson:"_id"` | ||
| Type string `json:"type" bson:"type"` | ||
| OwnerID string `json:"ownerId" bson:"ownerId"` | ||
| Participants []Participant `json:"participants" bson:"participants"` | ||
| ID string `json:"id" bson:"_id"` | ||
| Type string `json:"type" bson:"type"` | ||
| OwnerID string `json:"ownerId" bson:"ownerId"` | ||
| Participants []Participant `json:"participants" bson:"participants"` | ||
| InviteToken string `json:"inviteToken,omitempty" bson:"inviteToken,omitempty"` | ||
| Topic string `json:"topic,omitempty" bson:"topic,omitempty"` | ||
| InvitedUsername string `json:"invitedUsername,omitempty" bson:"invitedUsername,omitempty"` | ||
| RematchOfRoomID string `json:"rematchOfRoomId,omitempty" bson:"rematchOfRoomId,omitempty"` | ||
| } | ||
|
|
||
| // Participant represents a user in a room. | ||
|
|
@@ -37,8 +44,44 @@ type Participant struct { | |
|
|
||
| // generateRoomID creates a random six-digit room ID as a string. | ||
| func generateRoomID() string { | ||
| rand.Seed(time.Now().UnixNano()) | ||
| return strconv.Itoa(rand.Intn(900000) + 100000) | ||
| n, err := rand.Int(rand.Reader, big.NewInt(900000)) | ||
| if err != nil { | ||
| return strconv.FormatInt(time.Now().UnixNano()%900000+100000, 10) | ||
| } | ||
| return strconv.Itoa(int(n.Int64()) + 100000) | ||
| } | ||
|
|
||
| func generateInviteToken() string { | ||
| b := make([]byte, 16) | ||
| if _, err := rand.Read(b); err != nil { | ||
| return strconv.FormatInt(time.Now().UnixNano(), 36) | ||
| } | ||
| return hex.EncodeToString(b) | ||
| } | ||
|
|
||
| type roomUser struct { | ||
| ID primitive.ObjectID `bson:"_id"` | ||
| Email string `bson:"email"` | ||
| DisplayName string `bson:"displayName"` | ||
| Rating float64 `bson:"rating"` | ||
| AvatarURL string `bson:"avatarUrl"` | ||
| } | ||
|
|
||
| func fetchUserByEmail(ctx context.Context, email string) (roomUser, error) { | ||
| userCollection := db.MongoDatabase.Collection("users") | ||
| var user roomUser | ||
| err := userCollection.FindOne(ctx, bson.M{"email": email}).Decode(&user) | ||
| return user, err | ||
| } | ||
|
|
||
| func userToParticipant(user roomUser) Participant { | ||
| return Participant{ | ||
| ID: user.ID.Hex(), | ||
| Username: user.DisplayName, | ||
| Elo: int(math.Round(user.Rating)), | ||
| AvatarURL: user.AvatarURL, | ||
| Email: user.Email, | ||
| } | ||
| } | ||
|
|
||
| // CreateRoomHandler handles POST /rooms and creates a new debate room. | ||
|
|
@@ -127,7 +170,7 @@ func GetRoomsHandler(c *gin.Context) { | |
| ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | ||
| defer cancel() | ||
|
|
||
| cursor, err := collection.Find(ctx, bson.D{}) | ||
| cursor, err := collection.Find(ctx, bson.M{"type": bson.M{"$ne": "invite"}}) | ||
| if err != nil { | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Error fetching rooms"}) | ||
| return | ||
|
|
@@ -146,7 +189,12 @@ func GetRoomsHandler(c *gin.Context) { | |
| func JoinRoomHandler(c *gin.Context) { | ||
| roomId := c.Param("id") | ||
|
|
||
| // Get user email from middleware-set context | ||
| type JoinRoomInput struct { | ||
| InviteToken string `json:"inviteToken"` | ||
| } | ||
| var input JoinRoomInput | ||
| _ = c.ShouldBindJSON(&input) | ||
|
|
||
| email, exists := c.Get("email") | ||
| if !exists { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: user email not found"}) | ||
|
|
@@ -158,37 +206,87 @@ func JoinRoomHandler(c *gin.Context) { | |
| ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | ||
| defer cancel() | ||
|
|
||
|
|
||
| emailStr, ok := email.(string) | ||
| if !ok { | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid email format"}) | ||
| return | ||
| } | ||
|
|
||
| var user struct { | ||
| ID primitive.ObjectID `bson:"_id"` | ||
| Email string `bson:"email"` | ||
| DisplayName string `bson:"displayName"` | ||
| Rating float64 `bson:"rating"` | ||
| AvatarURL string `bson:"avatarUrl"` | ||
| } | ||
| ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | ||
| defer cancel() | ||
|
|
||
| err := userCollection.FindOne(ctx, bson.M{"email": emailStr}).Decode(&user) | ||
| user, err := fetchUserByEmail(ctx, emailStr) | ||
| if err != nil { | ||
| c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) | ||
| return | ||
| } | ||
|
|
||
| // Create participant | ||
| participant := Participant{ | ||
| ID: user.ID.Hex(), | ||
| Username: user.DisplayName, | ||
| Elo: int(math.Round(user.Rating)), | ||
| AvatarURL: user.AvatarURL, | ||
| Email: user.Email, | ||
| participant := userToParticipant(user) | ||
|
|
||
| roomCollection := db.MongoDatabase.Collection("rooms") | ||
| var room Room | ||
| if err := roomCollection.FindOne(ctx, bson.M{"_id": roomId}).Decode(&room); err != nil { | ||
| c.JSON(http.StatusNotFound, gin.H{"error": "Room not found"}) | ||
| return | ||
| } | ||
|
|
||
| alreadyIn := false | ||
| for _, p := range room.Participants { | ||
| if p.ID == participant.ID { | ||
| alreadyIn = true | ||
| break | ||
| } | ||
| } | ||
|
|
||
| if room.InviteToken != "" && !alreadyIn { | ||
| if input.InviteToken == "" || input.InviteToken != room.InviteToken { | ||
| c.JSON(http.StatusForbidden, gin.H{"error": "Invalid invite token"}) | ||
| return | ||
| } | ||
| if room.InvitedUsername != "" && !strings.EqualFold(strings.TrimSpace(user.DisplayName), room.InvitedUsername) { | ||
| c.JSON(http.StatusForbidden, gin.H{"error": "This challenge was sent to another user"}) | ||
| return | ||
| } | ||
|
|
||
| filter := bson.M{ | ||
| "_id": roomId, | ||
| "inviteToken": input.InviteToken, | ||
| "$expr": bson.M{ | ||
| "$lt": []interface{}{bson.M{"$size": "$participants"}, 2}, | ||
| }, | ||
| } | ||
| update := bson.M{ | ||
| "$addToSet": bson.M{"participants": participant}, | ||
| } | ||
| opts := options.FindOneAndUpdate().SetReturnDocument(options.After) | ||
|
|
||
| var updatedRoom Room | ||
| if err := roomCollection.FindOneAndUpdate(ctx, filter, update, opts).Decode(&updatedRoom); err != nil { | ||
| if err == mongo.ErrNoDocuments { | ||
| c.JSON(http.StatusConflict, gin.H{"error": "Room is full"}) | ||
| return | ||
| } | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not join room"}) | ||
| return | ||
| } | ||
|
|
||
| matchmakingService := services.GetMatchmakingService() | ||
| matchmakingService.RemoveFromPool(user.ID.Hex()) | ||
|
|
||
| c.JSON(http.StatusOK, updatedRoom) | ||
| return | ||
| } | ||
|
|
||
| if alreadyIn { | ||
| c.JSON(http.StatusOK, room) | ||
| return | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| // Use atomic operation to join room | ||
| roomCollection := db.MongoDatabase.Collection("rooms") | ||
|
|
||
| filter := bson.M{"_id": roomId} | ||
| update := mongo.Pipeline{ | ||
| bson.D{{Key: "$set", Value: bson.D{ | ||
|
|
@@ -218,7 +316,6 @@ func JoinRoomHandler(c *gin.Context) { | |
| return | ||
| } | ||
|
|
||
| // Remove user from matchmaking pool if they were in it | ||
| matchmakingService := services.GetMatchmakingService() | ||
| matchmakingService.RemoveFromPool(user.ID.Hex()) | ||
|
|
||
|
|
@@ -357,3 +454,153 @@ func GetRoomParticipantsHandler(c *gin.Context) { | |
| "participants": participantsWithDetails, | ||
| }) | ||
| } | ||
|
|
||
| // CreateChallengeHandler handles POST /rooms/challenge. | ||
| func CreateChallengeHandler(c *gin.Context) { | ||
| type CreateChallengeInput struct { | ||
| OpponentUsername string `json:"opponentUsername"` | ||
| Topic string `json:"topic"` | ||
| } | ||
|
|
||
| var input CreateChallengeInput | ||
| if err := c.ShouldBindJSON(&input); err != nil || strings.TrimSpace(input.Topic) == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": "Topic is required"}) | ||
| return | ||
| } | ||
|
|
||
| email, exists := c.Get("email") | ||
| if !exists { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: user email not found"}) | ||
| return | ||
| } | ||
|
|
||
| emailStr, ok := email.(string) | ||
| if !ok { | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid email format"}) | ||
| return | ||
| } | ||
|
|
||
| ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | ||
| defer cancel() | ||
|
|
||
| user, err := fetchUserByEmail(ctx, emailStr) | ||
| if err != nil { | ||
| c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) | ||
| return | ||
| } | ||
|
|
||
| opponentUsername := strings.TrimSpace(input.OpponentUsername) | ||
| if opponentUsername != "" { | ||
| if strings.EqualFold(opponentUsername, strings.TrimSpace(user.DisplayName)) { | ||
| opponentUsername = "" | ||
| } else { | ||
| userCollection := db.MongoDatabase.Collection("users") | ||
| var opponent roomUser | ||
| if err := userCollection.FindOne(ctx, bson.M{"displayName": opponentUsername}).Decode(&opponent); err != nil { | ||
| c.JSON(http.StatusNotFound, gin.H{"error": "Opponent not found. Leave blank to share link with anyone."}) | ||
| return | ||
| } | ||
| if opponent.ID == user.ID { | ||
| opponentUsername = "" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| creatorParticipant := userToParticipant(user) | ||
| inviteToken := generateInviteToken() | ||
| roomID := generateRoomID() | ||
|
|
||
| newRoom := Room{ | ||
| ID: roomID, | ||
| Type: "invite", | ||
| OwnerID: creatorParticipant.ID, | ||
| Participants: []Participant{creatorParticipant}, | ||
| InviteToken: inviteToken, | ||
| Topic: strings.TrimSpace(input.Topic), | ||
| InvitedUsername: opponentUsername, | ||
| } | ||
|
|
||
| roomCollection := db.MongoDatabase.Collection("rooms") | ||
| if _, err := roomCollection.InsertOne(ctx, newRoom); err != nil { | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create challenge room"}) | ||
| return | ||
| } | ||
|
|
||
| c.JSON(http.StatusOK, newRoom) | ||
| } | ||
|
|
||
| // RematchHandler handles POST /rooms/:id/rematch. | ||
| func RematchHandler(c *gin.Context) { | ||
| roomId := c.Param("id") | ||
|
|
||
| email, exists := c.Get("email") | ||
| if !exists { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: user email not found"}) | ||
| return | ||
| } | ||
|
|
||
| emailStr, ok := email.(string) | ||
| if !ok { | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid email format"}) | ||
| return | ||
| } | ||
|
|
||
| ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | ||
| defer cancel() | ||
|
|
||
| user, err := fetchUserByEmail(ctx, emailStr) | ||
| if err != nil { | ||
| c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) | ||
| return | ||
| } | ||
|
|
||
| roomCollection := db.MongoDatabase.Collection("rooms") | ||
| var room Room | ||
| if err := roomCollection.FindOne(ctx, bson.M{"_id": roomId}).Decode(&room); err != nil { | ||
| c.JSON(http.StatusNotFound, gin.H{"error": "Room not found"}) | ||
| return | ||
| } | ||
|
|
||
| if room.InviteToken == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": "Rematch is only available for challenge rooms"}) | ||
| return | ||
| } | ||
|
|
||
| wasParticipant := false | ||
| for _, p := range room.Participants { | ||
| if p.ID == user.ID.Hex() { | ||
| wasParticipant = true | ||
| break | ||
| } | ||
| } | ||
| if !wasParticipant { | ||
| c.JSON(http.StatusForbidden, gin.H{"error": "You were not in this challenge"}) | ||
| return | ||
| } | ||
|
|
||
| var existingRematch Room | ||
| if err := roomCollection.FindOne(ctx, bson.M{"rematchOfRoomId": roomId}).Decode(&existingRematch); err == nil { | ||
| c.JSON(http.StatusOK, existingRematch) | ||
| return | ||
| } | ||
|
Comment on lines
+581
to
+585
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Two players clicking Rematch together can end up in different rooms.
Add a unique sparse index on
|
||
|
|
||
| rematchParticipants := make([]Participant, len(room.Participants)) | ||
| copy(rematchParticipants, room.Participants) | ||
|
|
||
| newRoom := Room{ | ||
| ID: generateRoomID(), | ||
| Type: "invite", | ||
| OwnerID: user.ID.Hex(), | ||
| Participants: rematchParticipants, | ||
| InviteToken: generateInviteToken(), | ||
| Topic: room.Topic, | ||
| RematchOfRoomID: roomId, | ||
| } | ||
|
|
||
| if _, err := roomCollection.InsertOne(ctx, newRoom); err != nil { | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create rematch room"}) | ||
| return | ||
| } | ||
|
|
||
| c.JSON(http.StatusOK, newRoom) | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.