Add leave room method

This commit is contained in:
nxshock 2019-07-22 18:58:18 +05:00
parent c179fdc4b6
commit 32937adc80
3 changed files with 37 additions and 0 deletions

View File

@ -29,5 +29,6 @@ type User interface {
ID() string
Password() string
CreateRoom(request createroom.Request) (Room, *models.ApiError)
LeaveRoom(room Room) *models.ApiError
SetTopic(room Room, topic string) *models.ApiError
}

View File

@ -99,3 +99,25 @@ func TestSetRoomTopicWithnprivelegedUser(t *testing.T) {
err := user2.SetTopic(room, newTopic)
assert.NotNil(t, err)
}
func TestLeaveRoom(t *testing.T) {
backend := NewBackend("localhost")
user, _, _ := backend.Register("user1", "", "")
request := createroom.Request{
RoomAliasName: "room1",
Name: "room1",
Topic: "topic"}
room, _ := user.CreateRoom(request)
assert.Equal(t, 1, len(room.(*Room).joined))
err := user.LeaveRoom(room)
assert.Equal(t, 0, len(room.(*Room).joined))
// Try to leave room again must throw error
err = user.LeaveRoom(room)
assert.NotNil(t, err)
}

View File

@ -114,3 +114,17 @@ func (user *User) SetTopic(room internal.Room, topic string) *models.ApiError {
return nil
}
func (user *User) LeaveRoom(room internal.Room) *models.ApiError {
room.(*Room).mutex.Lock()
defer room.(*Room).mutex.Unlock()
for i, roomMember := range room.(*Room).joined {
if roomMember.ID() == user.ID() {
room.(*Room).joined = append(room.(*Room).joined[:i], room.(*Room).joined[i+1:]...)
return nil
}
}
return internal.NewError(models.M_BAD_STATE, "you are not a member of group") // TODO: check error code
}