This commit is contained in:
Hoernschen 2020-10-12 16:16:28 +02:00
parent 9eac960763
commit da9196f389
22 changed files with 302 additions and 76 deletions

View file

@ -1,6 +1,6 @@
package device
import "nutfactory.org/Matrix/utils"
import "git.nutfactory.org/hoernschen/Matrix/utils"
func New(name string) (err error, device *Device) {
err, id := utils.CreateUUID()

View file

@ -4,7 +4,7 @@ import (
"fmt"
"log"
"nutfactory.org/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateDevice(device *Device, userId string) (err error) {

View file

@ -5,8 +5,8 @@ import (
"fmt"
"net/http"
"nutfactory.org/Matrix/config"
"nutfactory.org/Matrix/utils"
"git.nutfactory.org/hoernschen/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/utils"
)
func InitServerSigningKey() (err error) {
@ -50,6 +50,7 @@ func GetServerSigningKeyHandler(w http.ResponseWriter, r *http.Request) {
}
}
// TODO: Use Function
func getVerifyKey(server string, id string) (key []byte, err error) {
if val, ok := config.VerifyKeys[server][id]; ok {
key = val

View file

@ -3,7 +3,7 @@ package device
import (
"fmt"
"nutfactory.org/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateKey(key *Key, deviceId string) (err error) {

View file

@ -9,12 +9,12 @@ import (
"strconv"
"time"
"git.nutfactory.org/hoernschen/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/entities/device"
"git.nutfactory.org/hoernschen/Matrix/entities/user"
"git.nutfactory.org/hoernschen/Matrix/utils"
"github.com/cenkalti/backoff/v4"
"github.com/gorilla/mux"
"nutfactory.org/Matrix/config"
"nutfactory.org/Matrix/entities/device"
"nutfactory.org/Matrix/entities/user"
"nutfactory.org/Matrix/utils"
)
func New(

View file

@ -4,7 +4,7 @@ import (
"fmt"
"strings"
"nutfactory.org/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateRoomMember(roomId string, userId string) (err error) {

View file

@ -3,7 +3,7 @@ package event
import (
"fmt"
"nutfactory.org/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateTransaction(transaction *Transaction) (err error) {

View file

@ -7,10 +7,10 @@ import (
"net/http"
"os"
"nutfactory.org/Matrix/config"
"nutfactory.org/Matrix/entities/device"
"nutfactory.org/Matrix/utils"
"nutfactory.org/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/entities/device"
"git.nutfactory.org/hoernschen/Matrix/utils"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
type resolveServerNameResponse struct {
@ -26,7 +26,7 @@ type serverImplementation struct {
Version string `json:"version,omitempty"`
}
type resetBody struct {
type ResetBody struct {
Packetloss float32 `json:"packetloss,omitempty"`
UnavailableTill int `json:"unavailableTill,omitempty"`
AuthentificationCheck bool `json:"authentificationCheck,omitempty"`
@ -52,9 +52,10 @@ func GetServerImplementation(w http.ResponseWriter, r *http.Request) {
}
}
// TODO: Add a function to set the Config-Params
func Reset(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
request := resetBody{}
request := ResetBody{}
errResponse := utils.CheckRequest(r)
if errResponse != nil {
w.WriteHeader(http.StatusBadRequest)

View file

@ -1,6 +1,6 @@
package room
import "nutfactory.org/Matrix/entities/event"
import "git.nutfactory.org/hoernschen/Matrix/entities/event"
type Room struct {
Id string `json:"id,omitempty"`
@ -15,7 +15,7 @@ type Room struct {
Federated bool `json:"federated,omitempty"`
}
type createRoomRequest struct {
type CreateRoomRequest struct {
Visibility string `json:"visibility,omitempty"`
RoomAliasName string `json:"room_alias_name,omitempty"`
Name string `json:"name,omitempty"`
@ -23,14 +23,14 @@ type createRoomRequest struct {
Invite string `json:"invite,omitempty"`
Invite3pid invite3pid `json:"invite_3pid,omitempty"`
RoomVersion string `json:"room_version,omitempty"`
CreationContent creationContent `json:"creation_content,omitempty"`
CreationContent CreationContent `json:"creation_content,omitempty"`
InitialState []event.StateEvent `json:"initial_state,omitempty"`
Preset string `json:"preset,omitempty"`
IsDirect bool `json:"is_direct,omitempty"`
PowerLevelContentOverride string `json:"power_level_content_override,omitempty"`
}
type createRoomResponse struct {
type CreateRoomResponse struct {
RoomId string `json:"room_id,omitempty"`
}
@ -40,11 +40,11 @@ type getRoomMemberResponse struct {
Chunk []*event.Event `json:"chunk,omitempty"`
}
type joinRoomUserRequest struct {
type JoinRoomUserRequest struct {
ThirdPartySigned thirdPartySigned `json:"third_party_signed,omitempty"`
}
type joinRoomUserResponse struct {
type JoinRoomUserResponse struct {
RoomId string `json:"room_id,omitempty"`
}
@ -89,7 +89,7 @@ type invite3pid struct {
Address string `json:"address,omitempty"`
}
type creationContent struct {
type CreationContent struct {
Federated bool `json:"m.federate,omitempty"`
}

View file

@ -9,12 +9,12 @@ import (
"strings"
"time"
"git.nutfactory.org/hoernschen/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/entities/event"
"git.nutfactory.org/hoernschen/Matrix/entities/user"
"git.nutfactory.org/hoernschen/Matrix/utils"
"github.com/cenkalti/backoff/v4"
"github.com/gorilla/mux"
"nutfactory.org/Matrix/config"
"nutfactory.org/Matrix/entities/event"
"nutfactory.org/Matrix/entities/user"
"nutfactory.org/Matrix/utils"
)
func New(
@ -47,7 +47,7 @@ func New(
func CreateRoomHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
request := createRoomRequest{}
request := CreateRoomRequest{}
errResponse := utils.CheckRequest(r)
if errResponse != nil {
w.WriteHeader(http.StatusBadRequest)
@ -315,7 +315,7 @@ func CreateRoomHandler(w http.ResponseWriter, r *http.Request) {
return
}
response := createRoomResponse{RoomId: newRoom.Id}
response := CreateRoomResponse{RoomId: newRoom.Id}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
panic(err)
@ -378,7 +378,7 @@ func GetRoomMemberHandler(w http.ResponseWriter, r *http.Request) {
func JoinRoomUserHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
request := joinRoomUserRequest{}
request := JoinRoomUserRequest{}
errResponse := utils.CheckRequest(r)
if errResponse != nil {
w.WriteHeader(http.StatusBadRequest)
@ -578,7 +578,7 @@ func JoinRoomUserHandler(w http.ResponseWriter, r *http.Request) {
}
return
}
response := joinRoomUserResponse{RoomId: roomId}
response := JoinRoomUserResponse{RoomId: roomId}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
panic(err)

View file

@ -3,8 +3,8 @@ package room
import (
"fmt"
"nutfactory.org/Matrix/entities/event"
"nutfactory.org/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/entities/event"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateRoom(room *Room) (err error) {

View file

@ -1,7 +1,7 @@
package user
import (
"nutfactory.org/Matrix/entities/device"
"git.nutfactory.org/hoernschen/Matrix/entities/device"
)
type User struct {
@ -19,8 +19,8 @@ type availableResponse struct {
Available bool `json:"available,omitempty"`
}
type registerRequest struct {
Auth authentificationData `json:"auth,omitempty"`
type RegisterRequest struct {
Auth AuthentificationData `json:"auth,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
DeviceId string `json:"device_id,omitempty"`
@ -28,7 +28,7 @@ type registerRequest struct {
InhibitLogin bool `json:"inhibit_login,omitempty"`
}
type registerResponse struct {
type RegisterResponse struct {
UserId string `json:"user_id,omitempty"`
AccessToken string `json:"access_token,omitempty"`
HomeServer string `json:"home_server,omitempty"`
@ -52,7 +52,7 @@ type loginResponse struct {
}
type deaktivateUserRequest struct {
Auth authentificationData `json:"auth,omitempty"`
Auth AuthentificationData `json:"auth,omitempty"`
IdentityServer string `json:"id_server,omitempty"`
}
@ -63,7 +63,7 @@ type deaktivateUserResponse struct {
type changePasswordRequest struct {
NewPassword string
LogoutDevices bool
Auth authentificationData
Auth AuthentificationData
}
type identifier struct {
@ -75,7 +75,7 @@ type identifier struct {
Phone string `json:"phone,omitempty"`
}
type authentificationData struct {
type AuthentificationData struct {
LoginType string `json:"type,omitempty"`
Session string `json:"session,omitempty"`
}

View file

@ -5,9 +5,9 @@ import (
"fmt"
"net/http"
"nutfactory.org/Matrix/config"
"nutfactory.org/Matrix/entities/device"
"nutfactory.org/Matrix/utils"
"git.nutfactory.org/hoernschen/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/entities/device"
"git.nutfactory.org/hoernschen/Matrix/utils"
)
func New(username string, name string, password string) (err error, newUser *User) {
@ -69,7 +69,7 @@ func CheckUsernameAvailabilityHandler(w http.ResponseWriter, r *http.Request) {
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
request := registerRequest{}
request := RegisterRequest{}
errResponse := utils.CheckRequest(r)
if errResponse != nil {
w.WriteHeader(http.StatusBadRequest)
@ -120,7 +120,7 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
}
return
}
response := registerResponse{
response := RegisterResponse{
UserId: newUser.Id,
AccessToken: userDevice.AccessToken,
DeviceId: userDevice.Id,
@ -242,15 +242,6 @@ func LogoutHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
//TODO: Check if necessary
func SyncHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode("Not Implemented"); err != nil {
panic(err)
}
}
func checkLoginType(loginType string) (errResponse *utils.ErrorResponse) {
if loginType != "m.login.password" {
errResponse = &utils.ErrorResponse{ErrorCode: "M_UNKNOWN", ErrorMessage: "Bad login type."}

View file

@ -3,8 +3,8 @@ package user
import (
"fmt"
"nutfactory.org/Matrix/entities/device"
"nutfactory.org/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/entities/device"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateUser(user *User) (err error) {

5
go.mod
View file

@ -1,9 +1,10 @@
module nutfactory.org/Matrix
module git.nutfactory.org/hoernschen/Matrix
go 1.14
require (
github.com/cenkalti/backoff/v4 v4.1.0
github.com/gorilla/mux v1.8.0
github.com/mattn/go-sqlite3 v1.14.3
github.com/mattn/go-sqlite3 v1.14.4
github.com/urfave/cli v1.22.4
)

13
go.sum
View file

@ -5,6 +5,8 @@ github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEe
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
github.com/cenkalti/backoff/v4 v4.1.0 h1:c8LkOFQTzuO0WBM/ae5HdGQuZPfPxp7lqBRwQRm4fSc=
github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
@ -14,7 +16,16 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mattn/go-sqlite3 v1.14.3 h1:j7a/xn1U6TKA/PHHxqZuzh64CdtRc7rU9M+AvkOl5bA=
github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v1.14.4 h1:4rQjbDxdu9fSgI/r3KN72G3c2goxknAqHHgPWWs8UlI=
github.com/mattn/go-sqlite3 v1.14.4/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/urfave/cli v1.22.4 h1:u7tSpNPPswAFymm8IehJhy4uJMlUuU/GmqSkvJ1InXA=
github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
@ -27,7 +38,9 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d h1:/iIZNFGxc/a7C3yWjGcnboV+Tkc7mxr+p6fDztwoxuM=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.1-2020.1.5 h1:nI5egYTGJakVyOryqLs1cQO5dO0ksin5XXs2pspk75k=
honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=

32
main.go
View file

@ -6,14 +6,14 @@ import (
"net/http"
"os"
"nutfactory.org/Matrix/config"
"nutfactory.org/Matrix/entities/device"
"nutfactory.org/Matrix/entities/event"
"nutfactory.org/Matrix/entities/general"
"nutfactory.org/Matrix/entities/room"
"nutfactory.org/Matrix/entities/user"
"nutfactory.org/Matrix/utils/database"
"nutfactory.org/Matrix/utils/router"
"git.nutfactory.org/hoernschen/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/entities/device"
"git.nutfactory.org/hoernschen/Matrix/entities/event"
"git.nutfactory.org/hoernschen/Matrix/entities/general"
"git.nutfactory.org/hoernschen/Matrix/entities/room"
"git.nutfactory.org/hoernschen/Matrix/entities/user"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
"git.nutfactory.org/hoernschen/Matrix/utils/router"
)
var keyPath = "./ssl.key"
@ -35,7 +35,6 @@ var routes = router.Routes{
router.Route{"Register", "POST", "/_matrix/client/r0/register", user.RegisterHandler},
router.Route{"Login", "POST", "/_matrix/client/r0/login", user.LoginHandler},
router.Route{"Logout", "POST", "/_matrix/client/r0/logout", user.LogoutHandler},
router.Route{"Sync", "GET", "/_matrix/client/r0/sync", user.SyncHandler},
// Rooms
router.Route{"CreateRoom", "POST", "/_matrix/client/r0/createRoom", room.CreateRoomHandler},
@ -56,11 +55,14 @@ var routes = router.Routes{
}
func main() {
// TODO: Change to something variable --> cli
// TODO: Implement Message Counter
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
config.Homeserver = "localhost"
config.Port = "80"
if len(os.Args) > 1 {
config.Homeserver = os.Args[1]
}
log.Printf("Start homeserver on name %s", config.Homeserver)
if err := device.InitServerSigningKey(); err != nil {
log.Fatal(err)
}
@ -83,7 +85,15 @@ func main() {
log.Fatal(httpErr)
}
// TODO: TEST
httpErr = http.ListenAndServe(":80", router)
if httpErr != nil {
log.Fatal(httpErr)
}
/*
go http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+r.Host+r.URL.String(), http.StatusMovedPermanently)
}))
*/
}

BIN
sqlite.db

Binary file not shown.

View file

@ -8,7 +8,7 @@ import (
"fmt"
"log"
"nutfactory.org/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/config"
)
func CreateToken() (err error, token string) {

View file

@ -7,7 +7,7 @@ import (
"net/http"
"strings"
"nutfactory.org/Matrix/config"
"git.nutfactory.org/hoernschen/Matrix/config"
)
type RequestSummary struct {

View file

@ -3,8 +3,8 @@ package router
import (
"net/http"
"git.nutfactory.org/hoernschen/Matrix/utils"
"github.com/gorilla/mux"
"nutfactory.org/Matrix/utils"
)
func NewRouter(routes Routes) *mux.Router {

View file

@ -0,0 +1,209 @@
package workloadgenerator
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"git.nutfactory.org/hoernschen/Matrix/entities/room"
"git.nutfactory.org/hoernschen/Matrix/entities/user"
"git.nutfactory.org/hoernschen/Matrix/utils"
)
var httpString = "http"
var servers = []string{
"localhost",
}
var userIds []string
var accessTokens map[string]string
var roomId string
var users = []string{
"user1",
"user2",
"user3",
"user4",
"user5",
"user6",
}
func main() {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
accessTokens = make(map[string]string)
err := createUsers()
if err != nil {
log.Printf("Error in User-Creation: %s", err)
return
}
// Create Room
err = createRoom(userIds[0])
if err != nil {
log.Printf("Error in Room-Creation: %s", err)
return
}
// Join to Room
err = joinRoom(userIds[1:])
if err != nil {
log.Printf("Error joining Room: %s", err)
return
}
// Send Messages with Timer
}
func reset() (err error) {
// TODO: Implement
return
}
func createRoom(userId string) (err error) {
accessToken := accessTokens[userId]
requestUrl := fmt.Sprintf("%s://%s/_matrix/client/r0/createRoom", httpString, strings.Split(userId, ":")[1])
request := room.CreateRoomRequest{
Visibility: "public",
Name: "Testraum",
Topic: "Raum für die Energieeffizienz-Tests",
RoomVersion: "1",
CreationContent: room.CreationContent{
Federated: true,
},
Preset: "public_chat",
IsDirect: true,
}
reqBody, err := json.Marshal(request)
if err != nil {
return
}
client := &http.Client{}
req, err := http.NewRequest(http.MethodPost, requestUrl, bytes.NewBuffer(reqBody))
if err != nil {
return
}
req.Header["Content-Type"] = []string{"application/json"}
req.Header["Authorization"] = []string{fmt.Sprintf("Bearer %s", accessToken)}
res, err := client.Do(req)
if res.StatusCode != http.StatusOK {
handleError(res)
} else {
response := room.CreateRoomResponse{}
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&response)
if err != nil {
return
}
roomId = response.RoomId
log.Printf("Room created: %s", roomId)
}
return
}
func joinRoom(userIdsToJoin []string) (err error) {
for _, userId := range userIdsToJoin {
err = joinRoomUser(userId)
if err != nil {
return
}
}
return
}
func joinRoomUser(userId string) (err error) {
accessToken := accessTokens[userId]
requestUrl := fmt.Sprintf("%s://%s/_matrix/client/r0/rooms/%s/join", httpString, strings.Split(userId, ":")[1], roomId)
request := room.JoinRoomUserRequest{}
reqBody, err := json.Marshal(request)
if err != nil {
return
}
client := &http.Client{}
req, err := http.NewRequest(http.MethodPost, requestUrl, bytes.NewBuffer(reqBody))
if err != nil {
return
}
req.Header["Content-Type"] = []string{"application/json"}
req.Header["Authorization"] = []string{fmt.Sprintf("Bearer %s", accessToken)}
res, err := client.Do(req)
if res.StatusCode != http.StatusOK {
handleError(res)
} else {
response := room.JoinRoomUserResponse{}
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&response)
if err != nil {
return
}
roomId = response.RoomId
log.Printf("%s joined Room", userId)
}
return
}
func createUsers() (err error) {
for _, userToCreate := range users {
var userId string
var accessToken string
userId, accessToken, err = createUser(userToCreate, "localhost")
if err != nil {
return
}
if userId != "" && accessToken != "" {
log.Printf("%s: %s", userId, accessToken)
accessTokens[userId] = accessToken
userIds = append(userIds, userId)
}
}
return
}
func createUser(userToCreate string, homeserver string) (userId string, accessToken string, err error) {
requestUrl := fmt.Sprintf("%s://%s/_matrix/client/r0/register", httpString, homeserver)
request := user.RegisterRequest{
Auth: user.AuthentificationData{
LoginType: "m.login.password",
},
Username: userToCreate,
Password: "password",
DeviceName: fmt.Sprintf("%s's device", userToCreate),
}
reqBody, err := json.Marshal(request)
if err != nil {
return
}
client := &http.Client{}
req, err := http.NewRequest(http.MethodPost, requestUrl, bytes.NewBuffer(reqBody))
if err != nil {
return
}
req.Header["Content-Type"] = []string{"application/json"}
res, err := client.Do(req)
if res.StatusCode != http.StatusOK {
handleError(res)
} else {
response := user.RegisterResponse{}
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&response)
if err != nil {
return
}
userId = response.UserId
accessToken = response.AccessToken
}
return
}
func handleError(res *http.Response) {
response := utils.ErrorResponse{}
decoder := json.NewDecoder(res.Body)
err := decoder.Decode(&response)
if err != nil {
log.Printf("Error not parseable")
return
}
log.Printf("%s (%s)", response.ErrorMessage, response.ErrorCode)
}