Add send message event to memry backend

This commit is contained in:
nxshock 2019-07-23 19:24:18 +05:00
parent 38f9c25b1b
commit a1717ec784
3 changed files with 66 additions and 0 deletions

View File

@ -31,4 +31,5 @@ type User interface {
CreateRoom(request createroom.Request) (Room, *models.ApiError)
LeaveRoom(room Room) *models.ApiError
SetTopic(room Room, topic string) *models.ApiError
SendMessage(room Room, text string) *models.ApiError
}

View File

@ -128,3 +128,29 @@ func (user *User) LeaveRoom(room internal.Room) *models.ApiError {
return internal.NewError(models.M_BAD_STATE, "you are not a member of group") // TODO: check error code
}
func (user *User) SendMessage(room internal.Room, text string) *models.ApiError {
room.(*Room).mutex.Lock()
defer room.(*Room).mutex.Unlock()
userInRoom := false
for _, roomMember := range room.(*Room).joined {
if roomMember.ID() == user.ID() {
userInRoom = true
}
}
if !userInRoom {
return internal.NewError(models.M_FORBIDDEN, "")
}
room.(*Room).events = append(room.(*Room).events, RoomEvent{
Content: nil,
Type: rooms.Message,
EventID: newToken(defaultTokenSize),
Sender: user,
OriginServerTS: time.Now(),
Room: room})
return nil
}

View File

@ -4,6 +4,8 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/nxshock/signaller/internal/models/createroom"
)
func TestUserID(t *testing.T) {
@ -19,3 +21,40 @@ func TestUserID(t *testing.T) {
assert.Equal(t, expectedUserID, user.ID())
}
func TestUserMessage(t *testing.T) {
backend := NewBackend("localhost")
user, _, err := backend.Register("user1", "", "")
assert.Nil(t, err)
request := createroom.Request{
RoomAliasName: "room1",
Name: "room1"}
room, err := user.CreateRoom(request)
assert.Nil(t, err)
err = user.SendMessage(room, "hello")
assert.Nil(t, err)
}
func TestUserMessageInWrongRoom(t *testing.T) {
backend := NewBackend("localhost")
user1, _, err := backend.Register("user1", "", "")
assert.Nil(t, err)
request := createroom.Request{
RoomAliasName: "room1",
Name: "room1"}
room, err := user1.CreateRoom(request)
assert.Nil(t, err)
user2, _, err := backend.Register("user2", "", "")
assert.Nil(t, err)
err = user2.SendMessage(room, "hello")
assert.NotNil(t, err)
}