diff --git a/internal/backend.go b/internal/backend.go index 5db6f7b..fe020f0 100644 --- a/internal/backend.go +++ b/internal/backend.go @@ -47,4 +47,5 @@ type User interface { SetRoomVisibility(Room, createroom.VisibilityType) *models.ApiError Logout(token string) LogoutAll() + JoinRoom(Room) *models.ApiError } diff --git a/internal/backends/memory/backend_test.go b/internal/backends/memory/backend_test.go index 31d08f4..c24877c 100644 --- a/internal/backends/memory/backend_test.go +++ b/internal/backends/memory/backend_test.go @@ -136,3 +136,44 @@ func TestGetUserByName(t *testing.T) { assert.Nil(t, user2) }) } + +func TestPublicRooms(t *testing.T) { + backend := NewBackend("localhost") + + user1, _, err := backend.Register("user1", "", "") + assert.Nil(t, err) + assert.NotNil(t, user1) + + // Create first room + request := createroom.Request{ + RoomAliasName: "room1", + Name: "room1", + Preset: createroom.PublicChat} + + room1, err := user1.CreateRoom(request) + assert.Nil(t, err) + assert.NotNil(t, room1) + + // Create second room + request = createroom.Request{ + RoomAliasName: "room2", + Name: "room2", + Preset: createroom.PublicChat} + + room2, err := user1.CreateRoom(request) + assert.Nil(t, err) + assert.NotNil(t, room2) + + // Make room2 has 2 users + user2, _, err := backend.Register("user2", "", "") + assert.Nil(t, err) + assert.NotNil(t, user2) + + err = user2.JoinRoom(room2) + assert.Nil(t, err) + + rooms := backend.PublicRooms() + assert.Len(t, rooms, 2) + assert.Equal(t, rooms[0], room2) + assert.Equal(t, rooms[1], room1) +} diff --git a/internal/backends/memory/user.go b/internal/backends/memory/user.go index 76b95f4..221e0ad 100644 --- a/internal/backends/memory/user.go +++ b/internal/backends/memory/user.go @@ -222,3 +222,20 @@ func (user *User) Logout(token string) { func (user *User) LogoutAll() { user.Tokens = make(map[string]Token) } + +func (user *User) JoinRoom(room internal.Room) *models.ApiError { + memRoom := room.(*Room) + + memRoom.mutex.Lock() + defer memRoom.mutex.Unlock() + + for _, roomUser := range memRoom.joined { + if roomUser.ID() == user.ID() { + return internal.NewError(models.M_BAD_STATE, "user already in room") // TODO: check code + } + } + + memRoom.joined = append(memRoom.joined, user) + + return nil +}