Refactor Database Connector, Implement Register

This commit is contained in:
hoernschen 2020-10-03 14:22:29 +02:00
parent 0cc882cff0
commit c79d1f86e4
18 changed files with 1495 additions and 1234 deletions

View file

@ -0,0 +1,127 @@
package device
import (
"fmt"
"nutfactory.org/Matrix/utils/database"
)
func CreateDevice(device *Device, userId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO device
(id, name, userId)
VALUES
(?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(device.Id, device.Name, userId)
if err != nil {
return
}
tx.Commit()
return
}
func ReadDevice(id string) (foundDevice *Device, err error) {
queryStmt := fmt.Sprintf(`SELECT id, name
FROM device
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundDevice = &Device{}
err = rows.Scan(&foundDevice.Id, &foundDevice.Name)
if err != nil {
return
}
foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id)
}
return
}
func ReadDevicesForUser(userId string) (devices map[string]*Device, err error) {
queryStmt := fmt.Sprintf(`SELECT id, name
FROM device
WHERE userId = '%s'`, userId)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
devices = make(map[string]*Device)
for rows.Next() {
foundDevice := &Device{}
err = rows.Scan(&foundDevice.Id, &foundDevice.Name)
if err != nil {
return
}
foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id)
devices[foundDevice.Id] = foundDevice
}
return
}
func UpdateDevice(device *Device, userId string) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE device SET
name = ?,
userId = ?
WHERE id = ?`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(device.Name, userId, device.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteDevice(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM device
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -0,0 +1,125 @@
package device
import (
"fmt"
"nutfactory.org/Matrix/utils/database"
)
func CreateKey(key *Key, deviceId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO key
(id, type, key, deviceId)
VALUES
(?, ?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(key.Id, key.Type, key.Key, deviceId)
if err != nil {
return
}
tx.Commit()
return
}
func ReadKey(id string) (foundKey *Key, err error) {
queryStmt := fmt.Sprintf(`SELECT id, type, key
FROM key
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundKey = &Key{}
err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key)
if err != nil {
return
}
}
return
}
func ReadKeysForDevice(deviceId string) (keys map[string]*Key, err error) {
queryStmt := fmt.Sprintf(`SELECT id, type, key
FROM key
WHERE deviceId = '%s'`, deviceId)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
keys = make(map[string]*Key)
for rows.Next() {
foundKey := &Key{}
err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key)
if err != nil {
return
}
keys[foundKey.Id] = foundKey
}
return
}
func UpdateKey(key *Key) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE key SET
type = ?,
key = ?
WHERE id = ?`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(key.Type, key.Key, key.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteKey(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM key
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -0,0 +1,208 @@
package event
import (
"fmt"
"nutfactory.org/Matrix/utils/database"
)
func CreateEvent(event *Event, txnId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO event
(id, roomId, txnId, eventType, content, parentId, depth)
VALUES
(?, ?, ?, ?, ?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(event.Id, event.RoomId, txnId, event.EventType, event.Content, event.ParentId, event.Depth)
if err != nil {
return
}
tx.Commit()
return
}
func CreateEventsFromTransaction(txnId string, pdus map[string]*Event) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO event
(id, roomId, txnId, eventType, content, parentId, depth)
VALUES
(?, ?, ?, ?, ?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
for _, pdu := range pdus {
_, err = stmt.Exec(pdu.Id, pdu.RoomId, txnId, pdu.EventType, pdu.Content, pdu.ParentId, pdu.Depth)
if err != nil {
return
}
}
tx.Commit()
return
}
func ReadEvent(id string) (foundEvent *Event, err error) {
queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth
FROM event
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundEvent = &Event{}
err = rows.Scan(&foundEvent.Id,
&foundEvent.RoomId,
&foundEvent.EventType,
&foundEvent.Content,
&foundEvent.ParentId,
&foundEvent.Depth,
)
if err != nil {
return
}
}
return
}
func ReadEventsFromRoom(roomId string) (events map[string]*Event, err error) {
queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth
FROM event
WHERE roomId = '%s'`, roomId)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
events = make(map[string]*Event)
for rows.Next() {
foundEvent := &Event{}
err = rows.Scan(&foundEvent.Id,
&foundEvent.RoomId,
&foundEvent.EventType,
&foundEvent.Content,
&foundEvent.ParentId,
&foundEvent.Depth,
)
if err != nil {
return
}
events[foundEvent.Id] = foundEvent
}
return
}
func ReadEventsFromTransaction(txnId string) (events map[string]*Event, err error) {
queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth
FROM event
WHERE txnId = '%s'`, txnId)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
events = make(map[string]*Event)
for rows.Next() {
foundEvent := &Event{}
err = rows.Scan(
&foundEvent.Id,
&foundEvent.RoomId,
&foundEvent.EventType,
&foundEvent.Content,
&foundEvent.ParentId,
&foundEvent.Depth,
)
if err != nil {
return
}
events[foundEvent.Id] = foundEvent
}
return
}
func UpdateEvent(event *Event) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE event SET
roomId = ?,
eventType = ?,
content = ?,
parentId = ?,
depth = ?
WHERE id = ?`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(
event.RoomId,
event.EventType,
event.Content,
event.ParentId,
event.Depth,
event.Id,
)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteEvent(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM event
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -0,0 +1,215 @@
package room
import (
"fmt"
"nutfactory.org/Matrix/entities/event"
"nutfactory.org/Matrix/utils/database"
)
func CreateRoom(room *Room, userId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO room
(id, version)
VALUES
(?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(room.Id, room.Version)
if err != nil {
return
}
tx.Commit()
err = CreateRoomMember(room.Id, userId)
return
}
func CreateRoomMember(roomId string, userId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO roomMember
(roomId, userId)
VALUES
(?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(roomId, userId)
if err != nil {
return
}
tx.Commit()
return
}
func ReadRoom(id string) (foundRoom *Room, err error) {
queryStmt := fmt.Sprintf(`SELECT id, version
FROM room
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundRoom = &Room{}
err = rows.Scan(&foundRoom.Id, &foundRoom.Version)
if err != nil {
return
}
foundRoom.Messages, err = event.ReadEventsFromRoom(foundRoom.Id)
if err != nil {
return
}
foundRoom.Members, err = ReadRoomMembers(foundRoom.Id)
if err != nil {
return
}
}
return
}
func ReadRoomMembers(roomId string) (roomMembers []string, err error) {
queryStmt := fmt.Sprintf(`SELECT userId
FROM roomMember
WHERE roomId = '%s'`, roomId)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
roomMembers = []string{}
for rows.Next() {
var foundUser string
err = rows.Scan(&foundUser)
if err != nil {
return
}
roomMembers = append(roomMembers, foundUser)
}
return
}
func UpdateRoom(room *Room) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE room SET
version = ?
WHERE id = ?`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(room.Version, room.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteRoom(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM room
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
err = DeleteAllRoomMemberForRoom(id)
tx.Commit()
return
}
func DeleteRoomMember(roomId string, userId string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM roomMember
WHERE userId = '%s' AND roomId = '%s'`, userId, roomId)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteAllRoomMemberForUser(userId string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM roomMember
WHERE userId = '%s'`, userId)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteAllRoomMemberForRoom(roomId string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM roomMember
WHERE roomId = '%s'`, roomId)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -0,0 +1,101 @@
package transaction
import (
"fmt"
"nutfactory.org/Matrix/entities/event"
"nutfactory.org/Matrix/utils/database"
)
func CreateTransaction(transaction *Transaction) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO txn
(id, origin, timestamp)
VALUES
(?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(transaction.Id, transaction.Origin, transaction.Timestamp)
if err != nil {
return
}
tx.Commit()
return
}
func ReadTransaction(id string) (foundTransaction *Transaction, err error) {
queryStmt := fmt.Sprintf(`SELECT id, origin, timestamp
FROM txn
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundTransaction = &Transaction{}
err = rows.Scan(&foundTransaction.Id, &foundTransaction.Origin, &foundTransaction.Timestamp)
if err != nil {
return
}
foundTransaction.PDUS, err = event.ReadEventsFromTransaction(foundTransaction.Id)
}
return
}
func UpdateTransaction(transaction *Transaction) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE txn SET
origin = ?,
timestamp = ?
WHERE id = ?`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(transaction.Origin, transaction.Timestamp, transaction.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteTransaction(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM txn
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -10,3 +10,83 @@ type User struct {
Password string `json:"password,omitempty"` Password string `json:"password,omitempty"`
Devices map[string]*device.Device `json:"devices,omitempty"` Devices map[string]*device.Device `json:"devices,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"`
DeviceName string `json:"initial_device_display_name,omitempty"`
InhibitLogin bool `json:"inhibit_login,omitempty"`
}
type registerResponse struct {
UserId string `json:"user_id,omitempty"`
AccessToken string `json:"access_token,omitempty"`
HomeServer string `json:"home_server,omitempty"`
DeviceId string `json:"device_id,omitempty"`
}
type loginRequest struct {
LoginType string `json:"type,omitempty"`
Identifier identifier `json:"identifier,omitempty"`
Password string `json:"password,omitempty"`
Token string `json:"token,omitempty"`
DeviceId string `json:"device_id,omitempty"`
DeviceName string `json:"initial_device_display_name,omitempty"`
}
type loginResponse struct {
UserId string `json:"user_id,omitempty"`
AccessToken string `json:"access_token,omitempty"`
DeviceId string `json:"device_id,omitempty"`
DiscoveryInfo discoveryInformation `json:"well_known,omitempty"`
}
type deaktivateUserRequest struct {
Auth authentificationData `json:"auth,omitempty"`
IdentityServer string `json:"id_server,omitempty"`
}
type deaktivateUserResponse struct {
Unbind3PIDS string `json:"id_server_unbind_result,omitempty"` // success or no-support
}
type changePasswordRequest struct {
NewPassword string
LogoutDevices bool
Auth authentificationData
}
type errorResponse struct {
ErrorCode string `json:"errcode,omitempty"`
ErrorMessage string `json:"error,omitempty"`
RetryTime int `json:"retry_after_ms,omitempty"`
}
type identifier struct {
IdentifierType string `json:"type,omitempty"`
User string `json:"user,omitempty"`
Medium string `json:"medium,omitempty"`
Address string `json:"address,omitempty"`
Country string `json:"country,omitempty"`
Phone string `json:"phone,omitempty"`
}
type authentificationData struct {
LoginType string `json:"type,omitempty"`
Session string `json:"session,omitempty"`
}
type discoveryInformation struct {
Homeserver homeserverInformation `json:"m.homeserver,omitempty"`
IdentityServer identityServerInformation `json:"m.identity_server,omitempty"`
}
type homeserverInformation struct {
BaseUrl string `json:"base_url,omitempty"`
}
type identityServerInformation struct {
BaseUrl string `json:"base_url,omitempty"`
}

View file

@ -1,5 +1,160 @@
package user package user
func New() (user *User) { import (
"encoding/json"
"net/http"
"nutfactory.org/Matrix/entities/device"
"nutfactory.org/Matrix/utils"
)
func New(id string, name, string, password string, devices map[string]*device.Device) (newUser *User) {
newUser = &User{
Id: id,
Name: name,
Password: password,
Devices: devices,
}
return
}
func CheckUsernameAvailability(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode("Test"); err != nil {
panic(err)
}
}
func Register(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
request := registerRequest{}
errResponse := utils.CheckRequest(r, request)
if errResponse != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(errResponse); err != nil {
panic(err)
}
return
}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&request)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Could not parse JSON"}); err != nil {
panic(err)
}
return
}
errResponse = checkAuthData(&request.Auth)
if errResponse != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(errResponse); err != nil {
panic(err)
}
return
}
// TODO: Use New Function
newUser := &User{
Id: request.Username,
Name: request.Username,
Password: request.Password,
}
foundUser, err := ReadUser(newUser.Id)
if foundUser != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorCode: "M_USER_IN_USE", ErrorMessage: "Username already in use"}); err != nil {
panic(err)
}
return
}
err = CreateUser(newUser)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Database Error"}); err != nil {
panic(err)
}
return
}
userDevice, err := device.ReadDevice(request.DeviceId)
if userDevice != nil {
err = device.UpdateDevice(userDevice, newUser.Id)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Database Error"}); err != nil {
panic(err)
}
return
}
} else {
// TODO: Use New Function
userDevice = &device.Device{}
err = device.CreateDevice(userDevice, newUser.Id)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Database Error"}); err != nil {
panic(err)
}
return
}
}
response := registerResponse{
UserId: newUser.Id,
// TODO: Create Funktion for Token Generation
AccessToken: "TEST",
DeviceId: userDevice.Id,
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
panic(err)
}
}
func Login(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode("Test"); err != nil {
panic(err)
}
}
func Logout(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode("Test"); err != nil {
panic(err)
}
}
func Deactivate(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode("Test"); err != nil {
panic(err)
}
}
func ChangePassword(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode("Test"); err != nil {
panic(err)
}
}
//TODO: Check if necessary
func Sync(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode("Test"); err != nil {
panic(err)
}
}
func checkAuthData(authData *authentificationData) (errResponse *utils.ErrorResponse) {
if authData.LoginType != "m.login.password" {
errResponse = &utils.ErrorResponse{ErrorCode: "M_FORBIDDEN", ErrorMessage: "Unsupported Auth Type"}
return
}
return return
} }

View file

@ -0,0 +1,101 @@
package user
import (
"fmt"
"nutfactory.org/Matrix/entities/device"
"nutfactory.org/Matrix/utils/database"
)
func CreateUser(user *User) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO user
(id, name, password)
VALUES
(?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(user.Id, user.Name, user.Password)
if err != nil {
return
}
tx.Commit()
return
}
func ReadUser(id string) (foundUser *User, err error) {
queryStmt := fmt.Sprintf(`SELECT id, name, password
FROM user
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundUser = &User{}
err = rows.Scan(&foundUser.Id, &foundUser.Name, &foundUser.Password)
if err != nil {
return
}
foundUser.Devices, err = device.ReadDevicesForUser(foundUser.Id)
}
return
}
func UpdateUser(user *User) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE user SET
name = ?,
password = ?
WHERE id = ?`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(user.Name, user.Password, user.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteUser(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM user
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = database.DB.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

19
main.go
View file

@ -6,6 +6,7 @@ import (
"net/http" "net/http"
"os" "os"
"nutfactory.org/Matrix/entities/user"
"nutfactory.org/Matrix/utils/database" "nutfactory.org/Matrix/utils/database"
"nutfactory.org/Matrix/utils/router" "nutfactory.org/Matrix/utils/router"
) )
@ -26,13 +27,13 @@ var routes = router.Routes{
router.Route{"GetSigningKeyFromMultipleServer", "GET", "/_matrix/key/v2/query", Test}, router.Route{"GetSigningKeyFromMultipleServer", "GET", "/_matrix/key/v2/query", Test},
// Users // Users
router.Route{"CheckUsernameAvailability", "GET", "/_matrix/client/r0/register/available", Test}, router.Route{"CheckUsernameAvailability", "GET", "/_matrix/client/r0/register/available", user.CheckUsernameAvailability},
router.Route{"Register", "POST", "/_matrix/client/r0/register", Test}, router.Route{"Register", "POST", "/_matrix/client/r0/register", user.Register},
router.Route{"Login", "POST", "/_matrix/client/r0/login", Test}, router.Route{"Login", "POST", "/_matrix/client/r0/login", user.Login},
router.Route{"Logout", "POST", "/_matrix/client/r0/logout", Test}, router.Route{"Logout", "POST", "/_matrix/client/r0/logout", user.Logout},
router.Route{"Deactivate", "POST", "/_matrix/client/r0/account/deactivate", Test}, router.Route{"Deactivate", "POST", "/_matrix/client/r0/account/deactivate", user.Deactivate},
router.Route{"ChangePassword", "POST", "/_matrix/client/r0/account/password", Test}, router.Route{"ChangePassword", "POST", "/_matrix/client/r0/account/password", user.ChangePassword},
router.Route{"Sync", "GET", "/_matrix/client/r0/sync", Test}, router.Route{"Sync", "GET", "/_matrix/client/r0/sync", user.Sync},
// Rooms // Rooms
router.Route{"CreateRoom", "POST", "/_matrix/client/r0/createRoom", Test}, router.Route{"CreateRoom", "POST", "/_matrix/client/r0/createRoom", Test},
@ -73,8 +74,8 @@ func main() {
// TODO: Remove later // TODO: Remove later
os.Remove("sqlite.db") os.Remove("sqlite.db")
db, _ := database.InitDB("sqlite.db") _ = database.InitDB("sqlite.db")
defer db.Close() defer database.DB.Close()
router := router.NewRouter(routes) router := router.NewRouter(routes)

BIN
sqlite.db

Binary file not shown.

View file

@ -8,22 +8,353 @@ import (
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
func InitDB(filepath string) (db *sql.DB, err error) { var DB *sql.DB
func InitDB(filepath string) (err error) {
log.Printf("Init DB") log.Printf("Init DB")
db, err = sql.Open("sqlite3", filepath) DB, err = sql.Open("sqlite3", filepath)
if err != nil { if err != nil {
panic(err) panic(err)
} }
if db == nil { if DB == nil {
panic("DB couldn't be initialized") panic("DB couldn't be initialized")
} }
handleError(initDeviceTable(db)) handleError(initDeviceTable())
handleError(initKeyTable(db)) handleError(initKeyTable())
handleError(initEventTable(db)) handleError(initEventTable())
handleError(initRoomTable(db)) handleError(initRoomTable())
handleError(initTransactionTable(db)) handleError(initTransactionTable())
handleError(initUserTable(db)) handleError(initUserTable())
return
}
func initDeviceTable() (err error) {
log.Printf("Init Device Table")
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS device (
id TEXT PRIMARY KEY,
name TEXT,
userId TEXT
)`)
if err != nil {
return
}
statement.Exec()
/*
newDevice := &device.Device{Id: "test", Name: "TEST", Keys: nil}
err = CreateDevice(db, newDevice, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
newDevice.Name = "TEST2"
err = UpdateDevice(db, newDevice)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
devices, err := ReadDevicesForUser(db, "test")
if err != nil {
log.Printf("Error Read User: %s", err)
return
}
log.Println(devices)
err = DeleteDevice(db, newDevice.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
de, err := ReadDevice(db, "test")
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if de != nil {
log.Printf("Device ID: %s Name: %s", de.Id, de.Name)
} else {
log.Printf("No Device found")
}
*/
return
}
func initKeyTable() (err error) {
log.Printf("Init Key Table")
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS key (
id TEXT PRIMARY KEY,
type TEXT,
key TEXT,
deviceId TEXT
)`)
if err != nil {
return
}
statement.Exec()
/*
newKey := &device.Key{Id: "test", Type: "test", Key: "test"}
err = CreateKey(db, newKey, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
keys, err := ReadKeysForDevice(db, "test")
if err != nil {
log.Printf("Error Read Multiple: %s", err)
return
}
log.Println(keys)
newKey.Key = "TEST123"
err = UpdateKey(db, newKey)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteKey(db, newKey.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readKey, err := ReadKey(db, "test")
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readKey != nil {
log.Printf("Key ID: %s Type: %s, Key: %s", readKey.Id, readKey.Type, readKey.Key)
} else {
log.Printf("No Key found")
}
*/
return
}
func initEventTable() (err error) {
log.Printf("Init Event Table")
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS event (
id TEXT PRIMARY KEY,
roomId TEXT,
txnId TEXT,
eventType TEXT,
content TEXT,
parentId TEXT,
depth INTEGER
)`)
if err != nil {
return
}
statement.Exec()
/*
newEvent := &event.Event{
Id: "test",
RoomId: "test",
EventType: "test",
Content: "{TEST}",
ParentId: "test1",
Depth: 0,
}
err = CreateEvent(db, newEvent, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
eventsRoom, err := ReadEventsFromRoom(db, "test")
if err != nil {
log.Printf("Error Read User: %s", err)
return
}
log.Println(eventsRoom)
eventsTxn, err := ReadEventsFromTransaction(db, "test")
if err != nil {
log.Printf("Error Read User: %s", err)
return
}
log.Println(eventsTxn)
newEvent.Content = "{TEST123}"
err = UpdateEvent(db, newEvent)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteEvent(db, newEvent.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readEvent, err := ReadEvent(db, "test")
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readEvent != nil {
log.Printf("Event ID: %s RoomId: %s EventType: %s Content: %s ParentId: %s Depth: %s",
readEvent.Id, readEvent.RoomId, readEvent.EventType, readEvent.Content, readEvent.ParentId, readEvent.Depth)
} else {
log.Printf("No Event found")
}
*/
return
}
func initRoomTable() (err error) {
log.Printf("Init Room Table")
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS room (
id TEXT PRIMARY KEY,
version TEXT
)`)
if err != nil {
return
}
statement.Exec()
statement, err = DB.Prepare(`CREATE TABLE IF NOT EXISTS roomMember (
userId TEXT,
roomId TEXT,
PRIMARY KEY (userId, roomId)
)`)
if err != nil {
return
}
statement.Exec()
/*
newRoom := &room.Room{Id: "test", Version: "test"}
err = CreateRoom(db, newRoom, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
err = CreateRoomMember(db, newRoom.Id, "test2")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
roomMembers, err := ReadRoomMembers(db, newRoom.Id)
if err != nil {
log.Printf("Error Read Members: %s", err)
return
}
log.Println(roomMembers)
newRoom.Version = "test2"
err = UpdateRoom(db, newRoom)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteRoomMember(db, newRoom.Id, "test")
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
err = DeleteAllRoomMemberForUser(db, "test2")
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
err = DeleteRoom(db, newRoom.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readRoom, err := ReadRoom(db, newRoom.Id)
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readRoom != nil {
log.Printf("Room ID: %s Version: %s Members: %s", readRoom.Id, readRoom.Version, readRoom.Members)
} else {
log.Printf("No Room found")
}
*/
return
}
func initTransactionTable() (err error) {
log.Printf("Init Transaction Table")
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS txn (
id TEXT PRIMARY KEY,
origin TEXT,
timestamp INTEGER
)`)
if err != nil {
return
}
statement.Exec()
/*
newTransaction := &transaction.Transaction{Id: "test", Origin: "test.de", Timestamp: 1234}
err = CreateTransaction(db, newTransaction)
if err != nil {
log.Printf("Error Create: %s", err)
return
}
newTransaction.Origin = "test2.de"
err = UpdateTransaction(db, newTransaction)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteTransaction(db, newTransaction.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readTransaction, err := ReadTransaction(db, newTransaction.Id)
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readTransaction != nil {
log.Printf("Transaction ID: %s Origin: %s Timestamp: %s PDUS: %s", readTransaction.Id, readTransaction.Origin, readTransaction.Timestamp, readTransaction.PDUS)
} else {
log.Printf("No Transaction found")
}
*/
return
}
func initUserTable() (err error) {
log.Printf("Init User Table")
statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS user (
id TEXT PRIMARY KEY,
name TEXT,
password TEXT
)`)
if err != nil {
return
}
statement.Exec()
/*
newUser := &user.User{Id: "test", Name: "test", Password: "test"}
err = CreateUser(db, newUser)
if err != nil {
log.Printf("Error Create: %s", err)
return
}
newUser.Name = "TEST2"
err = UpdateUser(db, newUser)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteUser(db, newUser.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readUser, err := ReadUser(db, newUser.Id)
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readUser != nil {
log.Printf("User ID: %s Name: %s Password: %s Devices: %s", readUser.Id, readUser.Name, readUser.Password, readUser.Devices)
} else {
log.Printf("No User found")
}
*/
return return
} }

View file

@ -1,179 +0,0 @@
package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/device"
)
func initDeviceTable(db *sql.DB) (err error) {
log.Printf("Init Device Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS device (
id TEXT PRIMARY KEY,
name TEXT,
userId TEXT
)`)
if err != nil {
return
}
statement.Exec()
/*
newDevice := &device.Device{Id: "test", Name: "TEST", Keys: nil}
err = CreateDevice(db, newDevice, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
newDevice.Name = "TEST2"
err = UpdateDevice(db, newDevice)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
devices, err := ReadDevicesForUser(db, "test")
if err != nil {
log.Printf("Error Read User: %s", err)
return
}
log.Println(devices)
err = DeleteDevice(db, newDevice.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
de, err := ReadDevice(db, "test")
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if de != nil {
log.Printf("Device ID: %s Name: %s", de.Id, de.Name)
} else {
log.Printf("No Device found")
}
*/
return
}
func CreateDevice(db *sql.DB, device *device.Device, userId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO device
(id, name, userId)
VALUES
(?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(device.Id, device.Name, userId)
if err != nil {
return
}
tx.Commit()
return
}
func ReadDevice(db *sql.DB, id string) (foundDevice *device.Device, err error) {
queryStmt := fmt.Sprintf(`SELECT id, name
FROM device
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundDevice = &device.Device{}
err = rows.Scan(&foundDevice.Id, &foundDevice.Name)
if err != nil {
return
}
foundDevice.Keys, err = ReadKeysForDevice(db, foundDevice.Id)
}
return
}
func ReadDevicesForUser(db *sql.DB, userId string) (devices map[string]*device.Device, err error) {
queryStmt := fmt.Sprintf(`SELECT id, name
FROM device
WHERE userId = '%s'`, userId)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
devices = make(map[string]*device.Device)
for rows.Next() {
foundDevice := &device.Device{}
err = rows.Scan(&foundDevice.Id, &foundDevice.Name)
if err != nil {
return
}
foundDevice.Keys, err = ReadKeysForDevice(db, foundDevice.Id)
devices[foundDevice.Id] = foundDevice
}
return
}
func UpdateDevice(db *sql.DB, device *device.Device) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE device SET
name = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(device.Name, device.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteDevice(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM device
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -1,278 +0,0 @@
package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/event"
"nutfactory.org/Matrix/entities/transaction"
)
func initEventTable(db *sql.DB) (err error) {
log.Printf("Init Event Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS event (
id TEXT PRIMARY KEY,
roomId TEXT,
txnId TEXT,
eventType TEXT,
content TEXT,
parentId TEXT,
depth INTEGER
)`)
if err != nil {
return
}
statement.Exec()
/*
newEvent := &event.Event{
Id: "test",
RoomId: "test",
EventType: "test",
Content: "{TEST}",
ParentId: "test1",
Depth: 0,
}
err = CreateEvent(db, newEvent, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
eventsRoom, err := ReadEventsFromRoom(db, "test")
if err != nil {
log.Printf("Error Read User: %s", err)
return
}
log.Println(eventsRoom)
eventsTxn, err := ReadEventsFromTransaction(db, "test")
if err != nil {
log.Printf("Error Read User: %s", err)
return
}
log.Println(eventsTxn)
newEvent.Content = "{TEST123}"
err = UpdateEvent(db, newEvent)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteEvent(db, newEvent.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readEvent, err := ReadEvent(db, "test")
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readEvent != nil {
log.Printf("Event ID: %s RoomId: %s EventType: %s Content: %s ParentId: %s Depth: %s",
readEvent.Id, readEvent.RoomId, readEvent.EventType, readEvent.Content, readEvent.ParentId, readEvent.Depth)
} else {
log.Printf("No Event found")
}
*/
return
}
func CreateEvent(db *sql.DB, event *event.Event, txnId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO event
(id, roomId, txnId, eventType, content, parentId, depth)
VALUES
(?, ?, ?, ?, ?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(event.Id, event.RoomId, txnId, event.EventType, event.Content, event.ParentId, event.Depth)
if err != nil {
return
}
tx.Commit()
return
}
func CreateEventsFromTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO event
(id, roomId, txnId, eventType, content, parentId, depth)
VALUES
(?, ?, ?, ?, ?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
for _, pdu := range transaction.PDUS {
_, err = stmt.Exec(pdu.Id, pdu.RoomId, transaction.Id, pdu.EventType, pdu.Content, pdu.ParentId, pdu.Depth)
if err != nil {
return
}
}
tx.Commit()
return
}
func ReadEvent(db *sql.DB, id string) (foundEvent *event.Event, err error) {
queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth
FROM event
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundEvent = &event.Event{}
err = rows.Scan(&foundEvent.Id,
&foundEvent.RoomId,
&foundEvent.EventType,
&foundEvent.Content,
&foundEvent.ParentId,
&foundEvent.Depth,
)
if err != nil {
return
}
}
return
}
func ReadEventsFromRoom(db *sql.DB, roomId string) (events map[string]*event.Event, err error) {
queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth
FROM event
WHERE roomId = '%s'`, roomId)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
events = make(map[string]*event.Event)
for rows.Next() {
foundEvent := &event.Event{}
err = rows.Scan(&foundEvent.Id,
&foundEvent.RoomId,
&foundEvent.EventType,
&foundEvent.Content,
&foundEvent.ParentId,
&foundEvent.Depth,
)
if err != nil {
return
}
events[foundEvent.Id] = foundEvent
}
return
}
func ReadEventsFromTransaction(db *sql.DB, txnId string) (events map[string]*event.Event, err error) {
queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth
FROM event
WHERE txnId = '%s'`, txnId)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
events = make(map[string]*event.Event)
for rows.Next() {
foundEvent := &event.Event{}
err = rows.Scan(
&foundEvent.Id,
&foundEvent.RoomId,
&foundEvent.EventType,
&foundEvent.Content,
&foundEvent.ParentId,
&foundEvent.Depth,
)
if err != nil {
return
}
events[foundEvent.Id] = foundEvent
}
return
}
func UpdateEvent(db *sql.DB, event *event.Event) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE event SET
roomId = ?,
eventType = ?,
content = ?,
parentId = ?,
depth = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(
event.RoomId,
event.EventType,
event.Content,
event.ParentId,
event.Depth,
event.Id,
)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteEvent(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM event
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -1,177 +0,0 @@
package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/device"
)
func initKeyTable(db *sql.DB) (err error) {
log.Printf("Init Key Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS key (
id TEXT PRIMARY KEY,
type TEXT,
key TEXT,
deviceId TEXT
)`)
if err != nil {
return
}
statement.Exec()
/*
newKey := &device.Key{Id: "test", Type: "test", Key: "test"}
err = CreateKey(db, newKey, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
keys, err := ReadKeysForDevice(db, "test")
if err != nil {
log.Printf("Error Read Multiple: %s", err)
return
}
log.Println(keys)
newKey.Key = "TEST123"
err = UpdateKey(db, newKey)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteKey(db, newKey.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readKey, err := ReadKey(db, "test")
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readKey != nil {
log.Printf("Key ID: %s Type: %s, Key: %s", readKey.Id, readKey.Type, readKey.Key)
} else {
log.Printf("No Key found")
}
*/
return
}
func CreateKey(db *sql.DB, key *device.Key, deviceId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO key
(id, type, key, deviceId)
VALUES
(?, ?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(key.Id, key.Type, key.Key, deviceId)
if err != nil {
return
}
tx.Commit()
return
}
func ReadKey(db *sql.DB, id string) (foundKey *device.Key, err error) {
queryStmt := fmt.Sprintf(`SELECT id, type, key
FROM key
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundKey = &device.Key{}
err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key)
if err != nil {
return
}
}
return
}
func ReadKeysForDevice(db *sql.DB, deviceId string) (keys map[string]*device.Key, err error) {
queryStmt := fmt.Sprintf(`SELECT id, type, key
FROM key
WHERE deviceId = '%s'`, deviceId)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
keys = make(map[string]*device.Key)
for rows.Next() {
foundKey := &device.Key{}
err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key)
if err != nil {
return
}
keys[foundKey.Id] = foundKey
}
return
}
func UpdateKey(db *sql.DB, key *device.Key) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE key SET
type = ?,
key = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(key.Type, key.Key, key.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteKey(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM key
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -1,288 +0,0 @@
package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/room"
)
func initRoomTable(db *sql.DB) (err error) {
log.Printf("Init Room Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS room (
id TEXT PRIMARY KEY,
version TEXT
)`)
if err != nil {
return
}
statement.Exec()
statement, err = db.Prepare(`CREATE TABLE IF NOT EXISTS roomMember (
userId TEXT,
roomId TEXT,
PRIMARY KEY (userId, roomId)
)`)
if err != nil {
return
}
statement.Exec()
/*
newRoom := &room.Room{Id: "test", Version: "test"}
err = CreateRoom(db, newRoom, "test")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
err = CreateRoomMember(db, newRoom.Id, "test2")
if err != nil {
log.Printf("Error Create: %s", err)
return
}
roomMembers, err := ReadRoomMembers(db, newRoom.Id)
if err != nil {
log.Printf("Error Read Members: %s", err)
return
}
log.Println(roomMembers)
newRoom.Version = "test2"
err = UpdateRoom(db, newRoom)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteRoomMember(db, newRoom.Id, "test")
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
err = DeleteAllRoomMemberForUser(db, "test2")
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
err = DeleteRoom(db, newRoom.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readRoom, err := ReadRoom(db, newRoom.Id)
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readRoom != nil {
log.Printf("Room ID: %s Version: %s Members: %s", readRoom.Id, readRoom.Version, readRoom.Members)
} else {
log.Printf("No Room found")
}
*/
return
}
func CreateRoom(db *sql.DB, room *room.Room, userId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO room
(id, version)
VALUES
(?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(room.Id, room.Version)
if err != nil {
return
}
tx.Commit()
err = CreateRoomMember(db, room.Id, userId)
return
}
func CreateRoomMember(db *sql.DB, roomId string, userId string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO roomMember
(roomId, userId)
VALUES
(?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(roomId, userId)
if err != nil {
return
}
tx.Commit()
return
}
func ReadRoom(db *sql.DB, id string) (foundRoom *room.Room, err error) {
queryStmt := fmt.Sprintf(`SELECT id, version
FROM room
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundRoom = &room.Room{}
err = rows.Scan(&foundRoom.Id, &foundRoom.Version)
if err != nil {
return
}
foundRoom.Messages, err = ReadEventsFromRoom(db, foundRoom.Id)
if err != nil {
return
}
foundRoom.Members, err = ReadRoomMembers(db, foundRoom.Id)
if err != nil {
return
}
}
return
}
func ReadRoomMembers(db *sql.DB, roomId string) (roomMembers []string, err error) {
queryStmt := fmt.Sprintf(`SELECT userId
FROM roomMember
WHERE roomId = '%s'`, roomId)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
roomMembers = []string{}
for rows.Next() {
var foundUser string
err = rows.Scan(&foundUser)
if err != nil {
return
}
roomMembers = append(roomMembers, foundUser)
}
return
}
func UpdateRoom(db *sql.DB, room *room.Room) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE room SET
version = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(room.Version, room.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteRoom(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM room
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
err = DeleteAllRoomMemberForRoom(db, id)
tx.Commit()
return
}
func DeleteRoomMember(db *sql.DB, roomId string, userId string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM roomMember
WHERE userId = '%s' AND roomId = '%s'`, userId, roomId)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteAllRoomMemberForUser(db *sql.DB, userId string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM roomMember
WHERE userId = '%s'`, userId)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteAllRoomMemberForRoom(db *sql.DB, roomId string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM roomMember
WHERE roomId = '%s'`, roomId)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -1,146 +0,0 @@
package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/transaction"
)
func initTransactionTable(db *sql.DB) (err error) {
log.Printf("Init Transaction Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS txn (
id TEXT PRIMARY KEY,
origin TEXT,
timestamp INTEGER
)`)
if err != nil {
return
}
statement.Exec()
/*
newTransaction := &transaction.Transaction{Id: "test", Origin: "test.de", Timestamp: 1234}
err = CreateTransaction(db, newTransaction)
if err != nil {
log.Printf("Error Create: %s", err)
return
}
newTransaction.Origin = "test2.de"
err = UpdateTransaction(db, newTransaction)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteTransaction(db, newTransaction.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readTransaction, err := ReadTransaction(db, newTransaction.Id)
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readTransaction != nil {
log.Printf("Transaction ID: %s Origin: %s Timestamp: %s PDUS: %s", readTransaction.Id, readTransaction.Origin, readTransaction.Timestamp, readTransaction.PDUS)
} else {
log.Printf("No Transaction found")
}
*/
return
}
func CreateTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO txn
(id, origin, timestamp)
VALUES
(?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(transaction.Id, transaction.Origin, transaction.Timestamp)
if err != nil {
return
}
tx.Commit()
return
}
func ReadTransaction(db *sql.DB, id string) (foundTransaction *transaction.Transaction, err error) {
queryStmt := fmt.Sprintf(`SELECT id, origin, timestamp
FROM txn
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundTransaction = &transaction.Transaction{}
err = rows.Scan(&foundTransaction.Id, &foundTransaction.Origin, &foundTransaction.Timestamp)
if err != nil {
return
}
foundTransaction.PDUS, err = ReadEventsFromTransaction(db, foundTransaction.Id)
}
return
}
func UpdateTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE txn SET
origin = ?,
timestamp = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(transaction.Origin, transaction.Timestamp, transaction.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteTransaction(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM txn
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

View file

@ -1,147 +0,0 @@
package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/user"
)
func initUserTable(db *sql.DB) (err error) {
log.Printf("Init User Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS user (
id TEXT PRIMARY KEY,
name TEXT,
password TEXT
)`)
if err != nil {
return
}
statement.Exec()
/*
newUser := &user.User{Id: "test", Name: "test", Password: "test"}
err = CreateUser(db, newUser)
if err != nil {
log.Printf("Error Create: %s", err)
return
}
newUser.Name = "TEST2"
err = UpdateUser(db, newUser)
if err != nil {
log.Printf("Error Update: %s", err)
return
}
err = DeleteUser(db, newUser.Id)
if err != nil {
log.Printf("Error Delete: %s", err)
return
}
readUser, err := ReadUser(db, newUser.Id)
if err != nil {
log.Printf("Error Read: %s", err)
return
}
if readUser != nil {
log.Printf("User ID: %s Name: %s Password: %s Devices: %s", readUser.Id, readUser.Name, readUser.Password, readUser.Devices)
} else {
log.Printf("No User found")
}
*/
return
}
func CreateUser(db *sql.DB, user *user.User) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO user
(id, name, password)
VALUES
(?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(user.Id, user.Name, user.Password)
if err != nil {
return
}
tx.Commit()
return
}
func ReadUser(db *sql.DB, id string) (foundUser *user.User, err error) {
queryStmt := fmt.Sprintf(`SELECT id, name, password
FROM user
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundUser = &user.User{}
err = rows.Scan(&foundUser.Id, &foundUser.Name, &foundUser.Password)
if err != nil {
return
}
foundUser.Devices, err = ReadDevicesForUser(db, foundUser.Id)
}
return
}
func UpdateUser(db *sql.DB, user *user.User) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE user SET
name = ?,
password = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(user.Name, user.Password, user.Id)
if err != nil {
return
}
tx.Commit()
return
}
func DeleteUser(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM user
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}

32
utils/requestChecker.go Normal file
View file

@ -0,0 +1,32 @@
package utils
import (
"encoding/json"
"net/http"
"strings"
)
type ErrorResponse struct {
ErrorCode string `json:"errcode,omitempty"`
ErrorMessage string `json:"error,omitempty"`
RetryTime int `json:"retry_after_ms,omitempty"`
}
func CheckRequest(r *http.Request, request interface{}) (response *ErrorResponse) {
if !strings.Contains(r.Header.Get("Content-Type"), "application/json") {
response = &ErrorResponse{ErrorMessage: "Content Type not JSON"}
}
return
}
func IsJSONString(s string) bool {
var js string
return json.Unmarshal([]byte(s), &js) == nil
}
func IsJSON(s string) bool {
var js interface{}
return json.Unmarshal([]byte(s), &js) == nil
}