Add create room method plus some rework of backend

This commit is contained in:
nxshock 2019-07-21 14:43:14 +05:00
parent 4394856f24
commit 2919be97bf
11 changed files with 330 additions and 144 deletions

View File

@ -14,7 +14,7 @@ var (
func init() { func init() {
server = internal.New() server = internal.New()
server.Address = "localhost" server.Address = "localhost"
server.Backend = memory.NewBackend() server.Backend = memory.NewBackend(server.Address)
server.Backend.Register("andrew", "1", "") server.Backend.Register("andrew", "1", "")
} }

View File

@ -2,12 +2,31 @@ package internal
import ( import (
"github.com/nxshock/signaller/internal/models" "github.com/nxshock/signaller/internal/models"
"github.com/nxshock/signaller/internal/models/createroom"
"github.com/nxshock/signaller/internal/models/rooms"
"github.com/nxshock/signaller/internal/models/sync" "github.com/nxshock/signaller/internal/models/sync"
) )
type Backend interface { type Backend interface {
Register(username, password, device string) (token string, error *models.ApiError) Register(username, password, device string) (user User, token string, err *models.ApiError)
Login(username, password, device string) (token string, err *models.ApiError) Login(username, password, device string) (token string, err *models.ApiError)
Logout(token string) *models.ApiError Logout(token string) *models.ApiError
CreateRoom(user User, request createroom.Request) (Room, *models.ApiError)
Sync(token string, request sync.SyncRequest) (response *sync.SyncReply, err *models.ApiError) Sync(token string, request sync.SyncRequest) (response *sync.SyncReply, err *models.ApiError)
} }
type Room interface {
ID() string
Creator() User
Users() User
AliasName() string
Name() string
Topic() string
Events() []rooms.Event
}
type User interface {
Name() string
ID() string
Password() string
}

View File

@ -0,0 +1,113 @@
package memory
import (
"sync"
"github.com/nxshock/signaller/internal"
"github.com/nxshock/signaller/internal/models"
"github.com/nxshock/signaller/internal/models/createroom"
mSync "github.com/nxshock/signaller/internal/models/sync"
)
type Backend struct {
data map[string]internal.User
rooms map[string]internal.Room
hostname string
mutex sync.Mutex // TODO: replace with RW mutex
}
type Token struct {
Device string
}
func NewBackend(hostname string) *Backend {
return &Backend{
hostname: hostname,
rooms: make(map[string]internal.Room),
data: make(map[string]internal.User)}
}
func (backend *Backend) Register(username, password, device string) (user internal.User, token string, err *models.ApiError) {
backend.mutex.Lock()
defer backend.mutex.Unlock()
if _, ok := backend.data[username]; ok {
return nil, "", internal.NewError(models.M_USER_IN_USE, "trying to register a user ID which has been taken")
}
token = internal.NewToken(internal.DefaultTokenSize)
user = &User{
name: username,
password: password,
Tokens: map[string]Token{
token: {
Device: device}},
backend: backend}
backend.data[username] = user
return user, token, nil
}
func (backend *Backend) Login(username, password, device string) (token string, err *models.ApiError) {
backend.mutex.Lock()
defer backend.mutex.Unlock()
user, ok := backend.data[username]
if !ok {
return "", internal.NewError(models.M_FORBIDDEN, "wrong username")
}
if user.Password() != password {
return "", internal.NewError(models.M_FORBIDDEN, "wrong password")
}
token = internal.NewToken(internal.DefaultTokenSize)
backend.data[username].(*User).Tokens[token] = Token{Device: device}
return token, nil
}
func (backend *Backend) Logout(token string) *models.ApiError {
backend.mutex.Lock()
defer backend.mutex.Unlock()
for _, user := range backend.data {
for userToken, _ := range user.(*User).Tokens {
if userToken == token {
delete(user.(*User).Tokens, token)
return nil
}
}
}
return internal.NewError(models.M_UNKNOWN_TOKEN, "unknown token") // TODO: create error struct
}
func (backend *Backend) Sync(token string, request mSync.SyncRequest) (response *mSync.SyncReply, err *models.ApiError) {
backend.mutex.Lock()
defer backend.mutex.Unlock()
return nil, nil // TODO: implement
}
func (backend *Backend) CreateRoom(user internal.User, request createroom.Request) (internal.Room, *models.ApiError) {
for _, existingRoom := range backend.rooms {
if existingRoom.AliasName() == request.RoomAliasName { // TODO: strip and check request room alias name before use
return nil, internal.NewError(models.M_ROOM_IN_USE, "")
}
}
room := &Room{
id: internal.NewToken(groupIDSize),
aliasName: request.RoomAliasName,
name: request.Name,
topic: request.Topic,
creator: user}
backend.rooms[room.id] = room
return room, nil
}

View File

@ -0,0 +1,3 @@
package memory
const groupIDSize = 16

View File

@ -1,124 +0,0 @@
package memory
import (
"encoding/json"
"log"
"os"
"sync"
"github.com/nxshock/signaller/internal"
"github.com/nxshock/signaller/internal/models"
"github.com/nxshock/signaller/internal/models/common"
mSync "github.com/nxshock/signaller/internal/models/sync"
)
var first bool
type Backend struct {
data map[string]*User
mutex sync.Mutex // TODO: replace with RW mutex
}
type User struct {
Password string
Tokens map[string]Token
}
type Token struct {
Device string
}
func NewBackend() *Backend {
return &Backend{data: make(map[string]*User)}
}
func (backend Backend) Register(username, password, device string) (token string, err *models.ApiError) {
backend.mutex.Lock()
defer backend.mutex.Unlock()
if _, ok := backend.data[username]; ok {
return "", internal.NewError(models.M_USER_IN_USE, "trying to register a user ID which has been taken")
}
token = internal.NewToken(internal.DefaultTokenSize)
backend.data[username] = &User{
Password: password,
Tokens: map[string]Token{
token: {
Device: device}}}
return token, nil
}
func (backend Backend) Login(username, password, device string) (token string, err *models.ApiError) {
backend.mutex.Lock()
defer backend.mutex.Unlock()
user, ok := backend.data[username]
if !ok {
return "", internal.NewError(models.M_FORBIDDEN, "wrong username")
}
if user.Password != password {
return "", internal.NewError(models.M_FORBIDDEN, "wrong password")
}
token = internal.NewToken(internal.DefaultTokenSize)
backend.data[username].Tokens[token] = Token{Device: device}
return token, nil
}
func (backend Backend) Logout(token string) *models.ApiError {
backend.mutex.Lock()
defer backend.mutex.Unlock()
for _, user := range backend.data {
for userToken, _ := range user.Tokens {
if userToken == token {
delete(user.Tokens, token)
return nil
}
}
}
return internal.NewError(models.M_UNKNOWN_TOKEN, "unknown token") // TODO: create error struct
}
func (backend Backend) Sync(token string, request mSync.SyncRequest) (response *mSync.SyncReply, err *models.ApiError) {
backend.mutex.Lock()
defer backend.mutex.Unlock()
log.Println(request)
if !first {
log.Println(1)
response = &mSync.SyncReply{
AccountData: common.AccountData{
Events: []common.Event{
common.Event{Type: "m.direct", Content: json.RawMessage(`"@vasyo2:localhost":"!room1:localhost"`)},
}},
Rooms: mSync.RoomsSyncReply{
Join: map[string]common.JoinedRoom{
"!room1:localhost": common.JoinedRoom{
Timeline: common.Timeline{
Events: []common.RoomEvent{
common.RoomEvent{Type: "m.room.create", Sender: "@vasyo2:localhost"},
common.RoomEvent{Type: "m.room.member", Sender: "@vasyo2:localhost", Content: json.RawMessage(`membership:"join",displayname:"vasyo2"`)},
}}}}}}
/* InviteState: models.InviteState{
Events: []models.StrippedState{
models.StrippedState{Type: "m.room.join_rules", Content: json.RawMessage(`join_rule:"invite"`), Sender: "@vasyo2:" + server.Address},
models.StrippedState{Type: "m.room.member", Content: json.RawMessage(`membership:"join",displayname:"vasyo2"`), Sender: "@vasyo2:" + server.Address},
models.StrippedState{Type: "m.room.member", Content: json.RawMessage(`is_direct:"true",membership:"invite",displayname:"vasyo"`), Sender: "@vasyo2:" + server.Address},
}}}}}}*/
first = true
} else {
os.Exit(0)
response = &mSync.SyncReply{}
}
return response, nil // TODO: implement
}

View File

@ -0,0 +1,79 @@
package memory
import (
"sync"
"github.com/nxshock/signaller/internal"
"github.com/nxshock/signaller/internal/models/createroom"
"github.com/nxshock/signaller/internal/models/rooms"
)
type Room struct {
id string
Visibility createroom.VisibilityType
aliasName string
name string
topic string
creator internal.User
events []rooms.Event
mutex sync.RWMutex
}
func (room *Room) ID() string {
room.mutex.RLock()
defer room.mutex.RUnlock()
return room.id
}
func (room *Room) Name() string {
room.mutex.RLock()
defer room.mutex.RUnlock()
return room.name
}
func (room *Room) AliasName() string {
room.mutex.RLock()
defer room.mutex.RUnlock()
return room.aliasName
}
func (room *Room) Topic() string {
room.mutex.RLock()
defer room.mutex.RUnlock()
return room.topic
}
func (room *Room) Users() internal.User {
room.mutex.RLock()
defer room.mutex.RUnlock()
return nil // TODO: implement
}
func (room *Room) Events() []rooms.Event {
room.mutex.RLock()
defer room.mutex.RUnlock()
return room.events
}
func (room *Room) Creator() internal.User {
room.mutex.RLock()
defer room.mutex.RUnlock()
return room.creator
}
func (room *Room) NewEvent(event rooms.Event) {
room.mutex.Lock()
defer room.mutex.Unlock()
room.events = append(room.events, event)
}

View File

@ -0,0 +1,64 @@
package memory
import (
"strings"
"testing"
"github.com/nxshock/signaller/internal/models/createroom"
"github.com/stretchr/testify/assert"
)
func TestRegisterUser(t *testing.T) {
backend := NewBackend("localhost")
var (
username = "user1"
password = "password1"
device = "device1"
)
user, token, err := backend.Register(username, password, device)
assert.Nil(t, err)
assert.Equal(t, username, user.Name())
assert.Equal(t, password, user.Password())
assert.NotEmpty(t, token)
assert.True(t, strings.HasSuffix(user.ID(), backend.hostname))
}
func TestCreateRoom(t *testing.T) {
backend := NewBackend("localhost")
user, _, err := backend.Register("user1", "", "")
assert.Nil(t, err)
request := createroom.Request{
RoomAliasName: "room1",
Name: "room1",
Topic: "topic"}
room, err := backend.CreateRoom(user, request)
assert.Nil(t, err)
assert.Equal(t, request.RoomAliasName, room.AliasName())
assert.Equal(t, request.Name, room.Name())
assert.Equal(t, request.Topic, room.Topic())
assert.Equal(t, user.ID(), room.Creator().ID())
assert.Equal(t, 1, len(backend.rooms))
}
func TestCreateAlreadyExistingRoom(t *testing.T) {
backend := NewBackend("localhost")
user, _, _ := backend.Register("user1", "", "")
request := createroom.Request{
RoomAliasName: "room1",
Name: "room1",
Topic: "topic"}
_, err := backend.CreateRoom(user, request)
assert.Nil(t, err)
_, err = backend.CreateRoom(user, request)
assert.NotNil(t, err)
}

View File

@ -0,0 +1,22 @@
package memory
type User struct {
id string
name string
password string
Tokens map[string]Token
backend *Backend
}
func (user *User) ID() string {
return "@" + user.id + ":" + user.backend.hostname
}
func (user *User) Name() string {
return user.name
}
func (user *User) Password() string {
return user.password
}

View File

@ -112,7 +112,7 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
var request register.RegisterRequest var request register.RegisterRequest
getRequest(r, &request) // TODO: handle error getRequest(r, &request) // TODO: handle error
token, apiErr := currServer.Backend.Register(request.Username, request.Password, request.DeviceID) _, token, apiErr := currServer.Backend.Register(request.Username, request.Password, request.DeviceID)
if apiErr != nil { if apiErr != nil {
errorResponse(w, *apiErr, http.StatusBadRequest, "") errorResponse(w, *apiErr, http.StatusBadRequest, "")
return return

View File

@ -1,5 +1,6 @@
package createroom package createroom
type CreateRoomReply struct { // https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom
type Reply struct {
RoomID string `json:"room_id"` RoomID string `json:"room_id"`
} }

View File

@ -4,35 +4,44 @@ import (
common "github.com/nxshock/signaller/internal/models/common" common "github.com/nxshock/signaller/internal/models/common"
) )
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom
type VisibilityType string type VisibilityType string
const ( const (
VisibilityTypePrivate = "private" VisibilityTypePrivate VisibilityType = "private"
VisibilityTypePublic = "public" VisibilityTypePublic = "public"
)
type Preset string
const (
PrivateChat Preset = "private_chat"
PublicChat = "public_chat"
TrustedPrivateChat = "trusted_private_chat"
) )
// Invite3pid represents third party IDs to invite into the room // Invite3pid represents third party IDs to invite into the room
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-createroom // https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom
type Invite3pid struct { type Invite3pid struct {
IDServer string `json:"id_server"` // Required. The hostname+port of the identity server which should be used for third party identifier lookups. IDServer string `json:"id_server"` // Required. The hostname+port of the identity server which should be used for third party identifier lookups.
Medium string `json:"medium"` // Required. The kind of address being passed in the address field, for example email. Medium string `json:"medium"` // Required. The kind of address being passed in the address field, for example email.
Address string `json:"address"` // Required. The invitee's third party identifier. Address string `json:"address"` // Required. The invitee's third party identifier.
} }
// CreateRoomRequest represents room creation request // Request is room creation request
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-createroom // https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom
type CreateRoomRequest struct { type Request struct {
Visibility VisibilityType `json:"visibility,omitempty"` Visibility VisibilityType `json:"visibility,omitempty"` // A public visibility indicates that the room will be shown in the published room list. A private visibility will hide the room from the published room list. Rooms default to private visibility if this key is not included. NB: This should not be confused with join_rules which also uses the word public. One of: ["public", "private"]
RoomAliasName string `json:"room_alias_name,omitempty"` RoomAliasName string `json:"room_alias_name,omitempty"` // The desired room alias local part. If this is included, a room alias will be created and mapped to the newly created room. The alias will belong on the same homeserver which created the room. For example, if this was set to "foo" and sent to the homeserver "example.com" the complete room alias would be #foo:example.com.
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"` // If this is included, an m.room.name event will be sent into the room to indicate the name of the room. See Room Events for more information on m.room.name.
Topic string `json:"topic,omitempty"` Topic string `json:"topic,omitempty"` // If this is included, an m.room.topic event will be sent into the room to indicate the topic for the room. See Room Events for more information on m.room.topic.
Invite []string `json:"invite,omitempty"` Invite []string `json:"invite,omitempty"` // A list of user IDs to invite to the room. This will tell the server to invite everyone in the list to the newly created room.
Invite3pids []Invite3pid `json:"invite_3pid,omitempty"` Invite3pids []Invite3pid `json:"invite_3pid,omitempty"` // A list of objects representing third party IDs to invite into the room.
RoomVersion string `json:"room_version,omitempty"` RoomVersion string `json:"room_version,omitempty"` // The room version to set for the room. If not provided, the homeserver is to use its configured default. If provided, the homeserver will return a 400 error with the errcode M_UNSUPPORTED_ROOM_VERSION if it does not support the room version.
// TODO: проверить тип // TODO: проверить тип
// CreationContent CreationContentType `json:"creation_content,omitempty"` // CreationContent CreationContentType `json:"creation_content,omitempty"`
InitialState []common.StateEvent `json:"initial_state,omitempty"` InitialState []common.StateEvent `json:"initial_state,omitempty"` // A list of state events to set in the new room. This allows the user to override the default state events set in the new room. The expected format of the state events are an object with type, state_key and content keys set. Takes precedence over events set by preset, but gets overriden by name and topic keys.
Preset string `json:"preset,omitempty"` // TODO: проверить тип Preset Preset `json:"preset,omitempty"` // Convenience parameter for setting various default state events based on a preset. If unspecified, the server should use the visibility to determine which preset to use. A visbility of public equates to a preset of public_chat and private visibility equates to a preset of private_chat. One of: ["private_chat", "public_chat", "trusted_private_chat"]
IsDirect bool `json:"is_direct,omitempty"` IsDirect bool `json:"is_direct,omitempty"` // This flag makes the server set the is_direct flag on the m.room.member events sent to the users in invite and invite_3pid.
// PowerLevelContentOverride `json:"power_level_content_override"` // PowerLevelContentOverride `json:"power_level_content_override"`
} }