Merge pull request #7426 from element-hq/feature/bma/documentation

Add KDoc to all the interfaces of the api modules
This commit is contained in:
Benoit Marty
2026-08-14 13:46:28 +02:00
committed by GitHub
187 changed files with 2750 additions and 37 deletions
@@ -10,6 +10,8 @@ package io.element.android.libraries.matrix.api
/**
* Provides information about the capabilities of the homeserver.
*
* The getters read a snapshot held by the SDK rather than querying the server on each call, so [refresh] must be used to pick up server-side changes.
*
* Spec: https://spec.matrix.org/latest/client-server-api/#capabilities-negotiation
*/
interface HomeserverCapabilitiesProvider {
@@ -54,47 +54,189 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import java.util.Optional
/**
* Entry point for everything scoped to a single logged in session: the sub-services, room access, and account level operations.
*
* One instance exists per session, created on login or session restore and torn down by [logout], [clearCache] or account deactivation.
* Suspending members here report failures through a [Result] instead of throwing, and run their work off the main thread.
*/
interface MatrixClient : UrlContentFetcher {
/** Identifier of the logged in user; a [SessionId] and a [UserId] are the same value. */
val sessionId: SessionId
/** Identifier of this device, as assigned by the homeserver when the session was created. */
val deviceId: DeviceId
/** Base URL of the homeserver this client is connected to. */
val homeserverUrl: String
/** Directories holding this session's databases, caches and downloaded media. */
val sessionPaths: SessionPaths
/**
* Display name and avatar of the logged in user.
* Seeded from the local session store so a value is available before the first network fetch, then kept up to date by the SDK.
*/
val userProfile: StateFlow<MatrixUser>
/** Gives access to the list of rooms the user is a member of, or has been invited to. */
val roomListService: RoomListService
/** Gives access to the spaces the user belongs to and their hierarchy. */
val spaceService: SpaceService
/** Controls the sync loop of this session and exposes its state. */
val syncService: SyncService
/** Handles verifying this session against the user's other devices or their recovery key. */
val sessionVerificationService: SessionVerificationService
/** Manages the push gateways (pushers) registered on the homeserver for this session. */
val pushersService: PushersService
/** Resolves incoming push notifications into renderable events. */
val notificationService: NotificationService
/** Reads and writes the push notification rules of the account. */
val notificationSettingsService: NotificationSettingsService
/** Gives access to end-to-end encryption state, recovery and key backup. */
val encryptionService: EncryptionService
/** Gives access to the public room directory of the homeserver. */
val roomDirectoryService: RoomDirectoryService
/** Whether this live client was built with a message search index attached. */
val isMessageSearchAvailable: Boolean
/** Searches messages in the local index; only usable when [isMessageSearchAvailable] is `true`. */
val messageSearchService: MessageSearchService
/** Reads and writes the account settings controlling whether media previews and avatars are shown. */
val mediaPreviewService: MediaPreviewService
/** Downloads media content, thumbnails and files from the homeserver, caching them on disk. */
val matrixMediaLoader: MatrixMediaLoader
/**
* Coroutine scope tied to the lifetime of this session, to be used for work that must stop when the session goes away.
* It is cancelled when the session is logged out or otherwise destroyed, so never use it for work that must outlive the session.
*/
val sessionCoroutineScope: CoroutineScope
/** The users the logged in user has ignored; starts empty and is updated by the SDK, including with an initial value. */
val ignoredUsersFlow: StateFlow<ImmutableList<UserId>>
/** Notifies of membership changes the current user makes, so that callers can react to leaving or joining a room. */
val roomMembershipObserver: RoomMembershipObserver
/** Emits updates about the live location beacons published by the current user. */
val ownBeaconInfoUpdates: Flow<BeaconInfoUpdate>
/** Scans media content before it is displayed, or `null` when no content scanner is configured for this session. */
val contentScanner: ContentScanner?
/**
* Returns the room with the given id if the user has joined it, along with its live [Timeline].
* A new instance is created on each call and the caller owns it, so it must be closed once no longer needed.
*
* @param roomId the id of the room to open.
* @return the room, or `null` if it is unknown to the client or the user is not joined.
*/
suspend fun getJoinedRoom(roomId: RoomId): JoinedRoom?
/**
* Returns the room with the given id whatever the current membership is, without building a timeline.
* As with [getJoinedRoom], a new instance is created on each call and must be closed by the caller.
*
* @param roomId the id of the room to open.
* @return the room, or `null` if it is unknown to the client.
*/
suspend fun getRoom(roomId: RoomId): BaseRoom?
/**
* Looks for an existing direct message room shared with [userId].
*
* @param userId the other member of the direct message room.
* @return the room id, or `null` if no direct message room exists with this user.
*/
suspend fun findDM(userId: UserId): Result<RoomId?>
/**
* Returns the ids of every room the user has joined, as currently known by the client.
* Invited, knocked and left rooms are excluded.
*/
suspend fun getJoinedRoomIds(): Result<Set<RoomId>>
/**
* Adds [userId] to the ignore list of the account, which hides their events and makes [ignoredUsersFlow] emit.
*
* @param userId the user to ignore.
*/
suspend fun ignoreUser(userId: UserId): Result<Unit>
/**
* Removes [userId] from the ignore list of the account, which makes [ignoredUsersFlow] emit.
*
* @param userId the user to stop ignoring.
*/
suspend fun unignoreUser(userId: UserId): Result<Unit>
/**
* Creates a room, applying the app's default power levels on top of [createRoomParams].
* Waits a short while for the new room to come back through sync, but a timeout there is only logged: the result is still a success.
*
* @param createRoomParams the name, topic, preset, invitees and other settings of the room to create.
*/
suspend fun createRoom(createRoomParams: CreateRoomParameters): Result<RoomId>
/**
* Creates a direct message room with [userId], as a private, invite-only room with the user already invited.
* This does not check whether such a room already exists; use [findDM] first if you want to reuse one.
*
* @param userId the user to start the direct message with.
* @param isEncrypted whether the room should have end-to-end encryption enabled.
*/
suspend fun createDM(userId: UserId, isEncrypted: Boolean): Result<RoomId>
/**
* Fetches the current profile of any user from the homeserver, bypassing the local cache.
*
* @param userId the user whose profile is requested.
*/
suspend fun getProfile(userId: UserId): Result<MatrixUser>
/**
* Searches the homeserver's user directory.
*
* @param searchTerm the text to look for in user ids and display names.
* @param limit the maximum number of results to return.
*/
suspend fun searchUsers(searchTerm: String, limit: Long): Result<MatrixSearchUserResults>
/**
* Changes the display name of the logged in user on the homeserver.
*
* @param displayName the new display name.
*/
suspend fun setDisplayName(displayName: String): Result<Unit>
/**
* Uploads [data] as the new avatar of the logged in user.
*
* @param mimeType the MIME type of the image, for instance `image/jpeg`.
* @param data the raw bytes of the image.
*/
suspend fun uploadAvatar(mimeType: String, data: ByteArray): Result<Unit>
/** Removes the avatar of the logged in user. */
suspend fun removeAvatar(): Result<Unit>
/**
* Sets the `m.status` profile field of the logged in user (MSC4426), refreshing [userProfile] if the server does not push the change itself.
*
* @param status the status to publish.
*/
suspend fun setUserStatus(status: UserStatus): Result<Unit>
/** Clears both m.status and m.call profile fields (maps to DELETE on the profile endpoint per MSC4426). */
@@ -103,16 +245,52 @@ interface MatrixClient : UrlContentFetcher {
/** Whether the homeserver advertises support for user status (MSC4426). */
suspend fun isUserStatusSupported(): Result<Boolean>
/** Enable or disable automatically setting the user's status to "in a call" (m.call) while in a call. */
/**
* Enable or disable automatically setting the user's status to "in a call" (m.call) while in a call.
*
* @param enabled whether the status should be maintained automatically.
*/
fun enableAutomaticCallStatus(enabled: Boolean)
/**
* Joins a room the client already knows about, then waits briefly for the new membership to arrive through sync.
* The returned [RoomInfo] is `null` when that wait times out, which is not treated as a failure: the join itself succeeded.
*
* @param roomId the id of the room to join.
*/
suspend fun joinRoom(roomId: RoomId): Result<RoomInfo?>
/**
* Joins a room by id or by alias, resolving it through [serverNames] when the client does not know it yet.
* As with [joinRoom], the returned [RoomInfo] is `null` if the membership did not arrive through sync in time.
*
* @param roomIdOrAlias the id or the alias of the room to join.
* @param serverNames servers to ask about the room, used when it cannot be resolved locally.
*/
suspend fun joinRoomByIdOrAlias(roomIdOrAlias: RoomIdOrAlias, serverNames: List<String>): Result<RoomInfo?>
/**
* Sends a request to join a room whose join rule is knock, then waits briefly for the knocked membership to arrive through sync.
* As with [joinRoom], the returned [RoomInfo] is `null` if that wait times out.
*
* @param roomIdOrAlias the id or the alias of the room to knock on.
* @param message the reason shown to the room moderators; may be empty.
* @param serverNames servers to ask about the room, used when it cannot be resolved locally.
*/
suspend fun knockRoom(roomIdOrAlias: RoomIdOrAlias, message: String, serverNames: List<String>): Result<RoomInfo?>
/**
* Returns the number of bytes this session occupies on disk that [clearCache] would be able to reclaim.
* This covers the cache directory, the state database and the message search index, but not the crypto database.
*/
suspend fun getCacheSize(): Long
/** Returns the size of each individual store the SDK maintains for this session, as reported by the SDK. */
suspend fun getDatabaseSizes(): Result<SdkStoreSizes>
/**
* Will close the client and delete the cache data.
* Deletes the cached data of this session and destroys the client.
* The instance is unusable afterwards, so callers are expected to restart the session, unlike with [logout] the session itself is kept.
*/
suspend fun clearCache()
@@ -125,29 +303,56 @@ interface MatrixClient : UrlContentFetcher {
suspend fun logout(userInitiated: Boolean, ignoreSdkError: Boolean)
/**
* Retrieve the user profile, will also eventually emit a new value to [userProfile].
* Retrieve the profile of the logged in user, emitting it to [userProfile] and persisting it in the local session store on success.
*/
suspend fun getUserProfile(): Result<MatrixUser>
/**
* Returns the web URL where the user can manage their account on the authentication provider, or `null` if the homeserver exposes none.
*
* @param action an optional section of the account management page to open directly, such as changing the password.
*/
suspend fun getAccountManagementUrl(action: AccountManagementAction?): Result<String?>
/**
* Uploads arbitrary content to the homeserver's media repository.
*
* @param mimeType the MIME type of the content being uploaded.
* @param data the raw bytes to upload.
* @return the `mxc://` URI the content is now available at.
*/
suspend fun uploadMedia(mimeType: String, data: ByteArray): Result<String>
/**
* Get a room info flow for a given room ID.
* The flow will emit a new value whenever the room info is updated.
* The flow will emit Optional.empty item if the room is not found.
* The flow will emit a new value whenever the room info is updated, skipping duplicates, and an empty [Optional] if the room is not found.
*
* @param roomId the id of the room to observe.
*/
fun getRoomInfoFlow(roomId: RoomId): Flow<Optional<RoomInfo>>
/**
* Whether [userId] is the logged in user, `false` for a `null` value.
*
* @param userId the user id to compare against this session's user.
*/
fun isMe(userId: UserId?) = userId == sessionId
/**
* Adds a room to the account's list of recently visited rooms, which backs the room suggestions when sharing or forwarding.
*
* @param roomId the id of the room that was just visited.
*/
suspend fun trackRecentlyVisitedRoom(roomId: RoomId): Result<Unit>
/** Returns the recently visited rooms of the account, most recent first. */
suspend fun getRecentlyVisitedRooms(): Result<List<RoomId>>
/**
* Resolves the given room alias to a roomID (and a list of servers), if possible.
* @param roomAlias the room alias to resolve
* @return the resolved room alias if any, an empty result if not found,or an error if the resolution failed.
*
* @param roomAlias the room alias to resolve.
* @return the resolved room alias if any, an empty result if not found, or an error if the resolution failed.
*/
suspend fun resolveRoomAlias(roomAlias: RoomAlias): Result<Optional<ResolvedRoomAlias>>
@@ -158,6 +363,8 @@ interface MatrixClient : UrlContentFetcher {
* event with it failed (e.g. sending an event via the Timeline),
* so it's required to manually re-enable it as soon as
* connectivity is back on the device.
*
* @param enabled whether the send queues of every room should be enabled.
*/
suspend fun setAllSendQueuesEnabled(enabled: Boolean)
@@ -175,6 +382,9 @@ interface MatrixClient : UrlContentFetcher {
/**
* Get a room preview for a given room ID or alias. This is especially useful for rooms that the user is not a member of, or hasn't joined yet.
*
* @param roomIdOrAlias the id or the alias of the room to preview.
* @param serverNames servers to ask about the room, used when it cannot be resolved locally.
*/
suspend fun getRoomPreview(roomIdOrAlias: RoomIdOrAlias, serverNames: List<String>): Result<NotJoinedRoom>
@@ -183,11 +393,21 @@ interface MatrixClient : UrlContentFetcher {
*/
suspend fun currentSlidingSyncVersion(): Result<SlidingSyncVersion>
/** Whether this account can be deactivated from the app, which depends on the authentication method used by the homeserver. */
fun canDeactivateAccount(): Boolean
/**
* Deactivates the account on the homeserver, then destroys this client and deletes every local trace of the session.
* The password is only sent if the homeserver asks for re-authentication, and on failure the session is left untouched.
*
* @param password the account password, required to confirm the deactivation.
* @param eraseData whether the homeserver should also erase the messages the user sent.
*/
suspend fun deactivateAccount(password: String, eraseData: Boolean): Result<Unit>
/**
* Check if the user can report a room.
* Whether the homeserver supports reporting a whole room, rather than individual events.
* Returns `false` if the capability cannot be determined.
*/
suspend fun canReportRoom(): Boolean
@@ -208,16 +428,23 @@ interface MatrixClient : UrlContentFetcher {
/**
* Adds an emoji to the list of recent emoji reactions for this account.
*
* @param emoji the emoji that was just used.
*/
suspend fun addRecentEmoji(emoji: String): Result<Unit>
/**
* Returns the raw JSON content of the global account data event of type [eventType], or null if it is not set.
*
* @param eventType the Matrix event type of the account data to read, for instance `m.direct`.
*/
suspend fun getAccountData(eventType: String): Result<String?>
/**
* Sets the global account data event of type [eventType] to the raw JSON [content].
*
* @param eventType the Matrix event type of the account data to write.
* @param content the new content, as a raw JSON object.
*/
suspend fun setAccountData(eventType: String, content: String): Result<Unit>
@@ -226,6 +453,9 @@ interface MatrixClient : UrlContentFetcher {
*
* This method should be used with caution as providing the [eventId] ourselves can result in incorrect read receipts.
* Use [Timeline.markAsRead] instead when possible.
*
* @param roomId the id of the room to mark as read.
* @param eventId the event up to which the room is considered read.
*/
suspend fun markRoomAsFullyRead(roomId: RoomId, eventId: EventId): Result<Unit>
@@ -252,6 +482,7 @@ interface MatrixClient : UrlContentFetcher {
/**
* Performs a database optimization that should flush cached data and improve performance.
* A periodic background job already calls this for every session, so callers rarely need to trigger it by hand.
*/
suspend fun performDatabaseVacuum(): Result<Unit>
@@ -260,6 +491,7 @@ interface MatrixClient : UrlContentFetcher {
*/
suspend fun resetWellKnownConfig(): Result<Unit>
/** Returns a provider for the capabilities the homeserver advertises, such as whether the display name can be changed. */
fun homeserverCapabilities(): HomeserverCapabilitiesProvider
}
@@ -10,18 +10,26 @@ package io.element.android.libraries.matrix.api
import io.element.android.libraries.matrix.api.core.SessionId
/**
* In-memory cache of the [MatrixClient] of every logged in session.
*
* Prefer injecting the [MatrixClient] directly: this provider is meant for the entry points that only know a [SessionId], such as push handling and workers.
*/
interface MatrixClientProvider {
/**
* Can be used to get or restore a MatrixClient with the given [SessionId].
* If a [MatrixClient] is already in memory, it'll return it. Otherwise it'll try to restore one.
* Most of the time you want to use injected constructor instead of retrieving a MatrixClient with this provider.
* Returns the cached [MatrixClient] for [sessionId], restoring the session from storage and starting its sync if it is not in memory yet.
* Concurrent calls are serialised, so only one restore happens per session.
*
* @param sessionId the [SessionId] of the session to get or restore.
* @return the client, or a failure if the session could not be restored.
*/
suspend fun getOrRestore(sessionId: SessionId): Result<MatrixClient>
/**
* Can be used to retrieve an existing [MatrixClient] with the given [SessionId].
* @param sessionId the [SessionId] of the [MatrixClient] to retrieve.
* @return the [MatrixClient] if it exists.
* Returns the [MatrixClient] for [sessionId] only if it is already in memory, without attempting to restore it.
*
* @param sessionId the [SessionId] of the session to retrieve.
* @return the cached client, or `null` if that session is not currently held in memory.
*/
fun getOrNull(sessionId: SessionId): MatrixClient?
}
@@ -8,6 +8,14 @@
package io.element.android.libraries.matrix.api
/**
* Exposes build information about the bundled `matrix-rust-sdk`.
*
* Mostly used to identify the exact SDK revision in bug reports and in the user agent.
*/
interface SdkMetadata {
/**
* The full git SHA of the commit the bundled `matrix-rust-sdk` was built from.
*/
val sdkGitSha: String
}
@@ -11,5 +11,11 @@ package io.element.android.libraries.matrix.api
* Factory to create a temporary [TemporaryMatrixClient] for a given home server URL.
*/
interface TemporaryMatrixClientFactory {
/**
* Builds an unauthenticated client pointing at [homeServerUrl], backed by a fresh set of temporary session directories.
* The caller owns the returned client and must close it to delete those directories.
*
* @param homeServerUrl the URL of the homeserver the client will talk to.
*/
suspend fun create(homeServerUrl: String): Result<TemporaryMatrixClient>
}
@@ -9,6 +9,14 @@ package io.element.android.libraries.matrix.api.analytics
import io.element.android.libraries.matrix.api.core.SessionId
/**
* Reads the on-disk size of a session's SDK stores, so they can be reported as analytics.
*/
fun interface GetDatabaseSizesUseCase {
/**
* Returns the size of each store of the given session.
*
* @param sessionId the session whose stores are measured.
*/
operator fun invoke(sessionId: SessionId): Result<SdkStoreSizes>
}
@@ -16,23 +16,41 @@ import io.element.android.libraries.matrix.api.auth.qrlogin.QrCodeLoginStep
import io.element.android.libraries.matrix.api.core.SessionId
import io.element.android.libraries.matrix.api.core.UserId
/**
* Creates and restores sessions: password login, OAuth login, QR code login, and importing a session from another client.
*
* [setHomeserver] must be called before any login attempt, since it is what tells the SDK which server to authenticate against.
* Every successful login stores the session and notifies the listeners registered through [listenToNewMatrixClients].
*/
interface MatrixAuthenticationService {
/**
* Restore a session from a [sessionId].
* Do not restore anything it the access token is not valid anymore.
* Generally this method should not be used directly, prefer using [MatrixClientProvider.getOrRestore] instead.
*
* @param sessionId the session to restore.
*/
suspend fun restoreSession(sessionId: SessionId): Result<MatrixClient>
/**
* Set the homeserver to use for authentication, and return its details.
*
* @param homeserver the homeserver URL or server name to authenticate against.
*/
suspend fun setHomeserver(homeserver: String): Result<MatrixHomeServerDetails>
/**
* Logs in with a password on the homeserver previously set through [setHomeserver].
*
* @param username the user id or its local part.
* @param password the account password.
*/
suspend fun login(username: String, password: String): Result<SessionId>
/**
* Import a session that was created using another client, for instance Element Web.
*
* @param externalSession the tokens and identifiers of the session to import.
*/
suspend fun importCreatedSession(externalSession: ExternalSession): Result<SessionId>
@@ -42,6 +60,9 @@ interface MatrixAuthenticationService {
/**
* Get the OAuth url to display to the user.
*
* @param prompt whether the authentication server should show the sign-in or the account-creation page.
* @param loginHint the user identifier to pre-fill on that page, or `null` to leave it empty.
*/
suspend fun getOAuthUrl(
prompt: OAuthPrompt,
@@ -55,11 +76,17 @@ interface MatrixAuthenticationService {
/**
* Set the existing data about Element Classic session, if any.
*
* @param session the session found in a local Element Classic install, or `null` when there is none to migrate.
*/
fun setElementClassicSession(session: ElementClassicSession?)
/**
* Check if the provided secrets from Element Classic session contain a key backup.
*
* @param userId the user the secrets belong to.
* @param secrets the raw secrets exported from Element Classic.
* @param backupInfo the raw backup description exported alongside them.
*/
fun doSecretsContainBackupKey(
userId: UserId,
@@ -69,11 +96,23 @@ interface MatrixAuthenticationService {
/**
* Attempt to log in using the [callbackUrl] provided by the OAuth page.
*
* @param callbackUrl the redirect URL the authentication server sent the user back to, carrying the authorization code.
*/
suspend fun loginWithOAuth(callbackUrl: String): Result<SessionId>
/**
* Logs in by acting on a QR code shown by an already signed in device, reporting each step of the exchange as it happens.
*
* @param qrCodeData the decoded QR code, obtained from [io.element.android.libraries.matrix.api.auth.qrlogin.MatrixQrCodeLoginDataFactory].
* @param progress called on every step of the flow, so the UI can follow along.
*/
suspend fun loginWithQrCode(qrCodeData: MatrixQrCodeLoginData, progress: (QrCodeLoginStep) -> Unit): Result<SessionId>
/** Listen to new Matrix clients being created on authentication. */
/**
* Listen to new Matrix clients being created on authentication.
*
* @param lambda called with each client created by a successful login or session restore.
*/
fun listenToNewMatrixClients(lambda: (MatrixClient) -> Unit)
}
@@ -8,6 +8,10 @@
package io.element.android.libraries.matrix.api.auth
/**
* Provides the redirect URL registered for OAuth login, which the authentication server sends the user back to once they have signed in.
*/
interface OAuthRedirectUrlProvider {
/** Returns the redirect URL, built from the app's custom URL scheme so that the system hands the callback back to the app. */
fun provide(): String
}
@@ -8,6 +8,12 @@
package io.element.android.libraries.matrix.api.auth.qrlogin
/**
* The decoded content of a login QR code, as produced by [MatrixQrCodeLoginDataFactory].
*
* The underlying data is opaque to the app: it is passed back to the SDK to perform the login.
*/
interface MatrixQrCodeLoginData {
/** The homeserver advertised by the QR code, or `null` when it does not carry one. */
fun serverName(): String?
}
@@ -8,6 +8,14 @@
package io.element.android.libraries.matrix.api.auth.qrlogin
/**
* Decodes the raw bytes of a scanned QR code into login data the SDK can use.
*/
interface MatrixQrCodeLoginDataFactory {
/**
* Parses the scanned bytes, failing with a [QrCodeDecodeException] when they are not a valid Matrix login QR code.
*
* @param data the raw content read from the QR code.
*/
fun parseQrCodeData(data: ByteArray): Result<MatrixQrCodeLoginData>
}
@@ -8,6 +8,15 @@
package io.element.android.libraries.matrix.api.core
/**
* Reports the progress of a long running transfer, such as a media upload or download.
*/
interface ProgressCallback {
/**
* Called as the transfer advances, possibly many times and from a background thread.
*
* @param current the number of bytes transferred so far.
* @param total the total number of bytes to transfer.
*/
fun onProgress(current: Long, total: Long)
}
@@ -8,6 +8,10 @@
package io.element.android.libraries.matrix.api.core
/**
* A handle on an event sitting in a room's send queue, obtained from a timeline item that failed to send.
*/
fun interface SendHandle {
/** Puts the event back in the send queue for another attempt. */
suspend fun retry(): Result<Unit>
}
@@ -14,13 +14,32 @@ import io.element.android.libraries.matrix.api.encryption.identity.IdentityState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
/**
* Gives access to the end-to-end encryption state of the session: key backup, recovery, and the trust of other users' identities.
*/
interface EncryptionService {
/**
* The state of the room key backup on the server.
* Reports [BackupState.WAITING_FOR_SYNC] for as long as the session is not actively syncing, since the real state is unknown until then.
*/
val backupStateStateFlow: StateFlow<BackupState>
/**
* The state of recovery, i.e. whether the secrets needed to restore the keys on a new device are available.
* As with [backupStateStateFlow], it reports a waiting-for-sync state until the session is syncing.
*/
val recoveryStateStateFlow: StateFlow<RecoveryState>
/** Progress of the [enableRecovery] call currently in flight, to be observed while that call is running. */
val enableRecoveryProgressStateFlow: StateFlow<EnableRecoveryProgress>
/** Whether this is the only device of the account, which matters because logging out of it can make the room keys unrecoverable. */
val isLastDevice: StateFlow<Boolean>
/** Whether the account has another device this one could be verified against; it stays loading until the first answer arrives. */
val hasDevicesToVerifyAgainst: StateFlow<AsyncData<Boolean>>
/** Enables the room key backup on the server, so that the keys survive losing every device. */
suspend fun enableBackups(): Result<Unit>
/**
@@ -39,12 +58,16 @@ interface EncryptionService {
*/
suspend fun resetRecoveryKey(): Result<String>
/** Disables recovery, which deletes the secrets from server-side storage; the key backup itself is left in place. */
suspend fun disableRecovery(): Result<Unit>
/** Whether a room key backup currently exists on the server, whether or not this device is the one using it. */
suspend fun doesBackupExistOnServer(): Result<Boolean>
/**
* Note: accept both recoveryKey and passphrase.
* Restores the secrets from server-side storage, which unlocks the room key backup for this device.
*
* @param recoveryKey the recovery key, or the passphrase it was derived from; both are accepted.
*/
suspend fun recover(recoveryKey: String): Result<Unit>
@@ -72,6 +95,8 @@ interface EncryptionService {
/**
* Remember this identity, ensuring it does not result in a pin violation.
*
* @param userId the user whose current identity should be pinned.
*/
suspend fun pinUserIdentity(userId: UserId): Result<Unit>
@@ -81,6 +106,8 @@ interface EncryptionService {
* Useful when a user that was verified is not anymore, but it is not
* possible to re-verify immediately. This allows to restore communication by reverting the
* user trust from verified to TOFU verified.
*
* @param userId the user whose verification should be withdrawn.
*/
suspend fun withdrawVerification(userId: UserId): Result<Unit>
@@ -7,6 +7,9 @@
package io.element.android.libraries.matrix.api.linknewdevice
/**
* Lets the user confirm the two-digit check code displayed by the device being linked, which proves the channel is not being intercepted.
*/
interface CheckCodeSender {
/**
* Validates the given [code]. Returns true if the code is valid, false otherwise.
@@ -7,7 +7,15 @@
package io.element.android.libraries.matrix.api.linknewdevice
/**
* Lets the user confirm or refuse a device linking request once they have approved it in the browser.
*
* Handed out with the step that is waiting for authorisation; exactly one of the two methods is meant to be called.
*/
interface ContinuationMessageSender {
/** Tells the other device that the user refused the linking, which ends the flow. */
suspend fun cancel(): Result<Unit>
/** Tells the other device that the user approved the linking, so the flow can carry on. */
suspend fun confirm(): Result<Unit>
}
@@ -10,8 +10,22 @@ package io.element.android.libraries.matrix.api.linknewdevice
import io.element.android.libraries.matrix.api.auth.qrlogin.QrCodeDecodeException
import kotlinx.coroutines.flow.StateFlow
/**
* Drives the linking of a new device that cannot scan a QR code, such as a desktop: this device scans the code the other one displays.
*
* Progress is reported entirely through [linkDesktopStep]; there is one handler per attempt, obtained from
* [io.element.android.libraries.matrix.api.MatrixClient.createLinkDesktopHandler].
*/
interface LinkDesktopHandler {
/** Each step of the flow, from establishing the secure channel to syncing the secrets to the new device. */
val linkDesktopStep: StateFlow<LinkDesktopStep>
/**
* Runs the whole flow from the QR code just scanned, suspending until it finishes or fails.
* A code that cannot be decoded is reported as an invalid-QR-code step rather than as a thrown error.
*
* @param data the raw content read from the QR code shown by the other device.
*/
suspend fun handleScannedQrCode(data: ByteArray)
}
@@ -9,8 +9,17 @@ package io.element.android.libraries.matrix.api.linknewdevice
import kotlinx.coroutines.flow.Flow
/**
* Drives the linking of a new device that is able to scan a QR code, by showing one on this already signed in device.
*
* Progress is reported entirely through [linkMobileStep]; there is one handler per attempt, obtained from
* [io.element.android.libraries.matrix.api.MatrixClient.createLinkMobileHandler].
*/
interface LinkMobileHandler {
/** Each step of the flow, from generating the QR code to syncing the secrets to the new device. */
val linkMobileStep: Flow<LinkMobileStep>
/** Runs the whole flow, suspending until it finishes or fails; the outcome is reported through [linkMobileStep]. */
suspend fun start()
}
@@ -8,6 +8,9 @@
package io.element.android.libraries.matrix.api.media
/**
* Fetches media content from the homeserver, decrypting it on the way when the room is encrypted.
*/
interface MatrixMediaLoader {
/**
* @param source to fetch the content for.
@@ -16,6 +16,7 @@ import java.io.File
* When closed the file will be removed from the disk unless [persist] has been used.
*/
interface MediaFile : Closeable {
/** The absolute path of the file on disk; see [toFile] to get a [File] instead. */
fun path(): String
/**
@@ -10,6 +10,11 @@ package io.element.android.libraries.matrix.api.media
import kotlinx.coroutines.flow.StateFlow
/**
* Reads and writes the account settings that decide whether media previews and invite avatars are shown.
*
* These are account data settings shared across clients, so the local value is only updated once the server has accepted the change.
*/
interface MediaPreviewService {
/**
* Will fetch the media preview config from the server.
@@ -24,11 +29,15 @@ interface MediaPreviewService {
/**
* Set the media preview display policy. This will update the value on the server and update the local value when successful.
*
* @param mediaPreviewValue whether media previews are shown always, never, or only in private rooms.
*/
suspend fun setMediaPreviewValue(mediaPreviewValue: MediaPreviewValue): Result<Unit>
/**
* Set the invite avatars display policy. This will update the value on the server and update the local value when successful.
*
* @param hide true to hide the avatars of users and rooms the user has been invited by.
*/
suspend fun setHideInviteAvatars(hide: Boolean): Result<Unit>
}
@@ -8,6 +8,9 @@
package io.element.android.libraries.matrix.api.mxc
/**
* Helpers to work with Matrix Content (`mxc://`) URIs.
*/
interface MxcTools {
/**
* Sanitizes an mxcUri to be used as a relative file path.
@@ -24,6 +24,9 @@ typealias GetNotificationDataResult = Result<Map<EventId, Result<NotificationDat
interface NotificationService {
/**
* Fetch notifications for the specified event ids in the given rooms.
* Each event is resolved independently, so a partial answer is normal: see [GetNotificationDataResult] for how the two failure levels differ.
*
* @param ids the events to resolve, grouped by the room they belong to.
*/
suspend fun getNotifications(ids: Map<RoomId, List<EventId>>): GetNotificationDataResult
}
@@ -11,28 +11,114 @@ package io.element.android.libraries.matrix.api.notificationsettings
import io.element.android.libraries.matrix.api.core.RoomId
import io.element.android.libraries.matrix.api.room.RoomNotificationMode
import io.element.android.libraries.matrix.api.room.RoomNotificationSettings
import io.element.android.libraries.matrix.api.room.RoomNotificationSettingsState
import kotlinx.coroutines.flow.SharedFlow
/**
* Reads and writes the push rules of the account, which decide what generates a notification.
*
* Rules are account data shared across clients, so a change made here is visible on the user's other devices.
* Several methods take the encryption and one-to-one nature of a room, because Matrix keeps a separate default rule for each combination.
*/
interface NotificationSettingsService {
/**
* State of the current room notification settings flow ([RoomNotificationSettingsState.Unknown] if not started).
* Emits every time the push rules change, whether from this client or another one, without saying what changed.
* Callers are expected to re-read the values they display; only the most recent signal is buffered.
*/
val notificationSettingsChangeFlow: SharedFlow<Unit>
/**
* Returns the notification settings that apply to one room, which may come from a room specific rule or from the matching default.
*
* @param roomId the room to read the settings of.
* @param isEncrypted whether that room is encrypted, which selects the relevant default rule.
* @param isOneToOne whether that room is a direct message, which selects the relevant default rule.
*/
suspend fun getRoomNotificationSettings(roomId: RoomId, isEncrypted: Boolean, isOneToOne: Boolean): Result<RoomNotificationSettings>
/**
* Returns the default notification mode used by rooms that have no rule of their own.
*
* @param isEncrypted whether to read the default for encrypted rooms.
* @param isOneToOne whether to read the default for direct messages.
*/
suspend fun getDefaultRoomNotificationMode(isEncrypted: Boolean, isOneToOne: Boolean): Result<RoomNotificationMode>
/**
* Changes the default notification mode for a whole category of rooms.
*
* @param isEncrypted whether to change the default for encrypted rooms.
* @param mode the new default mode.
* @param isDM whether to change the default for direct messages.
*/
suspend fun setDefaultRoomNotificationMode(isEncrypted: Boolean, mode: RoomNotificationMode, isDM: Boolean): Result<Unit>
/**
* Sets a room specific notification mode, which from then on overrides the default for that room.
*
* @param roomId the room to change.
* @param mode the new mode for that room.
*/
suspend fun setRoomNotificationMode(roomId: RoomId, mode: RoomNotificationMode): Result<Unit>
/**
* Removes the room specific rule so the room follows the matching default again.
*
* @param roomId the room to reset.
*/
suspend fun restoreDefaultRoomNotificationMode(roomId: RoomId): Result<Unit>
/**
* Mutes a room, which is a room specific rule like any other and is undone by [unmuteRoom].
*
* @param roomId the room to mute.
*/
suspend fun muteRoom(roomId: RoomId): Result<Unit>
/**
* Unmutes a room, restoring either its previous room specific mode or the matching default.
*
* @param roomId the room to unmute.
* @param isEncrypted whether that room is encrypted, which selects the relevant default rule.
* @param isOneToOne whether that room is a direct message, which selects the relevant default rule.
*/
suspend fun unmuteRoom(roomId: RoomId, isEncrypted: Boolean, isOneToOne: Boolean): Result<Unit>
/** Whether being mentioned through `@room` generates a notification. */
suspend fun isRoomMentionEnabled(): Result<Boolean>
/**
* Sets whether being mentioned through `@room` generates a notification.
*
* @param enabled true to be notified of `@room` mentions.
*/
suspend fun setRoomMentionEnabled(enabled: Boolean): Result<Unit>
/** Whether incoming calls generate a notification. */
suspend fun isCallEnabled(): Result<Boolean>
/**
* Sets whether incoming calls generate a notification.
*
* @param enabled true to be notified of incoming calls.
*/
suspend fun setCallEnabled(enabled: Boolean): Result<Unit>
/** Whether room invitations generate a notification. */
suspend fun isInviteForMeEnabled(): Result<Boolean>
/**
* Sets whether room invitations generate a notification.
*
* @param enabled true to be notified of invitations.
*/
suspend fun setInviteForMeEnabled(enabled: Boolean): Result<Unit>
/** The rooms that have an enabled rule of their own rather than following the defaults. */
suspend fun getRoomsWithUserDefinedRules(): Result<List<RoomId>>
/** Whether the homeserver is able to push encrypted events to the device, which decides how much a notification can show before decryption. */
suspend fun canHomeServerPushEncryptedEventsToDevice(): Result<Boolean>
/** The push rules as raw JSON, for debugging and bug reports; `null` when the server returned none. */
suspend fun getRawPushRules(): Result<String?>
}
@@ -20,6 +20,9 @@ interface MatrixToConverter {
* - https://riot.im/develop/#/room/#element-android:matrix.org -> https://matrix.to/#/#element-android:matrix.org
* - https://app.element.io/#/room/#element-android:matrix.org -> https://matrix.to/#/#element-android:matrix.org
* - https://www.example.org/#/room/#element-android:matrix.org -> https://matrix.to/#/#element-android:matrix.org
*
* @param uri the uri to convert.
* @return the equivalent matrix.to uri, or `null` when the input is not a permalink this converter recognises.
*/
fun convert(uri: Uri): Uri?
}
@@ -11,8 +11,22 @@ package io.element.android.libraries.matrix.api.permalink
import io.element.android.libraries.matrix.api.core.RoomAlias
import io.element.android.libraries.matrix.api.core.UserId
/**
* Builds `matrix.to` permalinks, which are the shareable links to a user or a room; see [PermalinkParser] for the other direction.
*/
interface PermalinkBuilder {
/**
* Builds a permalink to a user, failing with [PermalinkBuilderError.InvalidData] when the id is malformed.
*
* @param userId the user to link to.
*/
fun permalinkForUser(userId: UserId): Result<String>
/**
* Builds a permalink to a room from its alias, failing with [PermalinkBuilderError.InvalidData] when the alias is malformed.
*
* @param roomAlias the room alias to link to.
*/
fun permalinkForRoomAlias(roomAlias: RoomAlias): Result<String>
}
@@ -18,7 +18,10 @@ package io.element.android.libraries.matrix.api.permalink
interface PermalinkParser {
/**
* Turns a uri string to a [PermalinkData].
* A uri that is not a Matrix permalink is reported as a fallback link rather than as an error, so this never throws.
* https://github.com/matrix-org/matrix-doc/blob/master/proposals/1704-matrix.to-permalinks.md
*
* @param uriString the uri to parse.
*/
fun parse(uriString: String): PermalinkData
}
@@ -8,7 +8,21 @@
package io.element.android.libraries.matrix.api.pusher
/**
* Registers and removes the pusher of this session, i.e. the HTTP gateway the homeserver sends push notifications to.
*/
interface PushersService {
/**
* Registers or updates the pusher; calling it again with the same push key replaces the existing registration.
*
* @param setHttpPusherData the gateway URL, the push key and the other details the homeserver needs to reach the device.
*/
suspend fun setHttpPusher(setHttpPusherData: SetHttpPusherData): Result<Unit>
/**
* Removes the pusher, so the homeserver stops sending push notifications to this device.
*
* @param unsetHttpPusherData the push key and app id identifying the registration to remove.
*/
suspend fun unsetHttpPusher(unsetHttpPusherData: UnsetHttpPusherData): Result<Unit>
}
@@ -66,21 +66,30 @@ interface BaseRoom : Closeable {
*/
fun isDm() = roomInfoFlow.value.isDm
/**
* The room this one replaced when it was upgraded, or `null` if this room has no predecessor.
* Errors are swallowed and reported as `null`.
*/
fun predecessorRoom(): PredecessorRoom?
/**
* Try to load the room members and update the membersFlow.
* The first call may serve members from the local cache before the server response arrives; later calls always go to the server.
*/
suspend fun updateMembers()
/**
* Get the members of the room. Note: generally this should not be used, please use
* [membersStateFlow] and [updateMembers] instead.
*
* @param limit the maximum number of members to return.
*/
suspend fun getMembers(limit: Int = 5): Result<List<RoomMember>>
/**
* Will return an updated member or an error.
*
* @param userId the member to fetch.
*/
suspend fun getUpdatedMember(userId: UserId): Result<RoomMember>
@@ -103,6 +112,8 @@ interface BaseRoom : Closeable {
/**
* Gets the role of the user with the provided [userId] in the room.
*
* @param userId the member whose role is requested.
*/
suspend fun userRole(userId: UserId): Result<RoomMember.Role>
@@ -113,11 +124,15 @@ interface BaseRoom : Closeable {
/**
* Gets the display name of the user with the provided [userId] in the room.
*
* @param userId the member whose room specific display name is requested.
*/
suspend fun userDisplayName(userId: UserId): Result<String?>
/**
* Gets the avatar of the user with the provided [userId] in the room.
*
* @param userId the member whose room specific avatar is requested.
*/
suspend fun userAvatarUrl(userId: UserId): Result<String?>
@@ -138,6 +153,8 @@ interface BaseRoom : Closeable {
/**
* Sets the room as favorite or not, based on the [isFavorite] parameter.
*
* @param isFavorite true to mark the room as favorite, false to remove the flag.
*/
suspend fun setIsFavorite(isFavorite: Boolean): Result<Unit>
@@ -176,22 +193,29 @@ interface BaseRoom : Closeable {
suspend fun getRoomVisibility(): Result<RoomVisibility>
/**
* Returns the visibility for this room in the room directory, fetching it from the homeserver if needed.
* Returns whether this room is encrypted, based on the latest encryption state known to the SDK rather than on the cached [RoomInfo].
*/
suspend fun getUpdatedIsEncrypted(): Result<Boolean>
/**
* Store the given `ComposerDraft` in the state store of this room.
*
* @param composerDraft the unsent message content to remember.
* @param threadRoot the thread the draft belongs to, or `null` for the main timeline.
*/
suspend fun saveComposerDraft(composerDraft: ComposerDraft, threadRoot: ThreadId?): Result<Unit>
/**
* Retrieve the `ComposerDraft` stored in the state store for this room.
*
* @param threadRoot the thread whose draft is requested, or `null` for the main timeline.
*/
suspend fun loadComposerDraft(threadRoot: ThreadId?): Result<ComposerDraft?>
/**
* Clear the `ComposerDraft` stored in the state store for this room.
*
* @param threadRoot the thread whose draft should be cleared, or `null` for the main timeline.
*/
suspend fun clearComposerDraft(threadRoot: ThreadId?): Result<Unit>
@@ -202,10 +226,27 @@ interface BaseRoom : Closeable {
*/
suspend fun reportRoom(reason: String?): Result<Unit>
/**
* Declines the incoming call advertised by the given notification, letting the other devices of the room know.
*
* @param notificationEventId the id of the call notification event being declined.
*/
suspend fun declineCall(notificationEventId: EventId): Result<Unit>
/**
* Emits the id of each user who declines the call advertised by the given notification.
* Used to stop ringing once the callee has declined from another device.
*
* @param notificationEventId the id of the call notification event to watch.
*/
suspend fun subscribeToCallDecline(notificationEventId: EventId): Flow<UserId>
/**
* Returns the id of the thread the given event belongs to, fetching the event from the server if it is not cached locally.
*
* @param eventId the event whose thread is requested.
* @return the thread root id, or `null` if the event is not part of a thread.
*/
suspend fun threadRootIdForEvent(eventId: EventId): Result<ThreadId?>
/**
@@ -213,5 +254,6 @@ interface BaseRoom : Closeable {
*/
fun destroy()
/** Same as [destroy], so that a room can be used with `use { }`. */
override fun close() = destroy()
}
@@ -28,11 +28,28 @@ import io.element.android.libraries.matrix.api.widget.MatrixWidgetSettings
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
/**
* A room the current user has joined, adding to [BaseRoom] everything that requires membership: sending events, moderation and room settings.
*
* An instance owns SDK resources, in particular [liveTimeline], so it must be closed once no longer needed.
*/
interface JoinedRoom : BaseRoom {
/**
* A counter incremented every time a synced event is received on [liveTimeline], so callers can refresh data derived from the room.
* It carries no meaning beyond "something changed", and is only updated while it has subscribers.
*/
val syncUpdateFlow: StateFlow<Long>
/** The members currently typing in the room, never including the current user; starts as an empty list. */
val roomTypingMembersFlow: Flow<List<UserId>>
/** Emits when the verification state of other members' identities changes, for instance after a member resets their identity. */
val identityStateChangesFlow: Flow<List<IdentityStateChange>>
/**
* The notification settings that apply to this room.
* Starts as [RoomNotificationSettingsState.Unknown]: [updateRoomNotificationSettings] must be called to populate it.
*/
val roomNotificationSettingsStateFlow: StateFlow<RoomNotificationSettingsState>
/**
@@ -45,6 +62,7 @@ interface JoinedRoom : BaseRoom {
*/
val liveTimeline: Timeline
/** Gives access to the paginated list of threads started in this room. */
val threadsListService: ThreadsListService
/**
@@ -55,6 +73,14 @@ interface JoinedRoom : BaseRoom {
createTimelineParams: CreateTimelineParams,
): Result<Timeline>
/**
* Replaces the content of an event previously sent by the current user, by sending an edit of it.
*
* @param eventId the event to edit.
* @param body the new content, as plain text.
* @param htmlBody the new content as HTML, or `null` when the message has no formatted version.
* @param intentionalMentions the users and rooms this new content deliberately mentions.
*/
suspend fun editMessage(eventId: EventId, body: String, htmlBody: String?, intentionalMentions: List<IntentionalMention>): Result<Unit>
/**
@@ -63,12 +89,28 @@ interface JoinedRoom : BaseRoom {
*/
suspend fun typingNotice(isTyping: Boolean): Result<Unit>
/**
* Invites a user to this room.
*
* @param id the user to invite.
*/
suspend fun inviteUserById(id: UserId): Result<Unit>
/**
* Uploads [data] as the new avatar of the room, not of the current user.
*
* @param mimeType the MIME type of the image, for instance `image/jpeg`.
* @param data the raw bytes of the image.
*/
suspend fun updateAvatar(mimeType: String, data: ByteArray): Result<Unit>
/** Removes the avatar of the room. */
suspend fun removeAvatar(): Result<Unit>
/**
* Refreshes [roomNotificationSettingsStateFlow], which moves to a pending state and then to a ready or error state.
* The failure is reported through that flow as well as through the returned [Result].
*/
suspend fun updateRoomNotificationSettings(): Result<Unit>
/**
@@ -83,11 +125,15 @@ interface JoinedRoom : BaseRoom {
/**
* Update the room's visibility in the room directory.
*
* @param roomVisibility whether the room should be listed publicly in the directory.
*/
suspend fun updateRoomVisibility(roomVisibility: RoomVisibility): Result<Unit>
/**
* Update room history visibility for this room.
* Update room history visibility for this room, i.e. how much of the past a new member is allowed to read.
*
* @param historyVisibility the new history visibility to apply.
*/
suspend fun updateHistoryVisibility(historyVisibility: RoomHistoryVisibility): Result<Unit>
@@ -98,6 +144,8 @@ interface JoinedRoom : BaseRoom {
* - `true` if the room alias didn't exist and it's now published.
* - `false` if the room alias was already present so it couldn't be
* published.
*
* @param roomAlias the alias to publish.
*/
suspend fun publishRoomAliasInRoomDirectory(roomAlias: RoomAlias): Result<Boolean>
@@ -108,6 +156,8 @@ interface JoinedRoom : BaseRoom {
* - `true` if the room alias was present and it's now removed from the
* room directory.
* - `false` if the room alias didn't exist so it couldn't be removed.
*
* @param roomAlias the alias to remove.
*/
suspend fun removeRoomAliasFromRoomDirectory(roomAlias: RoomAlias): Result<Boolean>
@@ -117,26 +167,74 @@ interface JoinedRoom : BaseRoom {
suspend fun enableEncryption(): Result<Unit>
/**
* Update the join rule for this room.
* Update the join rule for this room, i.e. who is allowed to join it.
*
* @param joinRule the new join rule to apply.
*/
suspend fun updateJoinRule(joinRule: JoinRule): Result<Unit>
/**
* Changes the power level of individual members, which is how roles such as moderator or administrator are granted.
*
* @param changes the new power level to apply to each user.
*/
suspend fun updateUsersRoles(changes: List<UserRoleChange>): Result<Unit>
/**
* Changes the power level required for each action in the room, such as inviting, kicking or changing the room name.
*
* @param roomPowerLevelsValues the new threshold for every action.
*/
suspend fun updatePowerLevels(roomPowerLevelsValues: RoomPowerLevelsValues): Result<Unit>
/** Restores the power levels required for each action to the defaults the room was created with. */
suspend fun resetPowerLevels(): Result<Unit>
/**
* Changes the name of the room.
*
* @param name the new room name.
*/
suspend fun setName(name: String): Result<Unit>
/**
* Changes the topic of the room.
*
* @param topic the new room topic.
*/
suspend fun setTopic(topic: String): Result<Unit>
/**
* Reports an event to the homeserver moderators, optionally ignoring its sender at the same time.
*
* @param eventId the event being reported.
* @param reason the explanation sent to the moderators.
* @param blockUserId the sender to also add to the ignore list, or `null` to only report the event.
*/
suspend fun reportContent(eventId: EventId, reason: String, blockUserId: UserId?): Result<Unit>
/**
* Removes a member from the room; they are able to join again unless they are also banned.
*
* @param userId the member to remove.
* @param reason the reason recorded in the membership event, or `null` for none.
*/
suspend fun kickUser(userId: UserId, reason: String? = null): Result<Unit>
/**
* Bans a user from the room, removing them if they are a member and preventing them from joining again.
*
* @param userId the user to ban.
* @param reason the reason recorded in the membership event, or `null` for none.
*/
suspend fun banUser(userId: UserId, reason: String? = null): Result<Unit>
/**
* Lifts the ban on a user, allowing them to join the room again; it does not invite them back.
*
* @param userId the user to unban.
* @param reason the reason recorded in the membership event, or `null` for none.
*/
suspend fun unbanUser(userId: UserId, reason: String? = null): Result<Unit>
/**
@@ -161,6 +259,12 @@ interface JoinedRoom : BaseRoom {
*/
fun getWidgetDriver(widgetSettings: MatrixWidgetSettings): Result<MatrixWidgetDriver>
/**
* Enables or disables the send queue of this room only; see [io.element.android.libraries.matrix.api.MatrixClient.setAllSendQueuesEnabled]
* for the session-wide equivalent and for why a queue disables itself.
*
* @param enabled whether the send queue of this room should be enabled.
*/
suspend fun setSendQueueEnabled(enabled: Boolean)
/**
@@ -12,7 +12,13 @@ import io.element.android.libraries.matrix.api.room.preview.RoomPreviewInfo
/** A reference to a room either invited, knocked or banned. */
interface NotJoinedRoom : AutoCloseable {
/** What is publicly known about the room: name, topic, avatar, join rule and member count. */
val previewInfo: RoomPreviewInfo
/**
* The local room, available when the user has a membership in it, for instance after being invited.
* It is `null` for a room only discovered through a preview, and closing this instance also closes it.
*/
val localRoom: BaseRoom?
/**
@@ -10,7 +10,21 @@ package io.element.android.libraries.matrix.api.room.alias
import io.element.android.libraries.matrix.api.core.RoomAlias
/**
* Helpers to build and validate room aliases, delegating to the SDK so that the app and the server agree on what is acceptable.
*/
interface RoomAliasHelper {
/**
* Turns a room display name into a usable alias local part, dropping the characters that are not allowed in an alias.
*
* @param name the room display name to derive the alias from.
*/
fun roomAliasNameFromRoomDisplayName(name: String): String
/**
* Whether the given alias is well-formed; this is a format check only and says nothing about the alias being taken.
*
* @param roomAlias the alias to validate.
*/
fun isRoomAliasValid(roomAlias: RoomAlias): Boolean
}
@@ -11,7 +11,18 @@ package io.element.android.libraries.matrix.api.room.join
import im.vector.app.features.analytics.plan.JoinedRoom
import io.element.android.libraries.matrix.api.core.RoomIdOrAlias
/**
* Joins a room and reports the join to analytics, so that callers do not have to do both.
*/
interface JoinRoom {
/**
* Joins the room, picking the right SDK call depending on whether an id or an alias was given, and captures an analytics event on success.
* A `Forbidden` answer from the server is translated into [Failures.UnauthorizedJoin] so callers can tell it apart from other errors.
*
* @param roomIdOrAlias the id or the alias of the room to join.
* @param serverNames servers to ask about the room, ignored when joining by alias.
* @param trigger what made the user join, recorded in the analytics event.
*/
suspend operator fun invoke(
roomIdOrAlias: RoomIdOrAlias,
serverNames: List<String>,
@@ -11,20 +11,50 @@ package io.element.android.libraries.matrix.api.room.knock
import io.element.android.libraries.matrix.api.core.EventId
import io.element.android.libraries.matrix.api.core.UserId
/**
* A pending request from a user to join a room whose join rule is knock, along with the actions a moderator can take on it.
*
* Instances are snapshots handed out by [io.element.android.libraries.matrix.api.room.JoinedRoom.knockRequestsFlow].
*/
interface KnockRequest {
/** The id of the membership event carrying the request. */
val eventId: EventId
/** The user asking to join. */
val userId: UserId
/** The display name of the user asking to join, or `null` if they have none. */
val displayName: String?
/** The avatar of the user asking to join, or `null` if they have none. */
val avatarUrl: String?
/** The message the user attached to their request, or `null` if they sent none. */
val reason: String?
/** When the request was made, in milliseconds since the epoch, or `null` if the server did not provide it. */
val timestamp: Long?
/** Whether a moderator has already marked this request as seen, so that it is no longer highlighted as new. */
val isSeen: Boolean
/** Accepts the request, which makes the user a member of the room. */
suspend fun accept(): Result<Unit>
/**
* Declines the request; the user is free to knock again.
*
* @param reason the explanation recorded in the membership event, or `null` for none.
*/
suspend fun decline(reason: String?): Result<Unit>
/**
* Declines the request and bans the user, so that they cannot knock again.
*
* @param reason the explanation recorded in the membership event, or `null` for none.
*/
suspend fun declineAndBan(reason: String?): Result<Unit>
/** Marks the request as seen, without accepting or declining it. */
suspend fun markAsSeen(): Result<Unit>
}
@@ -59,12 +59,16 @@ interface RoomPermissions : AutoCloseable {
/**
* Returns true if the current user is able to send a specific message type
* in the room.
*
* @param message the kind of message the caller wants to send.
*/
fun canOwnUserSendMessage(message: MessageEventType): Boolean
/**
* Returns true if the current user is able to send a specific state event
* type in the room.
*
* @param stateEvent the kind of state event the caller wants to send.
*/
fun canOwnUserSendState(stateEvent: StateEventType): Boolean
@@ -77,48 +81,66 @@ interface RoomPermissions : AutoCloseable {
/**
* Returns true if the user with the given userId is able to ban in the
* room.
*
* @param userId the member whose ability is checked.
*/
fun canUserBan(userId: UserId): Boolean
/**
* Returns true if the user with the given userId is able to invite in the
* room.
*
* @param userId the member whose ability is checked.
*/
fun canUserInvite(userId: UserId): Boolean
/**
* Returns true if the user with the given userId is able to kick in the
* room.
*
* @param userId the member whose ability is checked.
*/
fun canUserKick(userId: UserId): Boolean
/**
* Returns true if the user with the given userId is able to pin or unpin
* events in the room.
*
* @param userId the member whose ability is checked.
*/
fun canUserPinUnpin(userId: UserId): Boolean
/**
* Returns true if the user with the given userId is able to redact
* messages of other users in the room.
*
* @param userId the member whose ability is checked.
*/
fun canUserRedactOther(userId: UserId): Boolean
/**
* Returns true if the user with the given userId is able to redact
* their own messages in the room.
*
* @param userId the member whose ability is checked.
*/
fun canUserRedactOwn(userId: UserId): Boolean
/**
* Returns true if the user with the given userId is able to send a
* specific message type in the room.
*
* @param userId the member whose ability is checked.
* @param message the kind of message to check.
*/
fun canUserSendMessage(userId: UserId, message: MessageEventType): Boolean
/**
* Returns true if the user with the given userId is able to send a
* specific state event type in the room.
*
* @param userId the member whose ability is checked.
* @param stateEvent the kind of state event to check.
*/
fun canUserSendState(userId: UserId, stateEvent: StateEventType): Boolean
@@ -127,6 +149,8 @@ interface RoomPermissions : AutoCloseable {
* notification in the room.
*
* The call may fail if there is an error in getting the power levels.
*
* @param userId the member whose ability is checked.
*/
fun canUserTriggerRoomNotification(userId: UserId): Boolean
}
@@ -9,10 +9,27 @@ package io.element.android.libraries.matrix.api.room.threads
import kotlinx.coroutines.flow.Flow
/**
* Exposes the paginated list of threads of a single room, kept up to date by the SDK.
*
* The list grows through explicit [paginate] calls; [destroy] must be called to release the underlying SDK resources.
*/
interface ThreadsListService {
/**
* The threads loaded so far, starting empty and re-emitted in full whenever the SDK sends an update.
* The underlying subscription is started on the first call and shared by later ones.
*/
fun subscribeToItemUpdates(): Flow<List<ThreadListItem>>
/** The pagination state of the list, emitting the current value immediately so callers know whether more threads can be loaded. */
fun subscribeToPaginationUpdates(): Flow<ThreadListPaginationStatus>
/** Loads the next page of threads, which will be reflected in [subscribeToItemUpdates]. */
suspend fun paginate(): Result<Unit>
/** Discards the loaded threads and starts the list again from the most recent one. */
suspend fun reset(): Result<Unit>
/** Releases the SDK resources and stops the item subscription; the service is unusable afterwards. */
fun destroy()
}
@@ -10,12 +10,21 @@ package io.element.android.libraries.matrix.api.roomdirectory
import kotlinx.coroutines.flow.Flow
/**
* A single, stateful search in the public room directory: one query at a time, with paginated results.
*
* Obtain an instance from [RoomDirectoryService.createRoomDirectoryList].
*/
interface RoomDirectoryList {
/**
* Starts a filtered search for the server.
* If the filter is not provided it will search for all the rooms. You can specify a batch_size to control the number of rooms to fetch per request.
* If the via_server is not provided it will search in the current homeserver by default.
* This method will clear the current search results and start a new one
*
* @param filter the text to look for, or `null` to list every room.
* @param batchSize the number of rooms to fetch per request.
* @param viaServerName the server whose directory to search, or `null` to use the user's own homeserver.
*/
suspend fun filter(filter: String?, batchSize: Int, viaServerName: String?): Result<Unit>
@@ -10,6 +10,14 @@ package io.element.android.libraries.matrix.api.roomdirectory
import kotlinx.coroutines.CoroutineScope
/**
* Gives access to the public room directory, i.e. the rooms a server advertises to users who have not joined them.
*/
interface RoomDirectoryService {
/**
* Creates an independent directory search, which is stateful and holds one query at a time.
*
* @param scope the lifetime of the search; the underlying SDK resources are released when it completes, so there is nothing to close by hand.
*/
fun createRoomDirectoryList(scope: CoroutineScope): RoomDirectoryList
}
@@ -14,6 +14,7 @@ package io.element.android.libraries.matrix.api.roomlist
* It lets load rooms on demand and filter them.
*/
interface DynamicRoomList : RoomList {
/** The number of rooms added to the list by each [loadMore] call, as chosen when the list was created. */
val pageSize: Int
/**
@@ -19,7 +19,13 @@ fun interface ContentScannerUrlProvider {
*/
suspend fun getContentScannerUrl(sessionId: SessionId): Result<String?>
/**
* Creates a provider, which needs a fetcher because the scanner URL is itself discovered over HTTP.
*/
fun interface Factory {
/**
* @param urlContentFetcher used to read the configuration advertised by the homeserver; a client that is not authenticated yet also works.
*/
fun create(urlContentFetcher: UrlContentFetcher): ContentScannerUrlProvider
}
}
@@ -10,6 +10,11 @@ package io.element.android.libraries.matrix.api.search
import io.element.android.libraries.matrix.api.core.RoomId
import kotlinx.coroutines.CoroutineScope
/**
* Creates the message search cursors backed by the local search index.
*
* Only usable when the session was built with the index attached, see [io.element.android.libraries.matrix.api.MatrixClient.isMessageSearchAvailable].
*/
interface MessageSearchService {
/**
* Create a new, independent search cursor.
@@ -8,6 +8,10 @@
package io.element.android.libraries.matrix.api.server
/**
* Resolves the server name of the logged in user, which is the part of their user id after the colon.
*/
interface UserServerResolver {
/** Returns the server name, for instance `matrix.org` for `@alice:matrix.org`. */
fun resolve(): String
}
@@ -10,6 +10,11 @@ package io.element.android.libraries.matrix.api.spaces
import io.element.android.libraries.matrix.api.core.RoomId
/**
* Handles leaving a space, letting the user also choose which of its rooms to leave in the same operation.
*
* Obtain an instance from [SpaceService.getLeaveSpaceHandle]; the caller owns it and must [close] it.
*/
interface LeaveSpaceHandle {
/**
* The id of the space to leave.
@@ -16,22 +16,36 @@ import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.util.Optional
/**
* The paginated list of the children of a single space, kept up to date by the SDK.
*
* Obtain an instance from [SpaceService.spaceRoomList]; the caller owns it and must call [destroy] when done.
*/
interface SpaceRoomList {
sealed interface PaginationStatus {
data object Loading : PaginationStatus
data class Idle(val hasMoreToLoad: Boolean) : PaginationStatus
}
/** The space whose children this list holds. */
val spaceId: RoomId
/** What is known about the space itself, starting empty until the SDK provides it. */
val currentSpaceFlow: StateFlow<Optional<SpaceRoom>>
/** The children loaded so far, re-emitted in full on every update; the latest value is replayed to new collectors. */
val spaceRoomsFlow: Flow<List<SpaceRoom>>
/** Whether a page is being loaded and whether more children remain; see [loadAllIncrementally] to drain the list. */
val paginationStatusFlow: StateFlow<PaginationStatus>
/** Loads the next page of children, which will be reflected in [spaceRoomsFlow]. */
suspend fun paginate(): Result<Unit>
/** Discards the loaded children and starts the list again from the beginning. */
suspend fun reset(): Result<Unit>
/** Releases the SDK resources and cancels the internal scope; the list is unusable afterwards. */
fun destroy()
}
@@ -11,13 +11,35 @@ package io.element.android.libraries.matrix.api.spaces
import io.element.android.libraries.matrix.api.core.RoomId
import kotlinx.coroutines.flow.SharedFlow
/**
* Gives access to the spaces the user belongs to, their hierarchy, and the operations that change it.
*/
interface SpaceService {
/** The spaces that have no joined parent, i.e. the roots of the hierarchy shown to the user; the latest value is replayed to new collectors. */
val topLevelSpacesFlow: SharedFlow<List<SpaceRoom>>
/** The filters the space list can be narrowed down with; as with [topLevelSpacesFlow], the latest value is replayed. */
val spaceFiltersFlow: SharedFlow<List<SpaceServiceFilter>>
/**
* Returns the spaces the given room or space is a child of, restricted to the ones the user has joined.
*
* @param spaceId the room or space whose parents are requested.
*/
suspend fun joinedParents(spaceId: RoomId): Result<List<SpaceRoom>>
/**
* Returns what is known about a single space, or `null` if it is unknown or the lookup failed.
*
* @param spaceId the space to look up.
*/
suspend fun getSpaceRoom(spaceId: RoomId): SpaceRoom?
/**
* Creates a paginated list of the children of a space; the caller owns it and must call `destroy` on it.
*
* @param id the space whose children are listed.
*/
fun spaceRoomList(id: RoomId): SpaceRoomList
/**
@@ -25,6 +47,11 @@ interface SpaceService {
*/
suspend fun editableSpaces(): Result<List<SpaceRoom>>
/**
* Creates a handle to leave a space, which lets the user also pick which of its rooms to leave; the caller must close it.
*
* @param spaceId the space the user wants to leave.
*/
fun getLeaveSpaceHandle(spaceId: RoomId): LeaveSpaceHandle
/**
@@ -10,21 +10,31 @@ package io.element.android.libraries.matrix.api.sync
import kotlinx.coroutines.flow.StateFlow
/**
* Drives the sync loop of a single session and exposes its current state.
*
* Both [startSync] and [stopSync] are idempotent and never throw: any error is wrapped in the returned [Result].
*/
interface SyncService {
/**
* Tries to start the sync. If already syncing it has no effect.
* Tries to start the sync. If already syncing, or if the service has been destroyed, it has no effect.
*/
suspend fun startSync(): Result<Unit>
/**
* Tries to stop the sync. If service is not syncing it has no effect.
* Tries to stop the sync. If the service is not syncing, or has been destroyed, it has no effect.
*/
suspend fun stopSync(): Result<Unit>
/**
* Flow of [SyncState]. Will be updated as soon as the current [SyncState] changes.
* Starts at [SyncState.Idle] and only emits on an actual change, for as long as the session lives.
*/
val syncState: StateFlow<SyncState>
/**
* Whether the client currently considers itself online, derived from [syncState].
* This is `false` only while the state is [SyncState.Offline]; an idle or errored sync still counts as online.
*/
val isOnline: StateFlow<Boolean>
}
@@ -31,6 +31,12 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.parcelize.Parcelize
import java.io.File
/**
* A window over the events of a room, restricted by its [Mode], and the entry point for sending events to that room.
*
* A timeline owns SDK resources and must be closed once no longer needed, except the live timeline, which is owned by its room.
* Sending returns successfully as soon as the event has been handed to the room's send queue, not when the server has accepted it.
*/
interface Timeline : AutoCloseable {
data class PaginationStatus(
val isPaginating: Boolean,
@@ -54,18 +60,66 @@ interface Timeline : AutoCloseable {
data class Thread(val threadRootId: ThreadId) : Mode
}
/** What this timeline is a view over: the live room, a single event and its context, the pinned events, the media, or a thread. */
val mode: Mode
/**
* Emits every time a membership change event is received in this timeline, without saying which one.
* Collecting it keeps the timeline subscribed to the SDK, so it should not be collected for longer than needed.
*/
val membershipChangeEventReceived: Flow<Unit>
/**
* Emits every time an event coming from sync is received in this timeline, without saying which one.
* As with [membershipChangeEventReceived], collecting it keeps the timeline subscribed to the SDK.
*/
val onSyncedEventReceived: Flow<Unit>
/**
* Sends a read receipt for a single event, which is how the unread state of the room is cleared.
*
* @param eventId the event the receipt points at.
* @param receiptType whether the receipt is public, private or only marks the fully read position.
*/
suspend fun sendReadReceipt(eventId: EventId, receiptType: ReceiptType): Result<Unit>
/**
* Marks the whole timeline as read by sending a receipt on its latest event.
*
* @param receiptType whether the receipt is public, private or only marks the fully read position.
*/
suspend fun markAsRead(receiptType: ReceiptType): Result<Unit>
/**
* Loads one more page of events and updates the matching pagination status flow.
* Fails with a `CannotPaginate` error when the corresponding status does not allow it, for instance because a pagination is already running.
*
* @param direction whether to load older or newer events.
* @return whether the end of the timeline has been reached in that direction.
*/
suspend fun paginate(direction: PaginationDirection): Result<Boolean>
/** Whether older events are being loaded and whether more remain; pinned event timelines start with nothing more to load. */
val backwardPaginationStatus: StateFlow<PaginationStatus>
/** Whether newer events are being loaded and whether more remain; only a timeline focused on an event starts with more to load. */
val forwardPaginationStatus: StateFlow<PaginationStatus>
/**
* The items to display, in timeline order, re-emitted on every change.
* Beyond the room events this also carries the virtual items the UI needs, such as date separators, loading indicators and the room beginning.
*/
val timelineItems: Flow<List<MatrixTimelineItem>>
/**
* Sends a text message to the room this timeline belongs to.
*
* @param body the message content, as plain text.
* @param htmlBody the message content as HTML, or `null` to send it unformatted.
* @param intentionalMentions the users and rooms the message deliberately mentions, so that they are notified.
* @param msgType the Matrix message type to use, which distinguishes a normal message from an emote or a notice.
* @param asPlainText whether to send the message without any formatting, ignoring markdown in [body].
*/
suspend fun sendMessage(
body: String,
htmlBody: String?,
@@ -74,6 +128,14 @@ interface Timeline : AutoCloseable {
asPlainText: Boolean = false,
): Result<Unit>
/**
* Replaces the content of a message, whether it has already been sent or is still local in the send queue.
*
* @param eventOrTransactionId the event to edit, identified by its event id once sent or by its transaction id while still local.
* @param body the new content, as plain text.
* @param htmlBody the new content as HTML, or `null` to send it unformatted.
* @param intentionalMentions the users and rooms the new content deliberately mentions.
*/
suspend fun editMessage(
eventOrTransactionId: EventOrTransactionId,
body: String,
@@ -81,12 +143,29 @@ interface Timeline : AutoCloseable {
intentionalMentions: List<IntentionalMention>,
): Result<Unit>
/**
* Replaces the caption of an already sent media message, leaving the media itself untouched.
*
* @param eventOrTransactionId the media event to edit, identified by its event id or by its transaction id while still local.
* @param caption the new caption, or `null` to remove it.
* @param formattedCaption the new caption as HTML, or `null` to send it unformatted.
*/
suspend fun editCaption(
eventOrTransactionId: EventOrTransactionId,
caption: String?,
formattedCaption: String?,
): Result<Unit>
/**
* Sends a message as a reply to another event.
*
* @param repliedToEventId the event being replied to.
* @param body the reply content, as plain text.
* @param htmlBody the reply content as HTML, or `null` to send it unformatted.
* @param intentionalMentions the users and rooms the reply deliberately mentions.
* @param fromNotification whether the reply was written from a notification rather than from the timeline.
* @param msgType the Matrix message type to use.
*/
suspend fun replyMessage(
repliedToEventId: EventId,
body: String,
@@ -96,6 +175,16 @@ interface Timeline : AutoCloseable {
msgType: MsgType = MsgType.MSG_TYPE_TEXT,
): Result<Unit>
/**
* Starts sending an image. The returned [MediaUploadHandler] tracks the upload and must be awaited by the caller to know the outcome.
*
* @param file the image to upload.
* @param thumbnailFile a pre-generated thumbnail, or `null` to send none.
* @param imageInfo the dimensions, size and MIME type of the image.
* @param caption the text shown along with the image, or `null` for none.
* @param formattedCaption the caption as HTML, or `null` to send it unformatted.
* @param inReplyToEventId the event this message replies to, or `null` if it is not a reply.
*/
suspend fun sendImage(
file: File,
thumbnailFile: File?,
@@ -105,6 +194,16 @@ interface Timeline : AutoCloseable {
inReplyToEventId: EventId?,
): Result<MediaUploadHandler>
/**
* Starts sending a video, with the same upload contract as [sendImage].
*
* @param file the video to upload.
* @param thumbnailFile a pre-generated thumbnail, or `null` to send none.
* @param videoInfo the duration, dimensions, size and MIME type of the video.
* @param caption the text shown along with the video, or `null` for none.
* @param formattedCaption the caption as HTML, or `null` to send it unformatted.
* @param inReplyToEventId the event this message replies to, or `null` if it is not a reply.
*/
suspend fun sendVideo(
file: File,
thumbnailFile: File?,
@@ -114,6 +213,15 @@ interface Timeline : AutoCloseable {
inReplyToEventId: EventId?,
): Result<MediaUploadHandler>
/**
* Starts sending an audio file, with the same upload contract as [sendImage]; use [sendVoiceMessage] for a recorded voice message.
*
* @param file the audio file to upload.
* @param audioInfo the duration, size and MIME type of the audio.
* @param caption the text shown along with the audio, or `null` for none.
* @param formattedCaption the caption as HTML, or `null` to send it unformatted.
* @param inReplyToEventId the event this message replies to, or `null` if it is not a reply.
*/
suspend fun sendAudio(
file: File,
audioInfo: AudioInfo,
@@ -122,6 +230,15 @@ interface Timeline : AutoCloseable {
inReplyToEventId: EventId?,
): Result<MediaUploadHandler>
/**
* Starts sending an arbitrary file, with the same upload contract as [sendImage].
*
* @param file the file to upload.
* @param fileInfo the size and MIME type of the file.
* @param caption the text shown along with the file, or `null` for none.
* @param formattedCaption the caption as HTML, or `null` to send it unformatted.
* @param inReplyToEventId the event this message replies to, or `null` if it is not a reply.
*/
suspend fun sendFile(
file: File,
fileInfo: FileInfo,
@@ -151,6 +268,14 @@ interface Timeline : AutoCloseable {
inReplyToEventId: EventId?,
): Result<Unit>
/**
* Starts sending a recorded voice message, with the same upload contract as [sendImage].
*
* @param file the recorded audio to upload.
* @param audioInfo the duration, size and MIME type of the recording.
* @param waveform the amplitudes used to draw the waveform, normalised between 0 and 1.
* @param inReplyToEventId the event this message replies to, or `null` if it is not a reply.
*/
suspend fun sendVoiceMessage(
file: File,
audioInfo: AudioInfo,
@@ -158,6 +283,14 @@ interface Timeline : AutoCloseable {
inReplyToEventId: EventId?,
): Result<MediaUploadHandler>
/**
* Starts sending several media items as a single gallery message, with the same upload contract as [sendImage].
*
* @param items the media making up the gallery, in the order they should appear.
* @param caption the text shown along with the gallery, or `null` for none.
* @param formattedCaption the caption as HTML, or `null` to send it unformatted.
* @param inReplyToEventId the event this message replies to, or `null` if it is not a reply.
*/
suspend fun sendGallery(
items: List<GalleryItemInfo>,
caption: String?,
@@ -165,12 +298,36 @@ interface Timeline : AutoCloseable {
inReplyToEventId: EventId?,
): Result<MediaUploadHandler>
/**
* Redacts an event, i.e. asks the server to remove its content; it also removes a local echo that has not been sent yet.
*
* @param eventOrTransactionId the event to redact, identified by its event id once sent or by its transaction id while still local.
* @param reason the explanation recorded in the redaction event, or `null` for none.
*/
suspend fun redactEvent(eventOrTransactionId: EventOrTransactionId, reason: String?): Result<Unit>
/**
* Adds the given reaction to an event, or removes it if the current user had already reacted with it.
*
* @param emoji the reaction key, usually an emoji.
* @param eventOrTransactionId the event to react to, identified by its event id or by its transaction id while still local.
* @return whether the reaction is now present.
*/
suspend fun toggleReaction(emoji: String, eventOrTransactionId: EventOrTransactionId): Result<Boolean>
/**
* Forwards the content of an event to other rooms, as new messages sent by the current user.
*
* @param eventId the event whose content is forwarded.
* @param roomIds the rooms to forward it to.
*/
suspend fun forwardEvent(eventId: EventId, roomIds: List<RoomId>): Result<Unit>
/**
* Cancels an event that is still waiting in the send queue, by redacting its local echo.
*
* @param transactionId the transaction id of the local echo to drop.
*/
suspend fun cancelSend(transactionId: TransactionId): Result<Unit> =
redactEvent(transactionId.toEventOrTransactionId(), reason = null)
@@ -222,12 +379,20 @@ interface Timeline : AutoCloseable {
*/
suspend fun endPoll(pollStartId: EventId, text: String): Result<Unit>
/**
* Resolves the content of a replied-to event so it can be rendered above the reply.
* Served from the loaded timeline items when possible, otherwise fetched through the SDK.
*
* @param eventId the event being replied to.
*/
suspend fun loadReplyDetails(eventId: EventId): InReplyTo
/**
* Returns true if [eventId] is currently loaded in this timeline's window, even if the display
* layer does not render it (e.g. filtered or state events). This distinguishes "in the window
* but not displayed" from "genuinely outside the loaded window".
*
* @param eventId the event to look for.
*/
suspend fun isEventLoaded(eventId: EventId): Boolean
@@ -237,6 +402,8 @@ interface Timeline : AutoCloseable {
*
* Returns `true` if we sent the request, `false` if the event was already
* pinned.
*
* @param eventId the event to pin.
*/
suspend fun pinEvent(eventId: EventId): Result<Boolean>
@@ -246,11 +413,13 @@ interface Timeline : AutoCloseable {
*
* Returns `true` if we sent the request, `false` if the event wasn't
* pinned
*
* @param eventId the event to unpin.
*/
suspend fun unpinEvent(eventId: EventId): Result<Boolean>
/**
* Get the latest event id of the timeline.
* Get the latest event id of the timeline, or `null` when it holds no event yet.
*/
suspend fun getLatestEventId(): Result<EventId?>
}
@@ -18,6 +18,7 @@ import kotlinx.coroutines.flow.first
* By default, the active timeline is the live timeline.
*/
fun interface TimelineProvider {
/** The timeline currently in use, or `null` while none is available yet; see [getActiveTimeline] to await a non-null value. */
fun activeTimelineFlow(): StateFlow<Timeline?>
}
@@ -60,14 +60,30 @@ data class EventTimelineItem(
}
}
/**
* Provides the debug information of a timeline item on demand, so the original event JSON is only fetched from the SDK when actually displayed.
*/
fun interface TimelineItemDebugInfoProvider {
/** Returns the debug information of the item, including its original and latest edit JSON. */
operator fun invoke(): TimelineItemDebugInfo
}
/**
* Provides the encryption warning to show next to a timeline item on demand, so the check is only run for items that are displayed.
*/
fun interface MessageShieldProvider {
/**
* Returns the warning to display for this event, or `null` when there is nothing to warn about.
*
* @param strict whether to also report the weaker problems that are hidden by default.
*/
operator fun invoke(strict: Boolean): MessageShield?
}
/**
* Provides the send queue handle of a timeline item on demand, which is needed to retry or cancel a failed send.
*/
fun interface SendHandleProvider {
/** Returns the send handle of the item, or `null` when it is not a local echo waiting in the send queue. */
operator fun invoke(): SendHandle?
}
@@ -10,8 +10,21 @@ package io.element.android.libraries.matrix.api.tracing
import timber.log.Timber
/**
* Routes the app's own logs into the SDK's tracing subsystem, so that Kotlin and Rust logs end up interleaved in the same files.
*/
interface TracingService {
/**
* Creates a Timber tree that forwards what the app logs to the SDK tracing subsystem.
*
* @param target the tracing target name the logs are attributed to, used to tell subsystems apart in the output.
*/
fun createTimberTree(target: String): Timber.Tree
/**
* Turns writing logs to files on or off at runtime, which is how the user-facing logging toggle is applied.
*
* @param config where to write the log files, or the disabled configuration to stop writing them.
*/
fun updateWriteToFilesConfiguration(config: WriteToFilesConfiguration)
}
@@ -13,6 +13,12 @@ import io.element.android.libraries.matrix.api.core.UserId
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
/**
* Drives session verification: proving to the account that this device is trusted, and verifying other users.
*
* A verification is a stateful exchange between two devices, so at most one flow is active at a time and its progress is reported
* through [verificationFlowState] rather than through the return value of each call.
*/
interface SessionVerificationService {
/**
* State of the current verification flow ([VerificationFlowState.Initial] if not started).
@@ -37,6 +43,8 @@ interface SessionVerificationService {
/**
* Request verification of the user with the given [userId].
*
* @param userId the other user to verify.
*/
suspend fun requestUserVerification(userId: UserId)
@@ -62,17 +70,23 @@ interface SessionVerificationService {
/**
* Returns the verification service state to the initial step.
*
* @param cancelAnyPendingVerificationAttempt whether to also cancel a verification that is still in progress.
*/
suspend fun reset(cancelAnyPendingVerificationAttempt: Boolean)
/**
* Register a listener to be notified of incoming session verification requests.
*
* @param listener the listener to notify, or `null` to stop being notified.
*/
fun setListener(listener: SessionVerificationServiceListener?)
/**
* Set this particular request as the currently active one and register for
* events pertaining it.
*
* @param verificationRequest the incoming request to make active.
*/
suspend fun acknowledgeVerificationRequest(verificationRequest: VerificationRequest.Incoming)
@@ -82,7 +96,15 @@ interface SessionVerificationService {
suspend fun acceptVerificationRequest()
}
/**
* Notified when another device asks to verify this session; register one through [SessionVerificationService.setListener].
*/
interface SessionVerificationServiceListener {
/**
* Called when a verification request is received, so the app can prompt the user about it.
*
* @param verificationRequest the incoming request, to be passed to [SessionVerificationService.acknowledgeVerificationRequest] to act on it.
*/
fun onIncomingSessionRequest(verificationRequest: VerificationRequest.Incoming)
}
@@ -8,10 +8,24 @@
package io.element.android.libraries.matrix.api.widget
/**
* Supplies the analytics and crash reporting credentials passed to the embedded Element Call widget.
*
* Every member is `null` when the corresponding service is not configured for this build, or when the user has not consented to analytics.
*/
interface CallAnalyticCredentialsProvider {
/** The PostHog identifier of the current user, so call analytics can be tied to the same person as app analytics. */
val posthogUserId: String?
/** The PostHog host the widget should send its events to. */
val posthogApiHost: String?
/** The PostHog API key the widget should use. */
val posthogApiKey: String?
/** The URL the widget should submit its rageshakes to. */
val rageshakeSubmitUrl: String?
/** The Sentry DSN the widget should report its crashes to. */
val sentryDsn: String?
}
@@ -10,7 +10,18 @@ package io.element.android.libraries.matrix.api.widget
import java.util.UUID
/**
* Builds the widget settings used to embed Element Call in a room, applying the app's own preferences on top of the SDK defaults.
*/
interface CallWidgetSettingsProvider {
/**
* @param baseUrl the URL Element Call is served from.
* @param widgetId a unique identifier for this widget instance.
* @param encrypted whether the room the call takes place in is encrypted.
* @param direct whether the call happens in a direct message room.
* @param isAudioCall whether the call should start without video.
* @param hasActiveCall whether a call is already ongoing in the room, which affects whether the user joins straight away.
*/
suspend fun provide(
baseUrl: String,
widgetId: String = UUID.randomUUID().toString(),
@@ -10,10 +10,25 @@ package io.element.android.libraries.matrix.api.widget
import kotlinx.coroutines.flow.Flow
/**
* Bridges a widget running in a WebView with the Matrix room it is embedded in, relaying the widget API messages in both directions.
*
* The driver owns SDK resources and must be closed once the widget goes away; Element Call is the main user of this.
*/
interface MatrixWidgetDriver : AutoCloseable {
/** The id of the widget this driver serves, matching the one in its settings. */
val id: String
/** The messages coming from the room that should be forwarded to the widget. */
val incomingMessages: Flow<String>
/** Starts relaying messages and suspends for as long as the driver runs; calling it again while it is running does nothing. */
suspend fun run()
/**
* Forwards a message from the widget to the room. Does nothing once the driver has been closed.
*
* @param message the raw widget API message emitted by the WebView.
*/
suspend fun send(message: String)
}