Merge pull request #2 from nxshock/refactor/models

Refactor models module structure
This commit is contained in:
ChronosX88 2019-07-19 19:53:58 +04:00 committed by GitHub
commit 063442f1b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 422 additions and 379 deletions

1
.gitignore vendored
View File

@ -11,3 +11,4 @@
# Output of the go coverage tool, specifically when used with LiteIDE # Output of the go coverage tool, specifically when used with LiteIDE
*.out *.out
/cmd/cmd /cmd/cmd
/.vscode

View File

@ -1,10 +1,13 @@
package internal package internal
import "github.com/nxshock/signaller/internal/models" import (
"github.com/nxshock/signaller/internal/models"
"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) (token string, error *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
Sync(token string, request models.SyncRequest) (response *models.SyncReply, err *models.ApiError) Sync(token string, request sync.SyncRequest) (response *sync.SyncReply, err *models.ApiError)
} }

View File

@ -9,6 +9,9 @@ import (
"strings" "strings"
"github.com/nxshock/signaller/internal/models" "github.com/nxshock/signaller/internal/models"
login "github.com/nxshock/signaller/internal/models/login"
register "github.com/nxshock/signaller/internal/models/register"
mSync "github.com/nxshock/signaller/internal/models/sync"
) )
func RootHandler(w http.ResponseWriter, r *http.Request) { func RootHandler(w http.ResponseWriter, r *http.Request) {
@ -50,7 +53,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
// https://models.org/docs/spec/client_server/latest#post-models-client-r0-login // https://models.org/docs/spec/client_server/latest#post-models-client-r0-login
case "POST": case "POST":
{ {
var request models.LoginRequest var request login.LoginRequest
getRequest(r, &request) // TODO: handle error getRequest(r, &request) // TODO: handle error
// delete start "@" if presents // delete start "@" if presents
@ -64,7 +67,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
response := models.LoginReply{ response := login.LoginReply{
UserID: request.Identifier.User, UserID: request.Identifier.User,
AccessToken: token} AccessToken: token}
@ -109,7 +112,7 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
var request models.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)
@ -118,7 +121,7 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
var response models.RegisterResponse var response register.RegisterResponse
response.UserID = "@" + request.Username response.UserID = "@" + request.Username
response.DeviceID = request.DeviceID response.DeviceID = request.DeviceID
response.AccessToken = token response.AccessToken = token
@ -128,7 +131,7 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
// https://models.org/docs/spec/client_server/latest#get-models-client-r0-sync // https://models.org/docs/spec/client_server/latest#get-models-client-r0-sync
func SyncHandler(w http.ResponseWriter, r *http.Request) { func SyncHandler(w http.ResponseWriter, r *http.Request) {
var request models.SyncRequest var request mSync.SyncRequest
request.Filter = r.FormValue("filter") request.Filter = r.FormValue("filter")
timeout, err := strconv.Atoi(r.FormValue("timeout")) timeout, err := strconv.Atoi(r.FormValue("timeout"))
@ -148,7 +151,7 @@ func SyncHandler(w http.ResponseWriter, r *http.Request) {
response, _ := currServer.Backend.Sync(token, request) // TODO: handle error response, _ := currServer.Backend.Sync(token, request) // TODO: handle error
response.NextBatch = "123" response.NextBatch = "123"
response.Rooms = models.RoomsSyncReply{} response.Rooms = mSync.RoomsSyncReply{}
sendJsonResponse(w, http.StatusOK, response) sendJsonResponse(w, http.StatusOK, response)
} }

View File

@ -0,0 +1,31 @@
package common
type AuthenticationType string
// Authentication types
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id198
const (
// Password-based
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id199
AuthenticationTypePassword AuthenticationType = "m.login.password"
// Google ReCaptcha
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id200
AuthenticationTypeRecaptcha AuthenticationType = "m.login.recaptcha"
// OAuth2-based
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id202
AuthenticationTypeOauth2 AuthenticationType = "m.login.oauth2"
// Email-based (identity server)
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id203
AuthenticationTypeEmail AuthenticationType = "m.login.email.identity"
// Token-based
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id201
AuthenticationTypeToken AuthenticationType = "m.login.token"
// Dummy Auth
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id204
AuthenticationTypeDummy AuthenticationType = "m.login.dummy"
)

View File

@ -0,0 +1,6 @@
package common
type DeviceLists struct {
Changed []string `json:"changed"` // List of users who have updated their device identity keys, or who now share an encrypted room with the client since the previous sync response.
Left []string `json:"left"` // List of users with whom we do not share any encrypted rooms anymore since the previous sync response.
}

View File

@ -0,0 +1,69 @@
package common
import "encoding/json"
type Membership string
const (
MembershipInvite Membership = "invite"
MembershipJoin Membership = "join"
MembershipKnock Membership = "knock"
MembershipLeave Membership = "leave"
MembershipBan Membership = "ban"
)
type Event struct {
// TODO: object
Content json.RawMessage `json:"content"` // Required. The fields in this object will vary depending on the type of event. When interacting with the REST API, this is the HTTP body.
Type string `json:"type"` // Required. The type of event. This SHOULD be namespaced similar to Java package naming conventions e.g. 'com.example.subdomain.event.type'
}
type EventContent struct {
AvatarURL string `json:"avatar_url"` // The avatar URL for this user, if any. This is added by the homeserver.
// TODO: string or null
DisplayName string `json:"displayname"` // The display name for this user, if any. This is added by the homeserver.
Membership Membership `json:"membership"` // Required. The membership state of the user. One of: ["invite", "join", "knock", "leave", "ban"]
IsDirect bool `json:"is_direct"` // Flag indicating if the room containing this event was created with the intention of being a direct chat. See Direct Messaging.
ThirdPartyInvite Invite `json:"third_party_invite"` //
Unsigned UnsignedData `json:"unsigned"` // Contains optional extra information about the event.
}
type StateEvent struct {
// TODO: object?
Content json.RawMessage `json:"content"` // Required. The fields in this object will vary depending on the type of event. When interacting with the REST API, this is the HTTP body.
Type string `json:"type"` // Required. The type of event. This SHOULD be namespaced similar to Java package naming conventions e.g. 'com.example.subdomain.event.type'
EventID string `json:"event_id"` // Required. The globally unique event identifier.
Sender string `json:"sender"` // Required. Contains the fully-qualified ID of the user who sent this event.
OriginServerTs int `json:"origin_server_ts"` // Required. Timestamp in milliseconds on originating homeserver when this event was sent.
Unsigned UnsignedData `json:"unsigned"` // Contains optional extra information about the event.
PrevContent EventContent `json:"prev_content"` // Optional. The previous content for this event. If there is no previous content, this key will be missing.
StateKey string `json:"state_key"` // Required. A unique key which defines the overwriting semantics for this piece of room state. This value is often a zero-length string. The presence of this key makes this event a State Event. State keys starting with an @ are reserved for referencing user IDs, such as room members. With the exception of a few events, state events set with a given user's ID as the state key MUST only be set by that user.
}
type signed struct {
Mxid string `json:"mxid"` // Required. The invited matrix user ID. Must be equal to the user_id property of the event.
// TODO:
// Signatures Signatures `json:"signatures"` // Required. A single signature from the verifying server, in the format specified by the Signing Events section of the server-server API.
Token string `json:"token"` // Required. The token property of the containing third_party_invite object.
}
type State struct {
events []StateEvent `json:"events"` // List of events.
}
type Invite struct {
DisplayName string `json:"display_name"` // Required. A name which can be displayed to represent the user instead of their third party identifier
Signed signed `json:"signed"` // Required. A block of content which has been signed, which servers can use to verify the event. Clients should ignore this.
}
type Ephemeral struct {
Events []Event `json:"events"` // List of events.
}
type StrippedState struct {
// TODO: в документации EventContent, хотя вроде сервер выдаёт json.RawMessage
Content json.RawMessage `json:"content"` // Required. The content for the event.
StateKey string `json:"state_key"` // Required. The state_key for the event.
Type string `json:"type"` // Required. The type for the event.
Sender string `json:"sender"` // Required. The sender for the event.
}

View File

@ -1,20 +1,4 @@
package models package common
type MRelatesTo struct {
InReplyTo MInReplyTo `json:"m.in_reply_to"`
}
type MInReplyTo struct {
EventID string `json:"event_id"`
}
// 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
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.
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.
}
// https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-client-r0-rooms-roomid-members // https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-client-r0-rooms-roomid-members
type MemberEvent struct { type MemberEvent struct {

View File

@ -0,0 +1,15 @@
package common
// https://matrix.org/docs/spec/client_server/r0.4.0.html#m-room-message-msgtypes
type MessageType string
const (
MessageTypeText MessageType = "m.text" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-text
MessageTypeEmote MessageType = "m.emote" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-emote
MessageTypeNotice MessageType = "m.notice" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-notice
MessageTypeImage MessageType = "m.image" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-image
MessageTypeFile MessageType = "m.file" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-file
MessageTypeVideo MessageType = "m.video" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-video
MessageTypeAudio MessageType = "m.audio" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-audio
MessageTypeLocation MessageType = "m.location" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-location
)

View File

@ -0,0 +1,5 @@
package common
type Presence struct {
events []Event `json:"events"` // List of events.
}

View File

@ -0,0 +1,50 @@
package common
import "encoding/json"
type Timeline struct {
Events []RoomEvent `json:"events"` // List of events.
Limited bool `json:"limited"` // True if the number of events returned was limited by the limit on the filter.
PrevBatch string `json:"prev_batch"` // A token that can be supplied to the from parameter of the rooms/{roomId}/messages endpoint.
}
type RoomEvent struct {
// TODO: object
Content json.RawMessage `json:"content"` // Required. The fields in this object will vary depending on the type of event. When interacting with the REST API, this is the HTTP body.
Type string `json:"type"` // Required. The type of event. This SHOULD be namespaced similar to Java package naming conventions e.g. 'com.example.subdomain.event.type'
EventID string `json:"event_id"` // Required. The globally unique event identifier.
Sender string `json:"sender"` // Required. Contains the fully-qualified ID of the user who sent this event.
OriginServerTs int64 `json:"origin_server_ts"` // Required. Timestamp in milliseconds on originating homeserver when this event was sent.
Unsigned UnsignedData `json:"unsigned"` // Contains optional extra information about the event.
}
type JoinedRoom struct {
State State `json:"state"` // Updates to the state, between the time indicated by the since parameter, and the start of the timeline (or all state up to the start of the timeline, if since is not given, or full_state is true).
Timeline Timeline `json:"timeline"` // The timeline of messages and state changes in the room.
Ephemeral Ephemeral `json:"ephemeral"` // The ephemeral events in the room that aren't recorded in the timeline or state of the room. e.g. typing.
AccountData AccountData `json:"account_data"` // The private data that this user has attached to this room.
UnreadNotifications UnreadNotificationCounts `json:"unread_notifications"` // Counts of unread notifications for this room
}
type AccountData struct {
Events []Event `json:"events"` // List of events.
}
type UnreadNotificationCounts struct {
HighlightCount int `json:"highlight_count"` // The number of unread notifications for this room with the highlight flag set
NotificationCount int `json:"notification_count"` // The total number of unread notifications for this room
}
type LeftRoom struct {
State State `json:"state"` // The state updates for the room up to the start of the timeline.
Timeline Timeline `json:"timeline"` // The timeline of messages and state changes in the room up to the point when the user left.
AccountData AccountData `json:"account_data"` // The private data that this user has attached to this room.
}
type InvitedRoom struct {
InviteState InviteState `json:"invite_state"` // The state of a room that the user has been invited to. These state events may only have the sender, type, state_key and content keys present. These events do not replace any state that the client already has for the room, for example if the client has archived the room. Instead the client should keep two separate copies of the state: the one from the invite_state and one from the archived state. If the client joins the room then the current state will be given as a delta against the archived state not the invite_state.
}
type InviteState struct {
Events []StrippedState `json:"events"` // The StrippedState events that form the invite state.
}

View File

@ -0,0 +1,6 @@
package common
// TODO: проверить правильность выбора типа
type ToDevice struct {
events []Event `json:"events` // List of send-to-device messages
}

View File

@ -0,0 +1,7 @@
package common
type UnsignedData struct {
Age int `json:"age"` // The time in milliseconds that has elapsed since the event was sent. This field is generated by the local homeserver, and may be incorrect if the local time on at least one of the two servers is out of sync, which can cause the age to either be negative or greater than it actually is.
RedactedBecause Event `json:"redacted_because"` // Optional. The event that redacted this event, if any.
TransactionID string `json:"transaction_id"` // The client-supplied transaction ID, if the client being given the event is the same one which sent it.
}

View File

@ -0,0 +1,21 @@
package common
// UserIdentifier represents user identifier object
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-login
type UserIdentifier struct {
Type IdentifierType `json:"type"` // Required. The type of identification. See Identifier types for supported values and additional property descriptions.
User string `json:"user,omitempty"` // The fully qualified user ID or just local part of the user ID, to log in.
Medium string `json:"medium,omitempty"` // When logging in using a third party identifier, the medium of the identifier. Must be 'email'.
Address string `json:"address,omitempty"` // Third party identifier for the user.
Country string `json:"country,omitempty"`
Phone string `json:"phone,omitempty"`
}
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id207
type IdentifierType string
const (
IdentifierTypeUser IdentifierType = "m.id.user" // https://matrix.org/docs/spec/client_server/r0.4.0.html#id208
IdentifierTypeThirdparty IdentifierType = "m.id.thirdparty" // https://matrix.org/docs/spec/client_server/r0.4.0.html#id209
IdentifierTypePhone IdentifierType = "m.id.phone" // https://matrix.org/docs/spec/client_server/r0.4.0.html#id210
)

View File

@ -0,0 +1,5 @@
package createroom
type CreateRoomReply struct {
RoomID string `json:"room_id"`
}

View File

@ -0,0 +1,38 @@
package createroom
import (
common "github.com/nxshock/signaller/internal/models/common"
)
type VisibilityType string
const (
VisibilityTypePrivate = "private"
VisibilityTypePublic = "public"
)
// 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
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.
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.
}
// CreateRoomRequest represents room creation request
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-createroom
type CreateRoomRequest struct {
Visibility VisibilityType `json:"visibility,omitempty"`
RoomAliasName string `json:"room_alias_name,omitempty"`
Name string `json:"name,omitempty"`
Topic string `json:"topic,omitempty"`
Invite []string `json:"invite,omitempty"`
Invite3pids []Invite3pid `json:"invite_3pid,omitempty"`
RoomVersion string `json:"room_version,omitempty"`
// TODO: проверить тип
// CreationContent CreationContentType `json:"creation_content,omitempty"`
InitialState []common.StateEvent `json:"initial_state,omitempty"`
Preset string `json:"preset,omitempty"` // TODO: проверить тип
IsDirect bool `json:"is_direct,omitempty"`
// PowerLevelContentOverride `json:"power_level_content_override"`
}

View File

@ -1,86 +1,5 @@
package models package models
type Membership string
const (
MembershipInvite Membership = "invite"
MembershipJoin Membership = "join"
MembershipKnock Membership = "knock"
MembershipLeave Membership = "leave"
MembershipBan Membership = "ban"
)
type SetPresence string
const (
SetPresenceOffline SetPresence = "offline"
SetPresenceOnline SetPresence = "online"
SetPresenceUnavailable SetPresence = "unavailable"
)
type JoinRule string
const (
JoinRulePublic JoinRule = "public"
JoinRuleKnock JoinRule = "knock"
JoinRuleInvite JoinRule = "invite"
JoinRulePrivate JoinRule = "private"
)
// https://matrix.org/docs/spec/client_server/r0.4.0.html#m-room-message-msgtypes
type MessageType string
const (
MessageTypeText MessageType = "m.text" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-text
MessageTypeEmote MessageType = "m.emote" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-emote
MessageTypeNotice MessageType = "m.notice" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-notice
MessageTypeImage MessageType = "m.image" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-image
MessageTypeFile MessageType = "m.file" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-file
MessageTypeVideo MessageType = "m.video" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-video
MessageTypeAudio MessageType = "m.audio" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-audio
MessageTypeLocation MessageType = "m.location" // https://matrix.org/docs/spec/client_server/r0.4.0.html#m-location
)
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id207
type IdentifierType string
const (
IdentifierTypeUser IdentifierType = "m.id.user" // https://matrix.org/docs/spec/client_server/r0.4.0.html#id208
IdentifierTypeThirdparty IdentifierType = "m.id.thirdparty" // https://matrix.org/docs/spec/client_server/r0.4.0.html#id209
IdentifierTypePhone IdentifierType = "m.id.phone" // https://matrix.org/docs/spec/client_server/r0.4.0.html#id210
)
// Authentication types
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id198
type AuthenticationType string
const (
// Password-based
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id199
AuthenticationTypePassword AuthenticationType = "m.login.password"
// Google ReCaptcha
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id200
AuthenticationTypeRecaptcha AuthenticationType = "m.login.recaptcha"
// OAuth2-based
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id202
AuthenticationTypeOauth2 AuthenticationType = "m.login.oauth2"
// Email-based (identity server)
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id203
AuthenticationTypeEmail AuthenticationType = "m.login.email.identity"
// Token-based
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id201
AuthenticationTypeToken AuthenticationType = "m.login.token"
// Dummy Auth
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id204
AuthenticationTypeDummy AuthenticationType = "m.login.dummy"
)
type VisibilityType string type VisibilityType string
const ( const (

View File

@ -0,0 +1,6 @@
package joinroom
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id276
type JoinRoomReply struct {
RoomID string `json:"room_id"` // The joined room ID must be returned in the room_id field.
}

View File

@ -0,0 +1,5 @@
package login
type GetLoginReply struct {
Flows []Flow `json:"flows"` // The homeserver's supported login types
}

View File

@ -0,0 +1,15 @@
package login
import (
common "github.com/nxshock/signaller/internal/models/common"
)
type LoginReply struct {
AccessToken string `json:"access_token"`
HomeServer string `json:"home_server,omitempty"` // TODO: check api
UserID string `json:"user_id"`
}
type Flow struct {
Type common.AuthenticationType `json:"type"`
}

View File

@ -0,0 +1,16 @@
package login
import (
common "github.com/nxshock/signaller/internal/models/common"
)
// LoginRequest represents login request
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-login
type LoginRequest struct {
Type common.AuthenticationType `json:"type"` // Required. The login type being used. One of: ["m.login.password", "m.login.token"]
Identifier common.UserIdentifier `json:"identifier"` // Identification information for the user.
Password string `json:"password,omitempty"` // Required when type is m.login.password. The user's password.
Token string `json:"token,omitempty"` // Required when type is m.login.token. Part of Token-based login.
DeviceID string `json:"device_id,omitempty"` // ID of the client device. If this does not correspond to a known client device, a new device will be created. The server will auto-generate a device_id if this is not specified.
InitialDeviceDisplayName string `json:"initial_device_display_name,omitempty"` // A display name to assign to the newly-created device. Ignored if device_id corresponds to a known device.
}

View File

@ -0,0 +1,8 @@
package register
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-register
type RegisterResponse struct {
UserID string `json:"user_id"` // Required. The fully-qualified Matrix user ID (MXID) that has been registered. Any user ID returned by this API must conform to the grammar given in the Matrix specification.
AccessToken string `json:"access_token,omitempty"` // An access token for the account. This access token can then be used to authorize other requests. Required if the inhibit_login option is false.
DeviceID string `json:"device_id,omitempty"` // ID of the registered device. Will be the same as the corresponding parameter in the request, if one was specified. Required if the inhibit_login option is false.
}

View File

@ -0,0 +1,20 @@
package register
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-register
type RegisterRequest struct {
Auth AuthenticationData `json:"auth"` // Additional authentication information for the user-interactive authentication API. Note that this information is not used to define how the registered user should be authenticated, but is instead used to authenticate the register call itself.
BindEmail bool `json:"bind_email"` // If true, the server binds the email used for authentication to the Matrix ID with the identity server.
BindMsisdn bool `json:"bind_msisdn"` // If true, the server binds the phone number used for authentication to the Matrix ID with the identity server.
Username string `json:"username"` // The basis for the localpart of the desired Matrix ID. If omitted, the homeserver MUST generate a Matrix ID local part.
Password string `json:"password"` // The desired password for the account.
DeviceID string `json:"device_id"` // ID of the client device. If this does not correspond to a known client device, a new device will be created. The server will auto-generate a device_id if this is not specified.
InitialDeviceDisplayName string `json:"initial_device_display_name"` // A display name to assign to the newly-created device. Ignored if device_id corresponds to a known device.
InhibitLogin bool `json:"inhibit_login"` // If true, an access_token and device_id should not be returned from this call, therefore preventing an automatic login. Defaults to false.
}
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-register
type AuthenticationData struct {
Type string `json:"type"` // Required. The login type that the client is attempting to complete.
Session string `json:"session,omitempty"` // The value of the session key given by the homeserver.
}

View File

@ -1,50 +1,8 @@
package models package models
type JoinedRoomReply struct { import (
JoinedRooms []string `json:"joined_rooms"` common "github.com/nxshock/signaller/internal/models/common"
} )
// SendMessageReply represents reply for send message command
// https://matrix.org/docs/spec/client_server/r0.4.0.html#put-matrix-client-r0-rooms-roomid-state-eventtype-statekey
type SendMessageReply struct {
EventID string `json:"event_id"` // A unique identifier for the event.
}
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-createroom
type CreateRoomReply struct {
RoomID string `json:"room_id"` // Information about the newly created room.
}
type GetLoginReply struct {
Flows []Flow // The homeserver's supported login types
}
type LoginReply struct {
AccessToken string `json:"access_token"`
HomeServer string `json:"home_server,omitempty"` // TODO: check api
UserID string `json:"user_id"`
}
type SyncReply struct {
NextBatch string `json:"next_batch"` // Required. The batch token to supply in the since param of the next /sync request.
Rooms RoomsSyncReply `json:"rooms"` // Updates to rooms.
Presence Presence `json:"presence"` // The updates to the presence status of other users.
AccountData AccountData `json:"account_data"` // The global private data created by this user.
ToDevice ToDevice `json:"to_device"` // Information on the send-to-device messages for the client device, as defined in Send-to-Device messaging.
DeviceLists DeviceLists `json:"device_lists"` // Information on end-to-end device updates, as specified in End-to-end encryption.
DeviceOneTimeKeysCount map[string]int `json:"device_one_time_keys_count"` // Information on end-to-end encryption keys, as specified in End-to-end encryption.
}
type RoomsSyncReply struct {
Join map[string]JoinedRoom `json:"join"` // The rooms that the user has joined.
Invite map[string]InvitedRoom `json:"invite"` // The rooms that the user has been invited to.
Leave map[string]LeftRoom `json:"leave"` // The rooms that the user has left or been banned from.
}
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id276
type JoinRoomReply struct {
RoomID string `json:"room_id"` // The joined room ID must be returned in the room_id field.
}
// https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-client-versions // https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-client-versions
type VersionsReply struct { type VersionsReply struct {
@ -59,12 +17,5 @@ type WhoAmIReply struct {
// https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-client-r0-rooms-roomid-members // https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-client-r0-rooms-roomid-members
type MembersReply struct { type MembersReply struct {
Chunk []MemberEvent `json:"chunk"` Chunk []common.MemberEvent `json:"chunk"`
}
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-register
type RegisterResponse struct {
UserID string `json:"user_id"` // Required. The fully-qualified Matrix user ID (MXID) that has been registered. Any user ID returned by this API must conform to the grammar given in the Matrix specification.
AccessToken string `json:"access_token,omitempty"` // An access token for the account. This access token can then be used to authorize other requests. Required if the inhibit_login option is false.
DeviceID string `json:"device_id,omitempty"` // ID of the registered device. Will be the same as the corresponding parameter in the request, if one was specified. Required if the inhibit_login option is false.
} }

View File

@ -1,66 +0,0 @@
package models
// LoginRequest represents login request
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-login
type LoginRequest struct {
Type AuthenticationType `json:"type"` // Required. The login type being used. One of: ["m.login.password", "m.login.token"]
Identifier UserIdentifier `json:"identifier"` // Identification information for the user.
Password string `json:"password,omitempty"` // Required when type is m.login.password. The user's password.
Token string `json:"token,omitempty"` // Required when type is m.login.token. Part of Token-based login.
DeviceID string `json:"device_id,omitempty"` // ID of the client device. If this does not correspond to a known client device, a new device will be created. The server will auto-generate a device_id if this is not specified.
InitialDeviceDisplayName string `json:"initial_device_display_name,omitempty"` // A display name to assign to the newly-created device. Ignored if device_id corresponds to a known device.
}
// UserIdentifier represents user identifier object
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-login
type UserIdentifier struct {
Type IdentifierType `json:"type"` // Required. The type of identification. See Identifier types for supported values and additional property descriptions.
User string `json:"user,omitempty"` // The fully qualified user ID or just local part of the user ID, to log in.
Medium string `json:"medium,omitempty"` // When logging in using a third party identifier, the medium of the identifier. Must be 'email'.
Address string `json:"address,omitempty"` // Third party identifier for the user.
Country string `json:"country,omitempty"`
Phone string `json:"phone,omitempty"`
}
// CreateRoomRequest represents room creation request
// https://matrix.org/docs/spec/client_server/r0.4.0.html#post-matrix-client-r0-createroom
type CreateRoomRequest struct {
Visibility VisibilityType `json:"visibility,omitempty"`
RoomAliasName string `json:"room_alias_name,omitempty"`
Name string `json:"name,omitempty"`
Topic string `json:"topic,omitempty"`
Invite []string `json:"invite,omitempty"`
Invite3pids []Invite3pid `json:"invite_3pid,omitempty"`
RoomVersion string `json:"room_version,omitempty"`
// TODO: проверить тип
// CreationContent CreationContentType `json:"creation_content,omitempty"`
InitialState []StateEvent `json:"initial_state,omitempty"`
Preset string `json:"preset,omitempty"` // TODO: проверить тип
IsDirect bool `json:"is_direct,omitempty"`
// PowerLevelContentOverride `json:"power_level_content_override"`
}
type SendMessageRequest struct {
Body string `json:"body"` // Required. The textual representation of this message.
MessageType MessageType `json:"msgtype"` // Required. The type of message, e.g. m.image, m.text
RelatesTo MRelatesTo `json:"m.relates_to,omitempty"`
}
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-register
type RegisterRequest struct {
Auth AuthenticationData `json:"auth"` // Additional authentication information for the user-interactive authentication API. Note that this information is not used to define how the registered user should be authenticated, but is instead used to authenticate the register call itself.
BindEmail bool `json:"bind_email"` // If true, the server binds the email used for authentication to the Matrix ID with the identity server.
BindMsisdn bool `json:"bind_msisdn"` // If true, the server binds the phone number used for authentication to the Matrix ID with the identity server.
Username string `json:"username"` // The basis for the localpart of the desired Matrix ID. If omitted, the homeserver MUST generate a Matrix ID local part.
Password string `json:"password"` // The desired password for the account.
DeviceID string `json:"device_id"` // ID of the client device. If this does not correspond to a known client device, a new device will be created. The server will auto-generate a device_id if this is not specified.
InitialDeviceDisplayName string `json:"initial_device_display_name"` // A display name to assign to the newly-created device. Ignored if device_id corresponds to a known device.
InhibitLogin bool `json:"inhibit_login"` // If true, an access_token and device_id should not be returned from this call, therefore preventing an automatic login. Defaults to false.
}
// https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-register
type AuthenticationData struct {
Type string `json:"type"` // Required. The login type that the client is attempting to complete.
Session string `json:"session,omitempty"` // The value of the session key given by the homeserver.
}

View File

@ -0,0 +1,7 @@
package sendmessage
// SendMessageReply represents reply for send message command
// https://matrix.org/docs/spec/client_server/r0.4.0.html#put-matrix-client-r0-rooms-roomid-state-eventtype-statekey
type SendMessageReply struct {
EventID string `json:"event_id"` // A unique identifier for the event.
}

View File

@ -0,0 +1,19 @@
package sendmessage
import (
common "github.com/nxshock/signaller/internal/models/common"
)
type SendMessageRequest struct {
Body string `json:"body"` // Required. The textual representation of this message.
MessageType common.MessageType `json:"msgtype"` // Required. The type of message, e.g. m.image, m.text
RelatesTo MRelatesTo `json:"m.relates_to,omitempty"`
}
type MRelatesTo struct {
InReplyTo MInReplyTo `json:"m.in_reply_to"`
}
type MInReplyTo struct {
EventID string `json:"event_id"`
}

View File

@ -1,141 +0,0 @@
package models
import (
"encoding/json"
)
// https://matrix.org/docs/spec/client_server/r0.4.0.html#id242
type SyncRequest struct {
Filter string `url:"filter,omitempty"` // The ID of a filter created using the filter API or a filter JSON object encoded as a string. The server will detect whether it is an ID or a JSON object by whether the first character is a "{" open brace. Passing the JSON inline is best suited to one off requests. Creating a filter using the filter API is recommended for clients that reuse the same filter multiple times, for example in long poll requests.
Since string `url:"since,omitempty"` // A point in time to continue a sync from.
FullState bool `url:"full_state,omitempty"` // Controls whether to include the full state for all rooms the user is a member of.
SetPresence SetPresence `url:"set_presence,omitempty"` // Controls whether the client is automatically marked as online by polling this API. If this parameter is omitted then the client is automatically marked as online when it uses this API. Otherwise if the parameter is set to "offline" then the client is not marked as being online when it uses this API. When set to "unavailable", the client is marked as being idle. One of: ["offline", "online", "unavailable"]
Timeout int `url:"timeout,omitempty"` // The maximum time to wait, in milliseconds, before returning this request. If no events (or other data) become available before this time elapses, the server will return a response with empty fields.
}
type JoinedRoom struct {
State State `json:"state"` // Updates to the state, between the time indicated by the since parameter, and the start of the timeline (or all state up to the start of the timeline, if since is not given, or full_state is true).
Timeline Timeline `json:"timeline"` // The timeline of messages and state changes in the room.
Ephemeral Ephemeral `json:"ephemeral"` // The ephemeral events in the room that aren't recorded in the timeline or state of the room. e.g. typing.
AccountData AccountData `json:"account_data"` // The private data that this user has attached to this room.
UnreadNotifications UnreadNotificationCounts `json:"unread_notifications"` // Counts of unread notifications for this room
}
type Ephemeral struct {
Events []Event `json:"events"` // List of events.
}
type UnreadNotificationCounts struct {
HighlightCount int `json:"highlight_count"` // The number of unread notifications for this room with the highlight flag set
NotificationCount int `json:"notification_count"` // The total number of unread notifications for this room
}
type InvitedRoom struct {
InviteState InviteState `json:"invite_state"` // The state of a room that the user has been invited to. These state events may only have the sender, type, state_key and content keys present. These events do not replace any state that the client already has for the room, for example if the client has archived the room. Instead the client should keep two separate copies of the state: the one from the invite_state and one from the archived state. If the client joins the room then the current state will be given as a delta against the archived state not the invite_state.
}
type InviteState struct {
Events []StrippedState `json:"events"` // The StrippedState events that form the invite state.
}
type StrippedState struct {
// TODO: в документации EventContent, хотя вроде сервер выдаёт json.RawMessage
Content json.RawMessage `json:"content"` // Required. The content for the event.
StateKey string `json:"state_key"` // Required. The state_key for the event.
Type string `json:"type"` // Required. The type for the event.
Sender string `json:"sender"` // Required. The sender for the event.
}
type LeftRoom struct {
State State `json:"state"` // The state updates for the room up to the start of the timeline.
Timeline Timeline `json:"timeline"` // The timeline of messages and state changes in the room up to the point when the user left.
AccountData AccountData `json:"account_data"` // The private data that this user has attached to this room.
}
type State struct {
events []StateEvent `json:"events"` // List of events.
}
type StateEvent struct {
// TODO: object?
Content json.RawMessage `json:"content"` // Required. The fields in this object will vary depending on the type of event. When interacting with the REST API, this is the HTTP body.
Type string `json:"type"` // Required. The type of event. This SHOULD be namespaced similar to Java package naming conventions e.g. 'com.example.subdomain.event.type'
EventID string `json:"event_id"` // Required. The globally unique event identifier.
Sender string `json:"sender"` // Required. Contains the fully-qualified ID of the user who sent this event.
OriginServerTs int `json:"origin_server_ts"` // Required. Timestamp in milliseconds on originating homeserver when this event was sent.
Unsigned UnsignedData `json:"unsigned"` // Contains optional extra information about the event.
PrevContent EventContent `json:"prev_content"` // Optional. The previous content for this event. If there is no previous content, this key will be missing.
StateKey string `json:"state_key"` // Required. A unique key which defines the overwriting semantics for this piece of room state. This value is often a zero-length string. The presence of this key makes this event a State Event. State keys starting with an @ are reserved for referencing user IDs, such as room members. With the exception of a few events, state events set with a given user's ID as the state key MUST only be set by that user.
}
type Timeline struct {
Events []RoomEvent `json:"events"` // List of events.
Limited bool `json:"limited"` // True if the number of events returned was limited by the limit on the filter.
PrevBatch string `json:"prev_batch"` // A token that can be supplied to the from parameter of the rooms/{roomId}/messages endpoint.
}
type RoomEvent struct {
// TODO: object
Content json.RawMessage `json:"content"` // Required. The fields in this object will vary depending on the type of event. When interacting with the REST API, this is the HTTP body.
Type string `json:"type"` // Required. The type of event. This SHOULD be namespaced similar to Java package naming conventions e.g. 'com.example.subdomain.event.type'
EventID string `json:"event_id"` // Required. The globally unique event identifier.
Sender string `json:"sender"` // Required. Contains the fully-qualified ID of the user who sent this event.
OriginServerTs int64 `json:"origin_server_ts"` // Required. Timestamp in milliseconds on originating homeserver when this event was sent.
Unsigned UnsignedData `json:"unsigned"` // Contains optional extra information about the event.
}
type UnsignedData struct {
Age int `json:"age"` // The time in milliseconds that has elapsed since the event was sent. This field is generated by the local homeserver, and may be incorrect if the local time on at least one of the two servers is out of sync, which can cause the age to either be negative or greater than it actually is.
RedactedBecause Event `json:"redacted_because"` // Optional. The event that redacted this event, if any.
TransactionID string `json:"transaction_id"` // The client-supplied transaction ID, if the client being given the event is the same one which sent it.
}
type Presence struct {
events []Event `json:"events"` // List of events.
}
type AccountData struct {
Events []Event `json:"events"` // List of events.
}
type Event struct {
// TODO: object
Content json.RawMessage `json:"content"` // Required. The fields in this object will vary depending on the type of event. When interacting with the REST API, this is the HTTP body.
Type string `json:"type"` // Required. The type of event. This SHOULD be namespaced similar to Java package naming conventions e.g. 'com.example.subdomain.event.type'
}
type EventContent struct {
AvatarURL string `json:"avatar_url"` // The avatar URL for this user, if any. This is added by the homeserver.
// TODO: string or null
DisplayName string `json:"displayname"` // The display name for this user, if any. This is added by the homeserver.
Membership Membership `json:"membership"` // Required. The membership state of the user. One of: ["invite", "join", "knock", "leave", "ban"]
IsDirect bool `json:"is_direct"` // Flag indicating if the room containing this event was created with the intention of being a direct chat. See Direct Messaging.
ThirdPartyInvite Invite `json:"third_party_invite"` //
Unsigned UnsignedData `json:"unsigned"` // Contains optional extra information about the event.
}
type Invite struct {
DisplayName string `json:"display_name"` // Required. A name which can be displayed to represent the user instead of their third party identifier
Signed signed `json:"signed"` // Required. A block of content which has been signed, which servers can use to verify the event. Clients should ignore this.
}
type signed struct {
Mxid string `json:"mxid"` // Required. The invited matrix user ID. Must be equal to the user_id property of the event.
// TODO:
// Signatures Signatures `json:"signatures"` // Required. A single signature from the verifying server, in the format specified by the Signing Events section of the server-server API.
Token string `json:"token"` // Required. The token property of the containing third_party_invite object.
}
// TODO: проверить правильность выбора типа
type ToDevice struct {
events []Event `json:"events` // List of send-to-device messages
}
type DeviceLists struct {
Changed []string `json:"changed"` // List of users who have updated their device identity keys, or who now share an encrypted room with the client since the previous sync response.
Left []string `json:"left"` // List of users with whom we do not share any encrypted rooms anymore since the previous sync response.
}
type Flow struct {
Type AuthenticationType `json:"type"`
}

View File

@ -0,0 +1,21 @@
package sync
import (
common "github.com/nxshock/signaller/internal/models/common"
)
type SyncReply struct {
NextBatch string `json:"next_batch"` // Required. The batch token to supply in the since param of the next /sync request.
Rooms RoomsSyncReply `json:"rooms"` // Updates to rooms.
Presence common.Presence `json:"presence"` // The updates to the presence status of other users.
AccountData common.AccountData `json:"account_data"` // The global private data created by this user.
ToDevice common.ToDevice `json:"to_device"` // Information on the send-to-device messages for the client device, as defined in Send-to-Device messaging.
DeviceLists common.DeviceLists `json:"device_lists"` // Information on end-to-end device updates, as specified in End-to-end encryption.
DeviceOneTimeKeysCount map[string]int `json:"device_one_time_keys_count"` // Information on end-to-end encryption keys, as specified in End-to-end encryption.
}
type RoomsSyncReply struct {
Join map[string]common.JoinedRoom `json:"join"` // The rooms that the user has joined.
Invite map[string]common.InvitedRoom `json:"invite"` // The rooms that the user has been invited to.
Leave map[string]common.LeftRoom `json:"leave"` // The rooms that the user has left or been banned from.
}

View File

@ -0,0 +1,17 @@
package sync
type SetPresence string
const (
SetPresenceOffline SetPresence = "offline"
SetPresenceOnline SetPresence = "online"
SetPresenceUnavailable SetPresence = "unavailable"
)
type SyncRequest struct {
Filter string `url:"filter,omitempty"` // The ID of a filter created using the filter API or a filter JSON object encoded as a string. The server will detect whether it is an ID or a JSON object by whether the first character is a "{" open brace. Passing the JSON inline is best suited to one off requests. Creating a filter using the filter API is recommended for clients that reuse the same filter multiple times, for example in long poll requests.
Since string `url:"since,omitempty"` // A point in time to continue a sync from.
FullState bool `url:"full_state,omitempty"` // Controls whether to include the full state for all rooms the user is a member of.
SetPresence SetPresence `url:"set_presence,omitempty"` // Controls whether the client is automatically marked as online by polling this API. If this parameter is omitted then the client is automatically marked as online when it uses this API. Otherwise if the parameter is set to "offline" then the client is not marked as being online when it uses this API. When set to "unavailable", the client is marked as being idle. One of: ["offline", "online", "unavailable"]
Timeout int `url:"timeout,omitempty"` // The maximum time to wait, in milliseconds, before returning this request. If no events (or other data) become available before this time elapses, the server will return a response with empty fields.
}

View File

@ -7,6 +7,8 @@ import (
"sync" "sync"
"github.com/nxshock/signaller/internal/models" "github.com/nxshock/signaller/internal/models"
"github.com/nxshock/signaller/internal/models/common"
mSync "github.com/nxshock/signaller/internal/models/sync"
) )
var first bool var first bool
@ -84,7 +86,7 @@ func (memoryBackend MemoryBackend) Logout(token string) *models.ApiError {
return NewError(models.M_UNKNOWN_TOKEN, "unknown token") // TODO: create error struct return NewError(models.M_UNKNOWN_TOKEN, "unknown token") // TODO: create error struct
} }
func (memoryBackend MemoryBackend) Sync(token string, request models.SyncRequest) (response *models.SyncReply, err *models.ApiError) { func (memoryBackend MemoryBackend) Sync(token string, request mSync.SyncRequest) (response *mSync.SyncReply, err *models.ApiError) {
memoryBackend.mutex.Lock() memoryBackend.mutex.Lock()
defer memoryBackend.mutex.Unlock() defer memoryBackend.mutex.Unlock()
@ -92,18 +94,18 @@ func (memoryBackend MemoryBackend) Sync(token string, request models.SyncRequest
if !first { if !first {
log.Println(1) log.Println(1)
response = &models.SyncReply{ response = &mSync.SyncReply{
AccountData: models.AccountData{ AccountData: common.AccountData{
Events: []models.Event{ Events: []common.Event{
models.Event{Type: "m.direct", Content: json.RawMessage(`"@vasyo2:localhost":"!room1:localhost"`)}, common.Event{Type: "m.direct", Content: json.RawMessage(`"@vasyo2:localhost":"!room1:localhost"`)},
}}, }},
Rooms: models.RoomsSyncReply{ Rooms: mSync.RoomsSyncReply{
Join: map[string]models.JoinedRoom{ Join: map[string]common.JoinedRoom{
"!room1:localhost": models.JoinedRoom{ "!room1:localhost": common.JoinedRoom{
Timeline: models.Timeline{ Timeline: common.Timeline{
Events: []models.RoomEvent{ Events: []common.RoomEvent{
models.RoomEvent{Type: "m.room.create", Sender: "@vasyo2:localhost"}, common.RoomEvent{Type: "m.room.create", Sender: "@vasyo2:localhost"},
models.RoomEvent{Type: "m.room.member", Sender: "@vasyo2:localhost", Content: json.RawMessage(`membership:"join",displayname:"vasyo2"`)}, common.RoomEvent{Type: "m.room.member", Sender: "@vasyo2:localhost", Content: json.RawMessage(`membership:"join",displayname:"vasyo2"`)},
}}}}}} }}}}}}
/* InviteState: models.InviteState{ /* InviteState: models.InviteState{
Events: []models.StrippedState{ Events: []models.StrippedState{
@ -114,7 +116,7 @@ func (memoryBackend MemoryBackend) Sync(token string, request models.SyncRequest
first = true first = true
} else { } else {
os.Exit(0) os.Exit(0)
response = &models.SyncReply{} response = &mSync.SyncReply{}
} }
return response, nil // TODO: implement return response, nil // TODO: implement