matrixclient

package module
v0.0.0-...-94d83ac Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

matrixclient

Small Matrix client library for matterircd/matterbridge, modelled on matterclient. Wraps mautrix: password login, sync loop, room/DM/user tracking, send (incl. threads), and message/reaction callbacks through the Handler interface.

Room invitations

Invitations() returns pending invitations for the logged-in user, including direct rooms. Each includes the room ID, inviter (Sender), optional room name, alias and reason, and whether it is direct. Invited rooms are not listed by Rooms() or selected by DirectRoom(), and are never automatically joined.

Implement the optional InviteHandler.OnInvite(*Invitation) to receive new or changed invitations after the initial sync. Invitations received while offline are available through Invitations() when Handler.Ready runs. Read that snapshot once your event consumer is running; initial invitations are not replayed through OnInvite. Deduplicate by room ID if consumer startup overlaps live callbacks. Callbacks run on the sync goroutine and must not block. For compatibility, live self-invites also reach MemberHandler.OnMember with MembershipInvite; use one callback path to avoid duplicate notifications.

Accept with Join(ctx, string(invite.RoomID)); Matrix has no separate accept API. Reject with Leave(ctx, invite.RoomID). Surface request errors to the user; failed requests keep the invitation pending. Successful joins, rejections and revocations remove it from Invitations() when synced. An IRC bridge can render OnInvite as an IRC INVITE and use /join to call Join with the room ID. Accepted direct invitations retain their DM classification across m.direct updates. Rooms observed leaving are excluded from DirectRoom() and Rooms() until they are joined again, even if stale m.direct data still lists them. Their DM classification is retained for final or late-decrypted incoming events and reused when rejoining without a new invitation or m.direct update. Join persists an accepted direct invitation to m.direct so it survives a restart. Restoring DM associations does not add members; room membership follows membership events independently of direct-room classification.

Encrypted rooms

End-to-end encryption is opt-in through the e2ee subpackage, as it needs cgo (sqlite for the key store) and either libolm or the pure Go goolm build tag:

c, err := matrixclient.New(ctx, cred, handler, e2ee.Factory(e2ee.Config{
	DBPath:    "keys.db",
	PickleKey: key,
}))

Build with go build -tags goolm. Keep the database and pickle key, they hold the device keys. Interactive device verification is available through the optional VerificationHandler below; without it the session stays unverified.

Interactive device verification

With e2ee.Factory, implement VerificationHandler.OnVerification(*Verification) on the handler passed to New. This enables mautrix's SAS engine before syncing, including incoming to-device requests received during the initial sync. No cryptography or raw to-device event handling is needed in matterircd.

Queue these callbacks to a separate consumer. They may run concurrently, before Handler.Ready, or while a verification API call holds a transaction lock. Do not call verification methods directly inside the callback, and do not block it waiting for user input. Make the consumer ready before calling New; it may need to wait for New to return before using the client.

Correlate updates and user commands by TransactionID:

Stage What matterircd should display/do
VerificationRequested Show the requesting UserID and DeviceID. Ask the user to accept; call AcceptVerification(ctx, txnID) on acceptance.
VerificationReady Acceptance is complete, not verification. If SupportsSAS, call StartSAS(ctx, txnID) to begin comparing; the peer may also initiate this exchange.
VerificationSAS Display Emojis with EmojiDescriptions, or the three Decimals, in order. Ask whether they match the other device. Call ConfirmSAS(ctx, txnID) only after explicit confirmation.
VerificationCancelled Show CancelCode and Reason, including timeout or cryptographic mismatch, and discard the pending UI.
VerificationDone Report successful verification and discard the pending UI.

For the other client's "Start verification on the other device" screen, either initiate from matterircd with StartVerification(ctx, c.UserID()), or initiate from the other client and accept its VerificationRequested update in matterircd. Outgoing requests go to the user's other devices, not a single device ID; the first device accepting is identified in VerificationReady.DeviceID. Keep the request's user/device information for later updates, which carry the transaction ID but do not repeat all peer information.

To verify another user, call StartInRoomVerification(ctx, roomID, userID) with a direct message room shared with that user. The request is sent in the room rather than to-device; the remaining steps are identical.

Reject or cancel with CancelVerification(ctx, txnID, event.VerificationCancelCodeUser, reason); use event.VerificationCancelCodeSASMismatch if the SAS differs. Surface every API error to the user. Local cancellation succeeds via its return value (there is no additional local callback). Never report success on acceptance or confirmation alone: wait for VerificationDone, after MAC validation and completion.

Verification methods return ErrVerificationUnavailable without a verification handler and a supporting crypto provider. Pending transactions are in memory and cannot be resumed after a restart. QR verification, recovery-key entry and cross-signing private-key recovery are not exposed by this API.

Mattermost concepts

  • Teams are Matrix spaces (Teams, TeamChannels, RoomTeams, CreateTeam, AddToTeam).
  • Matrix has no bot flag, IsBot is true for users that only ever sent m.notice messages.
  • PublicLink gives an unauthenticated media URL, DownloadURL the authenticated one.
  • Ping is skipped while syncs are arriving and Reconnect restarts the sync with a fresh login.

Documentation

Overview

Package matrixclient is a small Matrix client library used by matterircd (and usable by matterbridge), the equivalent of matterclient for Mattermost.

Index

Constants

View Source
const (
	StatusOnline  = "online"
	StatusAway    = "away"
	StatusOffline = "offline"
)

Status values returned by GetStatus, matching matterclient.

Variables

View Source
var ErrVerificationUnavailable = errors.New("matrixclient: interactive verification is not enabled")

ErrVerificationUnavailable means encryption or a VerificationHandler/provider was not enabled when the client was created.

Functions

This section is empty.

Types

type Channel

type Channel struct {
	sync.RWMutex

	ID         id.RoomID
	Name       string
	RawName    string // the room name as set, unlike Name without spaces and with a '#'
	Alias      id.RoomAlias
	AltAliases []id.RoomAlias
	Members    map[id.UserID]*User
	IsDirect   bool
	Encrypted  bool
	Topic      string

	LastActivity int64      // timestamp in milliseconds of the newest message seen, 0 if none
	LastEventID  id.EventID // newest message event seen, set during the initial sync as well

	// DeliveredEventID is the newest message event whose handler call has returned, see
	// Client.LastDeliveredEventID. It trails LastEventID by the events being delivered.
	DeliveredEventID id.EventID
	// contains filtered or unexported fields
}

Channel is a Matrix room.

type Client

type Client struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Client is a logged in Matrix client keeping track of rooms and users.

func New

func New(ctx context.Context, cred Credentials, h Handler, opts ...Option) (*Client, error)

New logs in and starts syncing. Handler.Ready is called after the initial sync.

func (*Client) AcceptVerification

func (c *Client) AcceptVerification(ctx context.Context, txnID id.VerificationTransactionID) error

AcceptVerification accepts an incoming request, but does not trust the device.

func (*Client) AddToTeam

func (c *Client) AddToTeam(ctx context.Context, spaceID, roomID id.RoomID) error

AddToTeam adds a room to a space.

func (*Client) CancelVerification

func (c *Client) CancelVerification(ctx context.Context, txnID id.VerificationTransactionID, code event.VerificationCancelCode, reason string) error

CancelVerification rejects or cancels a transaction. Use event.VerificationCancelCodeSASMismatch when the displayed SAS does not match. A successful local cancellation is reported by the return value, not a callback.

func (*Client) ConfirmSAS

func (c *Client) ConfirmSAS(ctx context.Context, txnID id.VerificationTransactionID) error

ConfirmSAS confirms that the user compared the SAS on both devices and it matches. Wait for VerificationDone before reporting success.

func (*Client) Connected

func (c *Client) Connected() bool

Connected reports whether the client is logged in.

func (*Client) CreateRoom

func (c *Client) CreateRoom(ctx context.Context, name, topic string, public bool, invite ...id.UserID) (id.RoomID, error)

CreateRoom creates a room and invites users. Public rooms get a published alias when name is set. The room shows up in Rooms once it is synced.

func (*Client) CreateTeam

func (c *Client) CreateTeam(ctx context.Context, name, topic string, public bool) (id.RoomID, error)

CreateTeam creates a space.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, roomID id.RoomID, eventID id.EventID) error

Delete redacts an event.

func (*Client) DeleteReaction

func (c *Client) DeleteReaction(ctx context.Context, roomID id.RoomID, reactionID id.EventID) error

DeleteReaction removes a reaction, given the reaction event ID.

func (*Client) DeviceID

func (c *Client) DeviceID() id.DeviceID

DeviceID is the ID of our device, as listed under the sessions of other clients. It is empty when end-to-end encryption is disabled.

func (*Client) DeviceVerified

func (c *Client) DeviceVerified(ctx context.Context) (bool, error)

DeviceVerified reports whether our device is verified or cross-signed and trusted. Trust is resolved from the local crypto store, so verification or revocation done elsewhere is only reflected once sync has stored it. It is false when end-to-end encryption is disabled or the account has no cross-signing. When encryption is enabled, a read-only server request first confirms our device still exists, so connectivity is required. A non-nil error, including a network error, a missing device or an authentication failure, means the state could not be determined, which is not the same as unverified.

func (*Client) DirectRoom

func (c *Client) DirectRoom(userID id.UserID) id.RoomID

DirectRoom returns the direct message room with userID, or "", excluding invitations and departed rooms.

func (*Client) DirectUsers

func (c *Client) DirectUsers(roomID id.RoomID) []id.UserID

DirectUsers returns the users of a direct message room.

func (*Client) DisplayName

func (c *Client) DisplayName(userID id.UserID) string

DisplayName returns the known display name of a user, or "".

func (*Client) Download

func (c *Client) Download(ctx context.Context, mxc id.ContentURIString) ([]byte, error)

Download fetches the media behind an mxc:// URI.

func (*Client) DownloadEncrypted

func (c *Client) DownloadEncrypted(ctx context.Context, file *event.EncryptedFileInfo) ([]byte, error)

DownloadEncrypted fetches and decrypts the media of an encrypted file message.

func (*Client) DownloadURL

func (c *Client) DownloadURL(mxc id.ContentURIString) string

DownloadURL returns the HTTP URL of the media behind an mxc:// URI, or "".

func (*Client) Edit

func (c *Client) Edit(ctx context.Context, roomID id.RoomID, eventID id.EventID, text string) (id.EventID, error)

Edit replaces the text of an event we sent.

func (*Client) EditHTML

func (c *Client) EditHTML(ctx context.Context, roomID id.RoomID, eventID id.EventID, text, html string) (id.EventID, error)

EditHTML is like Edit with an HTML formatted body next to the plain text.

func (*Client) Encrypted

func (c *Client) Encrypted() bool

Encrypted reports whether end-to-end encryption is enabled.

func (*Client) Event

func (c *Client) Event(ctx context.Context, roomID id.RoomID, eventID id.EventID) (*event.Event, error)

Event fetches a single event, retrying once.

func (*Client) Fingerprint

func (c *Client) Fingerprint() string

Fingerprint is the fingerprint of our device's Ed25519 key, for manual verification. It is empty when end-to-end encryption is disabled.

func (*Client) GetMessages

func (c *Client) GetMessages(ctx context.Context, roomID id.RoomID, limit int) ([]*Message, error)

GetMessages returns up to limit of the latest messages of a room, oldest first.

func (*Client) GetMessagesSince

func (c *Client) GetMessagesSince(ctx context.Context, roomID id.RoomID, since int64) ([]*Message, error)

GetMessagesSince returns the messages of a room newer than since (unix milliseconds), oldest first. At most historyMaxPages pages are fetched.

func (*Client) GetStatus

func (c *Client) GetStatus(userID id.UserID) string

GetStatus returns the cached status of a user, "offline" when unknown.

func (*Client) GetThread

func (c *Client) GetThread(ctx context.Context, roomID id.RoomID, rootID id.EventID) ([]*Message, error)

GetThread returns the root message of a thread followed by its replies, oldest first.

func (*Client) GetUserAvatarURL

func (c *Client) GetUserAvatarURL(ctx context.Context, userID id.UserID) string

GetUserAvatarURL returns the HTTP URL of the avatar of a user, see PublicLink, or "" if the user has none.

func (*Client) GetUserCustomStatus

func (c *Client) GetUserCustomStatus(userID id.UserID) string

GetUserCustomStatus returns the cached status message of a user.

func (*Client) GetUserLastActivity

func (c *Client) GetUserLastActivity(userID id.UserID) int64

GetUserLastActivity returns when the user was last active in unix milliseconds, or 0 if unknown.

func (*Client) GetUserLocalTime

func (c *Client) GetUserLocalTime(ctx context.Context, userID id.UserID) string

GetUserLocalTime returns the current time of a user formatted as HH:MM in their timezone (profile field m.tz), or "" if unknown.

func (*Client) HandleRetry

func (c *Client) HandleRetry(ctx context.Context, name string, err error, current, maxLimit int) (bool, error)

HandleRetry decides whether a failed API call should be retried, sleeping before returning true. Rate limits respect the server's retry_after_ms and other 4xx errors are not retried. It returns an error only when ctx is done.

func (*Client) Invitations

func (c *Client) Invitations() []Invitation

Invitations returns a snapshot of pending invitations, including direct rooms. Read it once the consumer is running to display invitations received offline. Joining accepts an invitation; Leave rejects it. A failed request preserves it, and a successful request is reflected when the membership is synced.

func (*Client) Invite

func (c *Client) Invite(ctx context.Context, roomID id.RoomID, userID id.UserID) error

Invite invites userID to a room.

func (*Client) IsBot

func (c *Client) IsBot(userID id.UserID) bool

IsBot reports whether the user only ever sent notices, the Matrix bot convention.

func (*Client) IsDirect

func (c *Client) IsDirect(roomID id.RoomID) bool

IsDirect reports whether roomID is a direct message room.

func (*Client) IsEncrypted

func (c *Client) IsEncrypted(roomID id.RoomID) bool

IsEncrypted reports whether roomID is end-to-end encrypted.

func (*Client) Join

func (c *Client) Join(ctx context.Context, roomIDOrAlias string) (id.RoomID, error)

Join joins a room by ID or alias, accepting a pending invitation if there is one.

func (*Client) JoinedMembers

func (c *Client) JoinedMembers(ctx context.Context, roomID id.RoomID) ([]id.UserID, error)

JoinedMembers returns the joined members of a room.

func (*Client) Kick

func (c *Client) Kick(ctx context.Context, roomID id.RoomID, userID id.UserID, reason string) error

Kick removes userID from a room.

func (*Client) KnownUsers

func (c *Client) KnownUsers() []id.UserID

KnownUsers returns the IDs of all known users.

func (*Client) LastDeliveredEventID

func (c *Client) LastDeliveredEventID(roomID id.RoomID) id.EventID

LastDeliveredEventID returns the newest message event, by timeline position, whose handler call has returned, "" if none. Unlike LastEventID, which advances before the handler is called, it never includes an event the handler has not seen yet, so a consumer that hands events on asynchronously can acknowledge up to it once it has handed over everything the handler returned for. Messages of the initial sync count as delivered, as they are never passed to the handler.

func (*Client) LastEventID

func (c *Client) LastEventID(roomID id.RoomID) id.EventID

LastEventID returns the newest message event seen in a room, "" if none.

func (*Client) LastSync

func (c *Client) LastSync() time.Time

LastSync returns when the last sync response was processed, the zero time if none yet.

func (*Client) LastViewedAt

func (c *Client) LastViewedAt(ctx context.Context, roomID id.RoomID) int64

LastViewedAt returns the timestamp in milliseconds of the event our read marker (m.fully_read) points to, or 0 if the room has none.

func (*Client) Leave

func (c *Client) Leave(ctx context.Context, roomID id.RoomID) error

Leave leaves a room or rejects a pending invitation.

func (*Client) Logout

func (c *Client) Logout()

Logout stops syncing.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks that the homeserver is reachable and our access token is valid. A recent sync response already proves that, so no request is made then.

func (c *Client) PublicLink(mxc id.ContentURIString) string

PublicLink returns an unauthenticated download URL for an mxc:// URI, usable by anyone with the link. Homeservers that only allow authenticated media refuse it, use DownloadURL with an access token there. Returns "" if mxc is invalid.

func (c *Client) PublicLinks(mxcs []id.ContentURIString) []string

PublicLinks is PublicLink for multiple URIs, skipping invalid ones.

func (*Client) React

func (c *Client) React(ctx context.Context, roomID id.RoomID, eventID id.EventID, key string) (id.EventID, error)

React adds a reaction to an event and returns the reaction event ID.

func (*Client) Reconnect

func (c *Client) Reconnect()

Reconnect restarts the sync and logs in again, reusing the device. It returns immediately, the sync goroutine does the work so the access token is never replaced while a request is using it.

func (*Client) RefreshRoomName

func (c *Client) RefreshRoomName(ctx context.Context, roomID id.RoomID) error

RefreshRoomName fetches the name and canonical alias of roomID from the server and applies the ones the room does not have yet. A room the server reports as having neither, by a 404 or by empty content after they were cleared, is marked as such and not healed again, later changes arrive through the sync. Unlike ResolveRoomName it does not report anything.

func (*Client) RemoveFromTeam

func (c *Client) RemoveFromTeam(ctx context.Context, spaceID, roomID id.RoomID) error

RemoveFromTeam removes a room from a space.

func (*Client) ResolveRoomName

func (c *Client) ResolveRoomName(ctx context.Context, roomID id.RoomID) string

ResolveRoomName returns the channel name of roomID, as Rooms lists it. A room known only by its ID is first looked up on the server, bounded by ctx, so a caller can pass a short deadline before creating the channel. It returns "" for an unknown room.

func (*Client) RoomTeams

func (c *Client) RoomTeams(roomID id.RoomID) []id.RoomID

RoomTeams returns the spaces roomID is in.

func (*Client) RoomUsers

func (c *Client) RoomUsers(ctx context.Context, roomID id.RoomID) ([]id.UserID, error)

RoomUsers returns the users of a room. The cached members are used when known, otherwise the joined members are fetched from the homeserver.

func (*Client) Rooms

func (c *Client) Rooms() []RoomInfo

Rooms returns a snapshot of the known rooms (excluding invitations, departed rooms and 1:1 direct rooms).

func (*Client) SearchMessages

func (c *Client) SearchMessages(ctx context.Context, query string) ([]*Message, error)

SearchMessages does a full text search over the messages of the joined rooms, best match first.

func (*Client) SearchUsers

func (c *Client) SearchUsers(ctx context.Context, query string, limit int) ([]UserInfo, error)

SearchUsers searches the homeserver user directory.

func (*Client) Send

func (c *Client) Send(ctx context.Context, roomID id.RoomID, parentID id.EventID, text string) (id.EventID, error)

Send sends a text message, as a thread reply when parentID is set.

func (*Client) SendDirect

func (c *Client) SendDirect(ctx context.Context, userID id.UserID, parentID id.EventID, text string) (id.EventID, error)

SendDirect sends a message to userID, creating the direct room if needed.

func (*Client) SendFile

func (c *Client) SendFile(ctx context.Context, roomID id.RoomID, parentID id.EventID, filename, contentType, caption string, data []byte) (id.EventID, error)

SendFile uploads data and sends it as a file message, with caption as the accompanying text when set. It is a thread reply when parentID is set.

func (*Client) SendTyping

func (c *Client) SendTyping(ctx context.Context, roomID id.RoomID) error

SendTyping sends a typing notification to roomID, at most once per typingDebounce per room.

func (*Client) ServerVersions

func (c *Client) ServerVersions(ctx context.Context) ([]string, error)

ServerVersions returns the Matrix spec versions supported by the homeserver.

func (*Client) SetDisplayName

func (c *Client) SetDisplayName(ctx context.Context, name string) error

SetDisplayName changes our own display name.

func (*Client) SetLogAPICalls

func (c *Client) SetLogAPICalls(level string)

SetLogAPICalls sets the log level of the Matrix API calls. Set to "warn" to log API requests, matching matterclient ("debug" also logs /sync).

func (*Client) SetLogLevel

func (c *Client) SetLogLevel(level string)

SetLogLevel sets the log level of matrixclient.

func (*Client) SetStatus

func (c *Client) SetStatus(ctx context.Context, status, msg string) error

SetStatus sets our own presence ("online", "away" or "offline") and status message.

func (*Client) SetTopic

func (c *Client) SetTopic(ctx context.Context, roomID id.RoomID, topic string) error

SetTopic changes the topic of a room.

func (*Client) StartInRoomVerification

func (c *Client) StartInRoomVerification(ctx context.Context, roomID id.RoomID, userID id.UserID) (id.VerificationTransactionID, error)

StartInRoomVerification requests SAS verification from userID by sending the request into roomID, normally a direct message room shared with that user. Use StartVerification for self-verification.

func (*Client) StartSAS

func (c *Client) StartSAS(ctx context.Context, txnID id.VerificationTransactionID) error

StartSAS begins the key exchange after VerificationReady. Only one side needs to call it; incoming SAS starts are handled automatically.

func (*Client) StartVerification

func (c *Client) StartVerification(ctx context.Context, userID id.UserID) (id.VerificationTransactionID, error)

StartVerification requests SAS verification from a user's other devices. For self-verification pass Client.UserID(). The first device accepting wins; this does not target a single selected device.

func (*Client) TeamByName

func (c *Client) TeamByName(name string) id.RoomID

TeamByName returns the space with the given name (case insensitive), or "".

func (*Client) TeamChannels

func (c *Client) TeamChannels(spaceID id.RoomID) []id.RoomID

TeamChannels returns the rooms in a space.

func (*Client) Teams

func (c *Client) Teams() []RoomInfo

Teams returns the spaces we know of, the Matrix equivalent of Mattermost teams.

func (*Client) Topic

func (c *Client) Topic(roomID id.RoomID) string

Topic returns the cached topic of a room, or "".

func (*Client) UpdateLastViewed

func (c *Client) UpdateLastViewed(ctx context.Context, roomID id.RoomID, eventID id.EventID) error

UpdateLastViewed marks roomID as read up to eventID. Repeated calls for the same event, or within lastViewedDebounce of the previous one, are skipped.

func (*Client) UpdateStatus

func (c *Client) UpdateStatus(ctx context.Context, userID id.UserID) error

UpdateStatus refreshes the cached presence of a user from the homeserver.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, data []byte, filename, contentType string) (id.ContentURI, error)

Upload uploads data to the media repository and returns its mxc:// URI.

func (*Client) UserID

func (c *Client) UserID() id.UserID

UserID is our own user ID.

func (*Client) UserVerified

func (c *Client) UserVerified(ctx context.Context, userID id.UserID) (bool, error)

UserVerified reports whether userID is verified, which is the "secure" state of a WHOIS. For our own user it is DeviceVerified, for others their cross-signing master key must be signed by our user-signing key. Trust is resolved from the local crypto store. It is false when end-to-end encryption is disabled or the user has no known cross-signing keys.

func (*Client) UsernamesInRoom

func (c *Client) UsernamesInRoom(ctx context.Context, roomID id.RoomID) []string

UsernamesInRoom returns the sorted display names of the users in a room, falling back to the localpart of the user ID.

type Credentials

type Credentials struct {
	Server string
	Login  string
	Pass   string

	// Token logs in with an existing access token instead of Login and Pass.
	// The token cannot be renewed, so it is not refreshed once it expires.
	Token string
	// DeviceID is the device the token belongs to. Optional, looked up when empty,
	// and a mismatch with the device the server reports for the token is an error.
	// With e2ee, the key database is bound to this device: a different device
	// fails to start instead of reusing or overwriting the stored keys.
	DeviceID id.DeviceID
	// DeviceName is the session name other clients list for this device, instead of
	// the generated device ID. Optional. It is also applied to an existing device.
	DeviceName string
}

Credentials used to log in to a homeserver.

type Crypto

type Crypto interface {
	mautrix.CryptoHelper

	Close() error
}

Crypto adds end-to-end encryption support to a client. The e2ee subpackage provides an implementation, it is kept separate as it needs cgo (sqlite) and the goolm build tag (or libolm) which not every user wants.

type CryptoFactory

type CryptoFactory func(mc *mautrix.Client, login *mautrix.ReqLogin) (Crypto, error)

CryptoFactory creates a Crypto for mc. The returned Crypto is responsible for logging in with login, so that the device that owns the stored keys is reused.

type DecryptFailureNotifier

type DecryptFailureNotifier interface {
	OnDecryptFailure(f func(ev *event.Event, err error))
}

DecryptFailureNotifier is optionally implemented by a Crypto that reports the messages it gave up decrypting, which are then never delivered. Without it the client expires the ordering data of undelivered encrypted messages by age.

type DeviceVerifier

type DeviceVerifier interface {
	DeviceVerified(ctx context.Context) (bool, error)
}

DeviceVerifier is optionally implemented by a Crypto that can report whether our device is verified and trusted, see Client.DeviceVerified.

type Edit

type Edit struct {
	RoomID    id.RoomID
	EventID   id.EventID
	TargetID  id.EventID // the edited message
	Sender    id.UserID
	Text      string
	Direct    bool
	Timestamp int64
}

Edit is an incoming edit of a message.

type EditHandler

type EditHandler interface {
	OnEdit(e *Edit)
}

EditHandler can optionally be implemented by a Handler to receive edits. Without it, edits are delivered to OnMessage as a message replying to the edited event.

type FingerprintProvider

type FingerprintProvider interface {
	Fingerprint() string
}

FingerprintProvider is optionally implemented by a Crypto that can report the fingerprint of the device's Ed25519 signing key, see Client.Fingerprint.

type Handler

type Handler interface {
	// Ready is called once, after the events of the initial sync were processed.
	// The messages, reactions, redactions and typing events of the initial sync
	// are not delivered, as a handler typically only starts consuming them once
	// Ready was called. Use the history methods to fetch earlier messages.
	Ready()
	OnMessage(msg *Message)
	OnReaction(r *Reaction)
}

Handler receives events from the client. All methods, including Ready, are called from the sync goroutine and must not block for long. The exception are encrypted messages whose room key arrives late: they are delivered from another goroutine once decrypted, possibly after Ready, so a handler must be safe for concurrent use. VerificationHandler has separate concurrency and reentrancy rules; see its documentation.

type Invitation

type Invitation struct {
	RoomID id.RoomID
	Sender id.UserID
	Name   string
	Alias  id.RoomAlias
	Reason string
	Direct bool
}

Invitation is a pending invitation for Client.UserID. Name, Alias and Reason may be empty; RoomID is the authoritative target to pass to Client.Join.

type InviteHandler

type InviteHandler interface {
	OnInvite(invite *Invitation)
}

InviteHandler can optionally be implemented by a Handler to receive new or changed invitations after the initial sync. Initial invitations are available through Client.Invitations when Ready is called. Callbacks must not block.

type MemberChange

type MemberChange struct {
	RoomID     id.RoomID
	UserID     id.UserID
	Sender     id.UserID // who caused the change, differs from UserID on invites, kicks and bans
	Membership event.Membership
	Reason     string
}

MemberChange is a membership change of a user in a room.

type MemberHandler

type MemberHandler interface {
	OnMember(m *MemberChange)
}

MemberHandler can optionally be implemented by a Handler to receive membership changes. Changes from the initial sync are not delivered.

type Message

type Message struct {
	RoomID    id.RoomID
	EventID   id.EventID
	ParentID  id.EventID
	Sender    id.UserID
	Text      string
	Direct    bool
	Timestamp int64
	MsgType   event.MessageType
	URL       id.ContentURIString // mxc:// URI of m.file, m.image, m.audio and m.video messages
	FileName  string
	Info      *event.FileInfo
	File      *event.EncryptedFileInfo // set instead of URL for encrypted media, see Client.DownloadEncrypted
}

Message is an incoming room or direct message. Messages sent by ourselves from other sessions are delivered too, compare Sender with Client.UserID.

type Option

type Option func(*options)

Option configures New.

func WithCrypto

func WithCrypto(f CryptoFactory) Option

WithCrypto enables end-to-end encryption, see the e2ee subpackage.

func WithDefaultProvider

func WithDefaultProvider(provider string) Option

WithDefaultProvider sets the homeserver that is left out of room names: aliases on it are reported without the "/provider" suffix by Rooms, and Join appends it to aliases that have none.

func WithRoomNameResolved

func WithRoomNameResolved(f func(roomID id.RoomID, name string)) Option

WithRoomNameResolved sets the callback for room names healed in the background, the counterpart of matterclient's OnChannelNameResolved. A room that was listed without a name or alias is reported once it has one, unless a RoomNameHandler rename already reported it. It is installed before syncing starts, and is called one at a time and must not block.

func WithSkipTLSVerify

func WithSkipTLSVerify(skip bool) Option

WithSkipTLSVerify disables verification of the homeserver certificate.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the dial and TLS handshake timeout, 10 seconds by default.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header of the API requests.

type PinChange

type PinChange struct {
	RoomID  id.RoomID
	EventID id.EventID
	Sender  id.UserID
	Pinned  bool // false when the message was unpinned
}

PinChange is a message that was pinned or unpinned in a room.

type PinHandler

type PinHandler interface {
	OnPin(p *PinChange)
}

PinHandler can optionally be implemented by a Handler to receive pinned and unpinned messages. Changes from the initial sync are not delivered.

type Presence

type Presence struct {
	Status         string
	StatusMsg      string
	LastActivityAt int64 // unix milliseconds, 0 if unknown
}

Presence is the last known presence of a user.

type Reaction

type Reaction struct {
	RoomID   id.RoomID
	ParentID id.EventID
	Sender   id.UserID
	Key      string
	Direct   bool
}

Reaction is an incoming reaction to an event. Reactions from ourselves are delivered too, compare Sender with Client.UserID.

type Redaction

type Redaction struct {
	RoomID   id.RoomID
	TargetID id.EventID
	Sender   id.UserID
	Direct   bool
	// TargetType is the type of the redacted event, which a redaction keeps. It is
	// event.EventReaction for a removed reaction, and empty when the lookup failed.
	TargetType event.Type
	// IsEdit is true when the redacted event was an edit (m.replace), so the
	// original message still exists. Best effort: homeservers normally prune the
	// relation from a redacted event, false does not guarantee it was not an edit.
	IsEdit bool
}

Redaction is an incoming deletion of an event, which can be a message or a reaction. Redactions from ourselves are delivered too, compare Sender with Client.UserID.

type RedactionHandler

type RedactionHandler interface {
	OnRedaction(r *Redaction)
}

RedactionHandler can optionally be implemented by a Handler to receive deletions.

type RoomInfo

type RoomInfo struct {
	ID       id.RoomID
	Name     string // alias, room name, member names or short ID, with ':' replaced by '/'
	IsDirect bool

	LastActivity int64 // timestamp in milliseconds of the newest message seen, 0 if none
}

RoomInfo is a snapshot of a room.

type RoomNameHandler

type RoomNameHandler interface {
	OnRoomName(r *RoomRename)
}

RoomNameHandler can optionally be implemented by a Handler to be told when the channel name of a room changes through the sync, the counterpart of the channel update event of Mattermost. Only rooms whose name was reported through Client.Rooms or Client.ResolveRoomName are delivered. A name healed in the background is reported through the WithRoomNameResolved callback instead.

type RoomRename

type RoomRename struct {
	// Kind is captured when the event is created, a consumer that queues it must not infer
	// the transition from the live Client.IsDirect, which may have changed since.
	Kind        RoomRenameKind
	RoomID      id.RoomID
	OldName     string
	Name        string
	DisplayName string // the room name as set, empty if it has none
}

RoomRename is a change of the channel name of a room, as listed by Client.Rooms. Like matterircd's ChannelUpdateEvent for Mattermost it carries the room ID, the new channel name and the display name. A consumer is expected to handle it the same way: PART the channel of OldName with "Channel renamed to <Name>", JOIN Name and send a server notice. Direct rooms are never reported, except once when a room that was handed out as a channel turns into one: the consumer is expected to drop the channel of OldName (Kind RoomDropped). Turning back into a channel is reported once as well (Kind RoomRestored), JOIN Name then, OldName is not a channel the consumer holds. Consumers should dispatch on Kind, not on the live Client.IsDirect.

type RoomRenameKind

type RoomRenameKind int

RoomRenameKind tells what a RoomRename reports.

const (
	RoomRenamed  RoomRenameKind = iota // the channel was renamed
	RoomDropped                        // the room turned into a DM, drop the channel of OldName
	RoomRestored                       // the room is a channel again, JOIN Name
)

type RoomVerificationController

type RoomVerificationController interface {
	StartInRoomVerification(ctx context.Context, roomID id.RoomID, userID id.UserID) (id.VerificationTransactionID, error)
}

RoomVerificationController is optionally implemented by a VerificationController that can verify a user in a direct message room.

type TopicChange

type TopicChange struct {
	RoomID id.RoomID
	Sender id.UserID
	Topic  string
}

TopicChange is a room topic change.

type TopicHandler

type TopicHandler interface {
	OnTopic(t *TopicChange)
}

TopicHandler can optionally be implemented by a Handler to receive topic changes. Changes from the initial sync are not delivered.

type Typing

type Typing struct {
	RoomID id.RoomID
	Users  []id.UserID
	Direct bool
}

Typing is the full list of users currently typing in a room, excluding ourselves.

type TypingHandler

type TypingHandler interface {
	OnTyping(t *Typing)
}

TypingHandler can optionally be implemented by a Handler to receive typing notifications.

type User

type User struct {
	*event.MemberEventContent

	ID id.UserID

	Bot bool // see Client.IsBot
	// contains filtered or unexported fields
}

User is a Matrix user as seen in room state.

type UserInfo

type UserInfo struct {
	ID          id.UserID
	DisplayName string
}

UserInfo is a user found in the homeserver user directory.

type UserVerifier

type UserVerifier interface {
	UserVerified(ctx context.Context, userID id.UserID) (bool, error)
}

UserVerifier is optionally implemented by a Crypto that can report whether another user is cross-signing verified by us, see Client.UserVerified.

type Verification

type Verification struct {
	TransactionID id.VerificationTransactionID
	Stage         VerificationStage
	UserID        id.UserID
	DeviceID      id.DeviceID
	SupportsSAS   bool // ready updates

	// SAS updates contain emojis with matching descriptions, decimals, or both.
	Emojis            []rune
	EmojiDescriptions []string
	Decimals          []int

	CancelCode event.VerificationCancelCode
	Reason     string
	Method     event.VerificationMethod // done updates
}

Verification is a verification update. Correlate updates by TransactionID. UserID is set on requests; DeviceID is set on requests and ready updates.

type VerificationController

type VerificationController interface {
	StartVerification(ctx context.Context, userID id.UserID) (id.VerificationTransactionID, error)
	AcceptVerification(ctx context.Context, txnID id.VerificationTransactionID) error
	StartSAS(ctx context.Context, txnID id.VerificationTransactionID) error
	ConfirmSAS(ctx context.Context, txnID id.VerificationTransactionID) error
	CancelVerification(ctx context.Context, txnID id.VerificationTransactionID, code event.VerificationCancelCode, reason string) error
}

VerificationController is the SAS verification engine supplied by a Crypto.

type VerificationHandler

type VerificationHandler interface {
	OnVerification(v *Verification)
}

VerificationHandler optionally receives interactive verification updates. Callbacks may run concurrently, including before Ready and from API calls. They must not block or call verification methods: queue updates for a separate consumer, as the verification engine may hold its transaction lock.

type VerificationProvider

type VerificationProvider interface {
	InitVerification(ctx context.Context, notify func(*Verification)) (VerificationController, error)
}

VerificationProvider is optionally implemented by a Crypto. InitVerification is called after Crypto.Init, before syncing, only with a VerificationHandler.

type VerificationStage

type VerificationStage string

VerificationStage describes a user-visible step of interactive verification.

const (
	VerificationRequested VerificationStage = "requested"
	VerificationReady     VerificationStage = "ready"
	VerificationSAS       VerificationStage = "sas"
	VerificationCancelled VerificationStage = "canceled"
	VerificationDone      VerificationStage = "done"
)

Directories

Path Synopsis
Package e2ee enables end-to-end encrypted rooms for matrixclient.
Package e2ee enables end-to-end encrypted rooms for matrixclient.

Jump to

Keyboard shortcuts

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