matrix

package
v0.1.2-0...-0e84da5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2023 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MasterRuleID                = ".m.rule.master"
	SuppressNoticesRuleID       = ".m.rule.suppress_notices"
	InviteForMeRuleID           = ".m.rule.invite_for_me"
	MemberEventRuleID           = ".m.rule.member_event"
	ContainsDisplayNameRuleID   = ".m.rule.contains_display_name"
	TombstoneRuleID             = ".m.rule.tombstone"
	RoomNotificationRuleID      = ".m.rule.roomnotif"
	ContainsUsernameRuleID      = ".m.rule.contains_user_name"
	CallRuleID                  = ".m.rule.call"
	EncryptedRoomOneToOneRuleID = ".m.rule.encrypted_room_one_to_one"
	RoomOneToOneRuleID          = ".m.rule.room_one_to_one"
	MessageRuleID               = ".m.rule.message"
	EncryptedRuleID             = ".m.rule.encrypted"
)
View Source
const (
	// NotifyAction causes each matching event to generate a notification.
	NotifyAction = "notify"
	// DontNotifyAction prevents each matching event from generating a notification.
	DontNotifyAction = "dont_notify"
	// CoalesceAction enables notifications for matching events but activates homeserver-specific
	// behavior to intelligently coalesce multiple events into a single notification.
	CoalesceAction = "coalesce"
)

Variables

View Source
var (
	// ErrInvalidUserID is an error generated by UserID.Parse when the user ID is invalid.
	ErrInvalidUserID = errors.New("invalid user ID")
	// ErrInvalidRoomID is an error generated by RoomID.Parse when the room ID is invalid.
	ErrInvalidRoomID = errors.New("invalid room ID")
)
View Source
var (
	// ErrInvalidGeoURI represents an error in parsing geo URI.
	ErrInvalidGeoURI = errors.New("invalid geo URI")
	// ErrAltitudeNotPresent is returned when altitude is requested but not present.
	ErrAltitudeNotPresent = errors.New("altitude not present")
)

Functions

func MapAPIError

func MapAPIError(e error, m ErrorMap) error

MapAPIError is a helper function that maps API errors to its concrete error types as provided by the user.

Unmatched errors are returned as-is.

func StatusCode

func StatusCode(e error) int

StatusCode takes in an error and return the HTTP status code associated with it.

If it's not a HTTPError, it returns -1 instead.

Types

type APIError

type APIError struct {
	// Code and Message should be included in every API error.
	Code    ErrorCode `json:"errcode"`
	Message string    `json:"error"`

	// SoftLogout is included in invalid token errors.
	// If it's true, the client should just log back in.
	// If it's false, the client should purge all its cache before
	// logging back in.
	SoftLogout bool `json:"soft_logout"`

	// RetryAfterMillisecond is included in rate limit errors.
	RetryAfterMillisecond int `json:"retry_after_ms"`
}

APIError represents an API error as returned by the Matrix server.

It is always wrapped around by HTTPError.

func (APIError) Error

func (e APIError) Error() string

Error makes API Error implement the `error` interface.

type Capabilities

type Capabilities map[string]json.RawMessage

Capabilities represent the server's capabilities as defined in https://spec.matrix.org/v1.1/client-server-api/#get_matrixclientv3capabilities.

func (Capabilities) ChangePassword

func (c Capabilities) ChangePassword() (CapabilityChangePassword, error)

ChangePassword retrieves CapabilityChangePassword from the Capabilities.

func (Capabilities) RoomVersion

func (c Capabilities) RoomVersion() (CapabilityRoomVersion, error)

RoomVersion retrieves CapabilityRoomVersion from the Capabilities.

type CapabilityChangePassword

type CapabilityChangePassword struct {
	Enabled bool `json:"enabled"`
}

CapabilityChangePassword contains whether the server has password change enabled. If it is disabled, it's probably delegated to the identity server.

type CapabilityRoomVersion

type CapabilityRoomVersion struct {
	Default   string `json:"default"`
	Available map[string]RoomVersionStability
}

CapabilityRoomVersion contains information of the version of the rooms.

type DeviceID

type DeviceID string

DeviceID is a magic string that identifies a device.

type Duration

type Duration int64

Duration is a duration of time measured in milliseconds.

func (Duration) Duration

func (d Duration) Duration() time.Duration

Duration converts a duration into valid Go duration.

type ErrorCode

type ErrorCode string

ErrorCode represents an error code that is found in REST errors.

const (
	// Common error codes
	CodeForbidden     ErrorCode = "M_FORBIDDEN"
	CodeUnknownToken  ErrorCode = "M_UNKNOWN_TOKEN"
	CodeMissingToken  ErrorCode = "M_MISSING_TOKEN"
	CodeBadJSON       ErrorCode = "M_BAD_JSON"
	CodeNotJSON       ErrorCode = "M_NOT_JSON"
	CodeNotFound      ErrorCode = "M_NOT_FOUND"
	CodeLimitExceeded ErrorCode = "M_LIMIT_EXCEEDED"
	CodeUnknown       ErrorCode = "M_UNKNOWN"

	// Other error codes the client might encounter
	CodeUnrecognized                 ErrorCode = "M_UNRECOGNIZED"
	CodeUnauthorized                 ErrorCode = "M_UNAUTHORIZED"
	CodeUserDeactivated              ErrorCode = "M_USER_DEACTIVATED"
	CodeUserInUse                    ErrorCode = "M_USER_IN_USE"
	CodeInvalidUsername              ErrorCode = "M_INVALID_USERNAME"
	CodeRoomInUse                    ErrorCode = "M_ROOM_IN_USE"
	CodeInvalidRoomState             ErrorCode = "M_INVALID_ROOM_STATE"
	CodeThreePIDInUse                ErrorCode = "M_THREEPID_IN_USE"
	CodeThreePIDNotFound             ErrorCode = "M_THREEPID_NOT_FOUND"
	CodeThreePIDAuthFailed           ErrorCode = "M_THREEPID_AUTH_FAILED"
	CodeThreePIDDenied               ErrorCode = "M_THREEPID_DENIED"
	CodeServerNotTrusted             ErrorCode = "M_SERVER_NOT_TRUSTED"
	CodeUnsupportedRoomVersion       ErrorCode = "M_UNSUPPORTED_ROOM_VERSION"
	CodeIncompatibleRoomVersion      ErrorCode = "M_INCOMPATIBLE_ROOM_VERSION"
	CodeBadState                     ErrorCode = "M_BAD_STATE"
	CodeGuestAccessForbidden         ErrorCode = "M_GUEST_ACCESS_FORBIDDEN"
	CodeCaptchaNeeded                ErrorCode = "M_CAPTCHA_NEEDED"
	CodeCaptchaInvalid               ErrorCode = "M_CAPTCHA_INVALID"
	CodeMissingParam                 ErrorCode = "M_MISSING_PARAM"
	CodeInvalidParam                 ErrorCode = "M_INVALID_PARAM"
	CodeTooLarge                     ErrorCode = "M_TOO_LARGE"
	CodeExclusive                    ErrorCode = "M_EXCLUSIVE"
	CodeResourceLimitExceeded        ErrorCode = "M_RESOURCE_LIMIT_EXCEEDED"
	CodeCannotLeaveServiceNoticeRoom ErrorCode = "M_CANNOT_LEAVE_SERVICE_NOTICE_ROOM"

	// Codes that are documented on other sections
	CodeWeakPassword ErrorCode = "M_WEAK_PASSWORD"
)

List of official error codes. It can be found at https://spec.matrix.org/v1.1/client-server-api/#standard-error-response.

func ErrCode

func ErrCode(e error) ErrorCode

ErrCode takes in an error and return the API error code associated with it.

If it's not an APIError, it returns an empty string instead.

type ErrorMap

type ErrorMap map[ErrorCode]error

ErrorMap is a shorthand for map[ErrorCode]error.

type EventID

type EventID string

EventID is a string that identifies an event.

type GeoURI

type GeoURI string

GeoURI is a geographic URI.

func (GeoURI) Altitude

func (g GeoURI) Altitude() (float64, error)

Altitude returns the altitude specified in the GeoURI.

func (GeoURI) Lat

func (g GeoURI) Lat() (float64, error)

Lat returns the latitude specified in the GeoURI.

func (GeoURI) Long

func (g GeoURI) Long() (float64, error)

Long returns the longitude specified in the GeoURI.

func (GeoURI) Parse

func (g GeoURI) Parse() (float64, float64, *float64, error)

Parse returns the lat, long and altitude (if present). This only implements simple parsing. For more details, use the specific functions.

type HTTPError

type HTTPError struct {
	Code            int
	UnderlyingError error
}

HTTPError represents an error while decoding response. It contains the status code and the actual error.

func NewHTTPError

func NewHTTPError(code int, underlyingError error) HTTPError

NewHTTPError constructs a new HTTP error with the provided details.

func (HTTPError) Error

func (h HTTPError) Error() string

Error makes HTTPError implement the `error` interface.

func (HTTPError) Unwrap

func (h HTTPError) Unwrap() error

Unwrap allows the underlying error to be exposed.

type IDServerUnbindResult

type IDServerUnbindResult string

IDServerUnbindResult represents whether 3PIDs has been unbound from the identity server successfully.

const (
	// UnbindSuccess represents success in unbinding.
	UnbindSuccess IDServerUnbindResult = "success"
	// UnbindNoSupport means that the homeserver is unable to determine
	// the identity server to unbind from.
	UnbindNoSupport IDServerUnbindResult = "no-support"
)

type Identifier

type Identifier struct {
	Type IdentifierType `json:"type"`

	// User is valid when the type is IdentifierUser.
	// It only contains the local part.
	User string `json:"user,omitempty"`

	// Medium and Address are valid when the type is IdentifierThirdparty.
	Medium  string `json:"medium,omitempty"`
	Address string `json:"address,omitempty"`

	// Country and Phone are valid when the type is IdentifierPhone.
	Country string `json:"country,omitempty"`
	Phone   string `json:"phone,omitempty"`
}

Identifier represents a struct with all possible fields of identifying a user.

type IdentifierType

type IdentifierType string

IdentifierType represents methods in which the user can identify themselves.

const (
	IdentifierUser       IdentifierType = "m.id.user"
	IdentifierThirdparty IdentifierType = "m.id.thirdparty"
	IdentifierPhone      IdentifierType = "m.id.phone"
)

Official list of Identifier types. It can be found at https://spec.matrix.org/v1.1/client-server-api/#identifier-types.

type LoginMethod

type LoginMethod string

LoginMethod represents a possible login method that can be used to authenticate.

const (
	LoginPassword  LoginMethod = "m.login.password"
	LoginRecaptcha LoginMethod = "m.login.recaptcha"
	LoginToken     LoginMethod = "m.login.token"
	LoginOAuth2    LoginMethod = "m.login.oauth2"
	LoginSSO       LoginMethod = "m.login.sso"
	LoginEmail     LoginMethod = "m.login.email.identity"
	LoginPhone     LoginMethod = "m.login.msisdn"
	LoginDummy     LoginMethod = "m.login.dummy"
)

List of official authentications. It can be found here: https://spec.matrix.org/v1.1/client-server-api/#authentication-types.

const (
	LoginAppservice LoginMethod = "uk.half-shot.msc2778.login.application_service"
)

List of famous custom authentications.

func (LoginMethod) FallbackURL

func (l LoginMethod) FallbackURL(authServerHost string, sessionID string) string

FallbackURL generates the URL that the application can open in order to finish the auth process. This can be used when the auth method is not natively supported by the client.

type Presence

type Presence string

Presence represents the status of the client to set while the client is polling.

const (
	PresenceOnline  Presence = "online"
	PresenceOffline Presence = "offline"
	PresenceIdle    Presence = "unavailable"
)

The three possible status to be in are online, offline (invisible) and idle (unavailable).

type PushAction

type PushAction string

PushAction affects if and how a notification is delivered for a matching event.

type PushActionTweak

type PushActionTweak string

PushActionTweak describes an entry key in the Tweaks dictionary that is sent in the notification request to the Push Gateway.

const (
	// SoundActionTweak maps to the sound to be played when this notification arrives. Default means
	// to play the default sound, but could also be something else like vibration.
	SoundActionTweak PushActionTweak = "sound"
	// HighlightActionTweak is a boolean representing whether or not this message should be
	// highlighted in the UI. If this tweak is given with no value, then it's true; if it's missing,
	// then it's false.
	HighlightActionTweak PushActionTweak = "highlight"
)

type PushActions

type PushActions struct {
	Action PushAction
	Tweaks map[PushActionTweak]json.RawMessage
}

PushActions describes the list of actions associated with push rules.

func (PushActions) Highlight

func (a PushActions) Highlight() bool

Highlight returns true if the PushActions has a HighlightAction tweak with a true value. It handles certain edge cases.

func (PushActions) MarshalJSON

func (a PushActions) MarshalJSON() ([]byte, error)

MarshalJSON marshals PushActions into an array.

func (*PushActions) SetTweak

func (a *PushActions) SetTweak(tweak PushActionTweak, value interface{}) error

SetTweak sets a tweak into the Tweaks map. If the map is nil, then it is initialized. If value is nil, then the value property is omitted from the SetTweak object. To delete tweaks, use the delete() built-in. If value is not valid JSON, then an error is returned.

func (*PushActions) UnmarshalJSON

func (a *PushActions) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals an array of push actions into a.

func (PushActions) UnmarshalTweak

func (a PushActions) UnmarshalTweak(tweak PushActionTweak, ptr interface{}) bool

UnmarshalTweak unmarshals the value with the given tweak key into ptr. False is returned if the JSON is invalid, missing or the tweak isn't there.

type PushCondition

type PushCondition struct {
	// Is is required for room_member_count conditions. It is a decimal integer optionally prefixed
	// by one of "==", "<", ">", ">=" or "<=". If no prefix, then "==" is implied. Use the IsCmp
	// method.
	Is string `json:"is,omitempty"`
	// Key is required for:
	//
	//    - EventMatchCondition: it's a dot-separated field of the event to match.
	//    - SenderNotificationPermissionCondition: it's the field in the power level event that the
	//      user needs a minimum power level for.
	Key string `json:"key,omitempty"`
	// Kind is the kind of condition to apply.
	Kind PushConditionKind `json:"kind"`
	// Pattern is required for event_match conditions (Kind). It is the glob-style pattern to match
	// against. Patterns with no special glob characters should be treated as having asterisks
	// prepended and appended when testing the condition.
	Pattern PushPattern `json:"pattern,omitempty"`
}

func (PushCondition) IsCmp

func (c PushCondition) IsCmp(num int) bool

IsCmp parses the Is string and compares it with num.

type PushConditionKind

type PushConditionKind string
const (
	// EventMatchCondition is a glob pattern match on a field of the event. This condition has the
	// fields Key and Pattern.
	EventMatchCondition PushConditionKind = "event_match"
	// ContainsDisplayNameCondition matches unencrypted messages where content.body contains the
	// owner’s display name in that room. This condition has no fields.
	ContainsDisplayNameCondition PushConditionKind = "contains_display_name"
	// RoomMemberCountCondition matches the current number of members in the room. This condition
	// has the Is field. Use IsCmp to compare the count.
	RoomMemberCountCondition PushConditionKind = "room_member_count"
	// SenderNotificationPermissionCondition takes into account the current power levels in the
	// room, ensuring the sender of the event has high enough power to trigger the notification.
	// This condition has the Key field.
	SenderNotificationPermissionCondition PushConditionKind = "sender_notification_permission"
)

type PushPattern

type PushPattern string

PushPattern describes a glob string used to match push rule patterns.

func (PushPattern) Matches

func (p PushPattern) Matches(str string) bool

Matches returns true if str matches the Pattern string.

type PushRule

type PushRule struct {
	// Actions are the actions to perform when this rule is matched.
	Actions PushActions `json:"actions"`
	// Conditions are the conditions that must hold true for an event tin order for a rule to be
	// applied to an event. This only applies to Underride and Override rules.
	Conditions []PushCondition `json:"conditions,omitempty"`
	// Default (required) is true if this is a default rule or has been set explicitly.
	Default bool `json:"default"`
	// Enabled (required) is true if the rule is enabled.
	Enabled bool `json:"enabled"`
	// Pattern is the glob-style pattern to match against. This only applies to Content rules.
	Pattern PushPattern `json:"pattern"`
	// RuleID is the ID of this rule.
	RuleID PushRuleID `json:"rule_id"`
}

PushRule describes a push rule.

type PushRuleID

type PushRuleID string

PushRuleID is the rule ID for a push rule.

func (PushRuleID) IsServerDefault

func (id PushRuleID) IsServerDefault() bool

IsServerDefault returns true if the rule ID identifies a server-default rule.

type PushRules

type PushRules []PushRule

PushRules is a list of push rules.

func (PushRules) EventMatch

func (r PushRules) EventMatch(matchers map[string]string) (PushRule, bool)

EventMatch finds an enabled rule with its Kind being EventMatch and its key being any of the given keys in the map. It then returns the rule if its pattern matches the value of that key along with a true boolean. A zero-value PushRule and false are returned for any other case.

func (PushRules) PatternMatch

func (r PushRules) PatternMatch(str string) (PushRule, bool)

PatternMatches returns true if any of the rules have a pattern that matches value. It behaves similarly to EventMatch, except the Pattern field is used instead.

func (PushRules) Rule

func (r PushRules) Rule(id PushRuleID) (PushRule, bool)

Rule searches for the rule with the given ID.

type PushRuleset

type PushRuleset struct {
	// Override rules are checked first. They're user-configured.
	Override PushRules `json:"override"`
	// Content rules configure behavior for unencrypted messages that match certain patterns.
	Content PushRules `json:"content"`
	// Room rules configure behavior for all messages within a given room. Their rule IDs are always
	// the ID of the rooms that they affect.
	Room PushRules `json:"room"`
	// Sender rules configure behavior for all messages from a specific Matrix user ID. Their rule
	// IDs are always the ID of those users.
	Sender PushRules `json:"sender"`
	// Underride rules are identical to Override rules but have a lower priority than all other
	// types of rules.
	Underride PushRules `json:"underride"`
}

PushRuleset describes the global push ruleset inside a PushRulesEvent.

type RoomID

type RoomID string

RoomID is a magic string that identifies a room.

func (RoomID) Parse

func (roomID RoomID) Parse() (localPart, serverName string, err error)

Parse attempts to split the room ID into the local part and the host name. It does not make any attempt at validating if the local part and the host name is valid.

It returns ErrInvalidRoomID when the ID cannot be made sense of.

type RoomVersionStability

type RoomVersionStability string

RoomVersionStability expresses the stability status of a room version.

const (
	RoomVersionStable   RoomVersionStability = "stable"
	RoomVersionUnstable RoomVersionStability = "unstable"
)

RoomVersionStability can either be "stable" or "unstable".

type Tag

type Tag struct {
	// Ordering information as a number between 0 and 1.
	// Compared such that 0 is displayed first, and an order of `0.2` would
	// come before a room with order `0.7`.
	//
	// If Order is nil, it should appear last.
	Order *float64 `json:"order"`
}

type TagName

type TagName string
var (
	TagFavourite    TagName = "m.favourite"
	TagLowPriority  TagName = "m.lowpriority"
	TagServerNotice TagName = "m.server_notice"
)

Tags defined in the matrix namespace.

func (TagName) HasNamespace

func (t TagName) HasNamespace(n string) bool

HasNamespace returns whether the specified tagname has the namespace.

type Timestamp

type Timestamp int64

Timestamp is a timestamp in milliseconds since Unix time.

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time converts a timestamp into valid Go time.

type URL

type URL string

URL is a URI which is likely to be MXC URI.

type UserID

type UserID string

UserID is a user's full qualified identifier. It includes the preceding @.

func (UserID) Parse

func (userID UserID) Parse() (localPart, serverName string, err error)

Parse attempts to split the user ID into the local part and the host name. It does not make any attempt at validating if the local part and the host name is valid.

It returns ErrInvalidUserID when the ID cannot be made sense of.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL