From 32937adc8047a47f45c0f787d8a468bc7056c730 Mon Sep 17 00:00:00 2001 From: nxshock Date: Mon, 22 Jul 2019 18:58:18 +0500 Subject: [PATCH] Add leave room method --- internal/backend.go | 1 + internal/backends/memory/rooms_test.go | 22 ++++++++++++++++++++++ internal/backends/memory/user.go | 14 ++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/internal/backend.go b/internal/backend.go index a4726e1..89c4b2a 100644 --- a/internal/backend.go +++ b/internal/backend.go @@ -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 } diff --git a/internal/backends/memory/rooms_test.go b/internal/backends/memory/rooms_test.go index d9f5885..0d3543e 100644 --- a/internal/backends/memory/rooms_test.go +++ b/internal/backends/memory/rooms_test.go @@ -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) +} diff --git a/internal/backends/memory/user.go b/internal/backends/memory/user.go index eb0e39c..c276fd8 100644 --- a/internal/backends/memory/user.go +++ b/internal/backends/memory/user.go @@ -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 +}