### Backup Setup and Monitoring Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Illustrates the process of enabling encrypted backups, including bootstrapping cross-signing and setting up a listener to monitor backup states. Requires an initialized client and encryption service. ```kotlin val encryption = client.encryption() // Bootstrap cross-signing first val bootstrapResult = encryption.bootstrapCrossSigning() // Send requests // (Implementation depends on your HTTP client) // Enable backups encryption.enableBackups() // Monitor backup state encryption.setBackupStateListener { state -> when (state) { BackupState.Enabled -> { println("Backups enabled!") } BackupState.NotTrusted -> { println("Backup needs verification") } else -> {} } } ``` -------------------------------- ### Complete Chat Application Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md A comprehensive example demonstrating the creation of a chat application using the Matrix Rust Components. It includes client initialization, login, encryption setup, message sending, and room observation. ```kotlin class ChatRepository(private val context: Context) { private lateinit var client: Client suspend fun initialize( homeserver: String, username: String, password: String ) { // Create client client = ClientBuilder() .homeserverUrl(homeserver) .sessionPath("${context.filesDir}/matrix") .build() // Login client.login( PasswordAuthData(username, password), "ChatApp" ) // Setup encryption setupEncryption() // Start sync startSync() } private suspend fun setupEncryption() { val encryption = client.encryption() if (encryption.crossSigningStatus() == CrossSigningStatus.NotBootstrapped) { encryption.bootstrapCrossSigning() } } private suspend fun startSync() { client.syncService().use { syncService -> syncService.start() } } suspend fun sendMessage(roomId: String, text: String) { client.roomOrNull(roomId)?.use { room -> room.sendMessage(text) } } fun observeMessages( roomId: String, callback: (TimelineUpdate) -> Unit ) { client.roomOrNull(roomId)?.timeline()?.use { timeline -> timeline.subscribe { callback(it) } } } suspend fun listRooms(): List { return client.rooms(null) } fun cleanup() { client.destroy() } } ``` -------------------------------- ### Quick Example: Listen to Messages Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/README.md Subscribes to timeline updates to receive and process new messages in a room. This example prints new items to the console. ```kotlin room.timeline().use { timeline -> timeline.subscribe { if (it is TimelineUpdate.Append) { for (item in it.items) { println("New item: $item") } } } } ``` -------------------------------- ### Timeline Subscription Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md An example demonstrating how to subscribe to timeline updates for a room and handle different types of timeline events. ```APIDOC ## Timeline Subscription ### Description This example shows how to subscribe to a room's timeline, listen for updates, paginate backwards, and focus on specific events. ### Usage ```kotlin room.timeline().use { // Start listening for updates timeline.subscribe(object : TimelineListener { override fun onUpdate(update: TimelineUpdate) { // Handle different update types like Append, SyncIndicatorChange, etc. } }) // Load previous messages timeline.paginateBackwards(50u) // Focus on a specific event timeline.focusEventId("$eventid:matrix.org") } ``` ### Key Components - **`timeline().use { ... }`**: Manages the lifecycle of the timeline subscription. - **`subscribe(listener: TimelineListener)`**: Registers a listener to receive timeline updates. - **`paginateBackwards(count: UInt)`**: Loads a specified number of previous messages. - **`focusEventId(eventId: String)`**: Scrolls the timeline to a specific event. - **`TimelineUpdate`**: Represents different types of updates received from the timeline (e.g., `Append`, `SyncIndicatorChange`). - **`TimelineItem`**: Represents an item in the timeline, which can be an `EventTimelineItem` or other types. ``` -------------------------------- ### Start Synchronization Service Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Start the client's synchronization service to receive real-time updates from the homeserver. Ensure the sync service is managed using 'use'. ```kotlin client.syncService().use { syncService -> syncService.start() } ``` -------------------------------- ### Handling Encryption Setup Failures Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/08-error-handling.md In case of encryption setup failure, log the error and provide an option for the user to retry. This is crucial for ensuring secure communication. ```kotlin try { encryption.bootstrapCrossSigning() } catch (e: Exception) { // Retry or inform user Log.e("MatrixSDK", "Encryption setup failed", e) showRetryPrompt() } ``` -------------------------------- ### Start and Stop Sync Service Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md Demonstrates how to start, stop, and listen to the state changes of the Sync Service. Use this to manage the background synchronization of messages and room states. ```kotlin client.syncService().use { syncService -> // Listen to sync state launch { syncService.state().collect { state -> when (state) { SyncServiceState.Running -> { println("Sync started") } SyncServiceState.Error -> { println("Sync error") } SyncServiceState.Idle -> { println("Sync idle") } else -> {} } } } // Start syncing syncService.start() // Do work... // Stop when done syncService.stop() } ``` -------------------------------- ### Quick Example: Verify Device Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/README.md Boots the cross-signing process for device verification. Any returned requests must be sent to the server. ```kotlin val encryption = client.encryption() val result = encryption.bootstrapCrossSigning() // Send returned requests to server... ``` -------------------------------- ### Start SyncService Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md Starts the Matrix synchronization loop. This is a suspend function that blocks until the sync loop is actively running. ```kotlin syncService.start() // Blocks until sync loop is running ``` -------------------------------- ### Bootstrap Cross-Signing Usage Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Demonstrates how to use the BootstrapCrossSigningResult. Ensure each request is sent to the server in the correct order. ```kotlin val result = encryption.bootstrapCrossSigning() // Send each request to the server in order client.send(result.uploadKeysRequest) client.send(result.uploadSigningKeysRequest) client.send(result.uploadSignatureRequest) ``` -------------------------------- ### Bootstrap Cross-Signing Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/README.md Initiates the setup process for cross-signing to enable secure device verification and key management. ```APIDOC ## Bootstrap Cross-Signing ### Description Initializes the cross-signing process for secure device verification. ### Method POST (implied by bootstrapCrossSigning) ### Endpoint Not explicitly defined, but relates to encryption operations. ### Parameters #### Path Parameters None explicitly defined. #### Query Parameters None explicitly defined. #### Request Body None explicitly defined. ### Request Example ```kotlin val encryption = client.encryption() val result = encryption.bootstrapCrossSigning() // Send returned requests to server... ``` ### Response #### Success Response (200) Returns a result object containing requests to be sent to the server. #### Response Example None explicitly defined. ``` -------------------------------- ### Quick Example: Send a Message Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/README.md Initializes a client and sends a message to a specified room. Ensure the client is built with the correct homeserver URL, session path, and server name. ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath("/path/to/session") .serverName("matrix.org") .build() client.roomOrNull("!roomid:matrix.org")?.use { room -> room.sendMessage("Hello!") } ``` -------------------------------- ### Basic Logging Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Demonstrates how to log messages using the standard Android Log utility. This library does not provide its own logging configuration. ```kotlin import android.util.Log Log.d("MatrixSDK", "Message") ``` -------------------------------- ### Complete Matrix Client Configuration Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Shows how to create and configure a Matrix client instance using `MatrixClientFactory`. This includes setting up paths for session and media, enabling encryption, and starting the sync service. ```kotlin class MatrixClientFactory(private val context: Context) { suspend fun createClient( homeserverUrl: String, serverName: String, passphrase: String? = null ): Client { val basePath = context.filesDir.absolutePath + "/matrix" val sessionPath = "$basePath/session" val mediaPath = context.cacheDir.absolutePath + "/media" return ClientBuilder() .homeserverUrl(homeserverUrl) .sessionPath(sessionPath) .mediaPath(mediaPath) .serverName(serverName) .passphrase(passphrase) .build() } } // Usage val factory = MatrixClientFactory(context) val client = factory.createClient( homeserverUrl = "https://matrix.org", serverName = "matrix.org", passphrase = null ) // Configure encryption client.encryption().use { encryption -> val result = encryption.bootstrapCrossSigning() // Handle bootstrap... } // Enable backups client.encryption().enableBackups() // Start syncing client.syncService().use { syncService -> syncService.start() } ``` -------------------------------- ### OlmMachine Encryption and Decryption Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Demonstrates initializing the OlmMachine, encrypting a message, decrypting an incoming message, marking a device as trusted, and cleaning up resources. Ensure the OlmMachine is properly initialized with user ID, device ID, and a file path for storage. ```kotlin val machine = OlmMachine( userId = client.userId(), deviceId = client.deviceId(), path = context.filesDir.absolutePath ) // Encrypt message val ciphertext = machine.encrypt( plaintext = "Secret message", eventType = "m.room.message" ) // Decrypt incoming message val plaintext = machine.decrypt( ciphertext = encryptedBody, senderKey = senderPublicKey ) // Mark device as trusted machine.markDeviceAsTrusted("@alice:matrix.org", "DEVICE123") // Clean up machine.destroy() ``` -------------------------------- ### Get Cross-Signing Status Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Check the current status of the cross-signing setup. This can indicate if it's not bootstrapped, ready, or if keys are missing or untrusted. ```kotlin when (encryption.crossSigningStatus()) { CrossSigningStatus.NotBootstrapped -> { /* Not initialized */ } CrossSigningStatus.Bootstrapped -> { /* Ready */ } CrossSigningStatus.SigningKeysNotStored -> { /* Missing keys */ } CrossSigningStatus.UserSigningKeyNotTrusted -> { /* Not trusted */ } } ``` -------------------------------- ### Update Room Power Levels Usage Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/03-types.md Example of how to instantiate and use RoomPowerLevelChanges to update a room's power levels. ```kotlin val changes = RoomPowerLevelChanges( ban = 50L, kick = 50L, redact = 50L ) room.updatePowerLevels(changes) ``` -------------------------------- ### Server Information Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve the homeserver URL, discover available sliding sync versions, and get the server name. ```APIDOC ## homeserverUrl() ### Description Returns the homeserver URL configured for this client. ### Method `fun homeserverUrl(): String` ### Usage Example ```kotlin val url = client.homeserverUrl() // "https://matrix.org" ``` ``` ```APIDOC ## availableSlidingSyncVersions() ### Description Discovers available sliding sync versions on the server. Makes requests to `.well-known` and `/versions` endpoints. ### Method `suspend fun availableSlidingSyncVersions(): List` ### Usage Example ```kotlin val versions = client.availableSlidingSyncVersions() for (version in versions) { println("Sliding sync ${version.version}") } ``` ``` ```APIDOC ## serverName() ### Description Returns the server name (domain part of user IDs). ### Method `fun serverName(): String` ### Usage Example ```kotlin val server = client.serverName() // "matrix.org" ``` ``` -------------------------------- ### Device Verification Flow Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Demonstrates how to initiate and complete a device verification flow with another user using the SAS or QR code methods. Ensure you have a valid client instance and user ID. ```kotlin // Start verification with another user val verification = encryption.startVerification("@alice:matrix.org") // Accept the request verification.accept() // Use SAS verification val sas = verification.sas() if (sas != null) { // Get emoji to display val emojis = sas.emoji() for (emoji in emojis) { println("${emoji.symbol} ${emoji.description}") } // User confirms match if (sas.accept()) { sas.confirm() } } // Or use QR code val qr = verification.qrCode() if (qr != null) { val data = qr.data() // Display as QR code } ``` -------------------------------- ### Get Homeserver URL Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve the URL of the homeserver configured for this client instance. ```kotlin val url = client.homeserverUrl() // "https://matrix.org" ``` -------------------------------- ### Full Room Usage Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Demonstrates comprehensive usage of a single room, including retrieving its information, sending messages, subscribing to timeline updates, managing members, and leaving the room. Ensure the room object is managed within a 'use' block. ```kotlin client.roomOrNull("!abc:matrix.org")?.use { // Get room info val name = room.displayName() val memberCount = room.joinedMembersCount() // Send message room.sendMessage("Hello everyone!") // Get timeline room.timeline().use { timeline.subscribe { when (update) { is TimelineUpdate.Append -> { for (item in update.items) { println("New item: $item") } } else -> {} } } } // Manage members for (member in room.activeMembers()) { println("${member.userId}: ${member.displayName}") } // Leave when done room.leave() } ``` -------------------------------- ### Manage Room Lifecycle Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Demonstrates how to get a room instance, send a message, and properly destroy the room. It also shows an alternative using AutoCloseable for automatic resource management. ```kotlin val room = client.roomOrNull("!abc:matrix.org") try { // Use room room.sendMessage("Hello") } finally { room.destroy() } // Or using AutoCloseable client.roomOrNull("!abc:matrix.org")?.use { room -> room.sendMessage("Hello") } ``` -------------------------------- ### Commonly Used Constants Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Provides examples of predefined constants for event IDs, room IDs, user IDs, media URLs, power levels, and pagination sizes. ```kotlin // Event IDs val eventId = "$eventId:matrix.org" val roomId = "!roomId:matrix.org" val userId = "@user:matrix.org" val alias = "#alias:matrix.org" // Media URLs val mxcUrl = "mxc://matrix.org/avatar123" // Power levels val User = 0L // Normal user val Moderator = 50L // Moderator val Admin = 100L // Administrator // Pagination val DefaultPageSize = 20u val LargePageSize = 50u val SmallPageSize = 10u ``` -------------------------------- ### Start OAuth 2.0 Login Flow Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Initiates the OAuth 2.0 authentication flow by obtaining a login URL. The browser should then be opened to this URL, and the callback should be handled by `finishOauthAuth`. ```kotlin // Start OAuth flow val authData = client.startOauthAuth() val loginUrl = authData.loginUrl() // Open browser val intent = Intent(Intent.ACTION_VIEW, Uri.parse(loginUrl)) startActivity(intent) // Handle callback client.finishOauthAuth(authorizationCode) ``` -------------------------------- ### Get Notification Client Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve a client instance specifically for managing push notifications. ```kotlin val notifClient = client.notificationClient() ``` -------------------------------- ### Get Server Name Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve the server name, which is the domain part of user IDs, from the client configuration. ```kotlin val server = client.serverName() // "matrix.org" ``` -------------------------------- ### Listen for Incoming Messages Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Subscribe to timeline updates to receive and process new messages. This example filters for 'EventTimelineItem' and prints sender and content. ```kotlin room.timeline().use { timeline -> timeline.subscribe { update -> if (update is TimelineUpdate.Append) { for (item in update.items) { if (item is EventTimelineItem) { println("${item.sender}: ${item.content}") } } } } } ``` -------------------------------- ### Get Device Information with OlmMachine Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves information about a specific device belonging to a user. Requires both user and device IDs. ```kotlin val device = machine.getDevice("@alice:matrix.org", "DEVICE456") ``` -------------------------------- ### Get Joined Members Count Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves the total number of users currently joined to a room. No setup is required beyond having a room instance. ```kotlin val count = room.joinedMembersCount() ``` -------------------------------- ### Initialize Client with Custom State Paths Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Builds a Matrix client instance, specifying custom paths for session state and downloaded media. Ensure the directory structure is correctly set up. ```kotlin val basePath = context.filesDir.absolutePath + "/matrix" val sessionPath = "$basePath/session" val mediaPath = context.cacheDir.absolutePath + "/media" val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath(sessionPath) .mediaPath(mediaPath) .serverName("matrix.org") .build() ``` -------------------------------- ### Build Client Instance Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Obtain a Client instance using ClientBuilder, configuring homeserver URL, session path, and server name. ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath("/path/to/session") .serverName("matrix.org") .build() ``` -------------------------------- ### Initialize Matrix Client Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Build and initialize the Matrix client with homeserver URL, session path, and server name. ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath(context.filesDir.absolutePath) .serverName("matrix.org") .build() ``` -------------------------------- ### Bootstrap and Verify Device Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Bootstrap cross-signing for encryption and initiate device verification with another user. This involves starting verification and confirming a SAS verification. ```kotlin val encryption = client.encryption() val result = encryption.bootstrapCrossSigning() // Send requests to server... // Later, verify another device val verification = encryption.startVerification("@alice:matrix.org") val sas = verification.sas() if (sas != null) { println("Verify: ${sas.emoji()}") sas.confirm() } ``` -------------------------------- ### Optimize Memory Usage: Pagination Limits Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Applies pagination limits when loading messages to control memory usage. This example loads 20 messages instead of the default 100. ```kotlin timeline.paginateBackwards(20u) // Load 20 messages, not 100 ``` -------------------------------- ### Get Room ID Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves the unique identifier for a Matrix room. ```kotlin val id = room.roomId() // "!abc:matrix.org" ``` -------------------------------- ### Get User ID Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve the user ID of the logged-in user. ```kotlin val userId = client.userId() ``` -------------------------------- ### Cross-Signing Status Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the current status of the cross-signing setup. This is a suspend function. ```APIDOC ## crossSigningStatus() ### Description Returns the status of cross-signing setup. ### Method `crossSigningStatus(): CrossSigningStatus` (suspend) ### Returns `CrossSigningStatus` - The status of cross-signing (NotBootstrapped, Bootstrapped, SigningKeysNotStored, UserSigningKeyNotTrusted). ### Example ```kotlin when (encryption.crossSigningStatus()) { CrossSigningStatus.NotBootstrapped -> { /* Not initialized */ } CrossSigningStatus.Bootstrapped -> { /* Ready */ } CrossSigningStatus.SigningKeysNotStored -> { /* Missing keys */ } CrossSigningStatus.UserSigningKeyNotTrusted -> { /* Not trusted */ } } ``` ``` -------------------------------- ### Get Current Device ID Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieve the unique identifier for the current device. ```kotlin val deviceId = client.deviceId() val displayName = "My iPhone" ``` -------------------------------- ### Documentation File Organization Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/MANIFEST.md This snippet shows the directory structure for the project's documentation files. It indicates the purpose of each markdown file, starting with an index and covering various aspects of the library. ```markdown output/ ├── 00-index.md # Start here ├── 01-overview.md # Context and structure ├── 02-client-api.md # Main client API ├── 03-types.md # All types ├── 04-room-api.md # Room operations ├── 05-crypto-api.md # Encryption ├── 06-timeline-sync-api.md # Messaging and sync ├── 07-configuration.md # Setup and options ├── 08-error-handling.md # Errors and recovery ├── 09-quick-reference.md # Quick patterns ├── 10-advanced-features.md # Advanced usage └── MANIFEST.md # This file ``` -------------------------------- ### Get Archived Rooms Only Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md Fetches only the archived rooms from the RoomListService. This is a suspend function. ```kotlin val archived = service.archivedRooms() ``` -------------------------------- ### Build Client Instance Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Constructs and returns a configured Client instance using the specified builder settings. ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath("/data/session") .serverName("matrix.org") .build() ``` -------------------------------- ### Get Room Preview in Kotlin Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Fetches pre-join information for a room using its ID. The returned `RoomPreview` object can then be used to access details like the number of joined members. ```kotlin val preview = client.getRoomPreview("!abc:matrix.org") println("Members: ${preview.numJoinedMembers()}") ``` -------------------------------- ### Get Device ID Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve the unique device ID for the current session. ```kotlin val deviceId = client.deviceId() ``` -------------------------------- ### Get All Rooms (Including Archived) Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md Retrieves all rooms, including those that are archived. This is a suspend function. ```kotlin val all = service.allRooms() ``` -------------------------------- ### Get Room Alternative Aliases Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves a list of alternative aliases for a Matrix room. ```kotlin val aliases = room.alternativeAliases() ``` -------------------------------- ### Client Build Method Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Creates a configured Matrix client instance. Requires essential parameters like homeserver URL and session path. ```APIDOC ## build(): Client (suspend) Creates the configured client. **Throws:** - `InternalException` - If Rust initialization fails - `IllegalArgumentException` - If required parameters are missing ### Request Example ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath(context.filesDir.absolutePath) .serverName("matrix.org") .passphrase(null) .build() ``` ``` -------------------------------- ### Get User Identity with OlmMachine Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the cross-signing status for a given user ID. ```kotlin val status = machine.getIdentity("@alice:matrix.org") ``` -------------------------------- ### Build Matrix Client Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Initializes and builds the Matrix client with essential configuration like homeserver URL, session path, and server name. Ensure all required parameters are provided. ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath(context.filesDir.absolutePath) .serverName("matrix.org") .passphrase(null) .build() ``` -------------------------------- ### Get Room Encryption Settings in Kotlin Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Fetches the encryption settings for a room. Use the returned object within a `use` block for proper resource management. ```kotlin room.encryption().use { encryption -> val status = encryption.status() } ``` -------------------------------- ### Backup State Listener Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Gets the currently set listener for backup state changes. ```APIDOC ## backupStateListener() ### Description Returns the current backup state listener, if set. ### Method `backupStateListener(): BackupStateListener?` ### Returns `BackupStateListener?` - The current listener or null if none is set. ### Example ```kotlin val listener = encryption.backupStateListener() ``` ``` -------------------------------- ### Create OlmMachine Instance Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Instantiates the core cryptography engine. Requires user ID, device ID, and a path for state storage. ```kotlin val machine = OlmMachine( userId = "@user:matrix.org", deviceId = "DEVICE123", path = "/path/to/crypto/state" ) ``` -------------------------------- ### Get All Rooms Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve a list of all joined rooms. Can be filtered by category, such as Direct Messages. ```kotlin val allRooms = client.rooms(null) val dmRooms = client.rooms(RoomCategoryFilter.DirectMessage) ``` -------------------------------- ### Get RoomListService Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md Retrieves the RoomListService instance from the SyncService, which is used for managing and querying room lists. ```kotlin val roomListService = syncService.roomListService() ``` -------------------------------- ### Get Room Topic Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves the topic of a Matrix room. Returns null if the topic is not set. ```kotlin val topic = room.topic() ``` -------------------------------- ### ClientBuilder Configuration Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Configure a Client instance using the ClientBuilder by setting the homeserver URL, session path, server name, and passphrase. ```APIDOC ## ClientBuilder Creates and configures a Client instance. **Package:** `org.matrix.rustcomponents.sdk` ### Methods #### `homeserverUrl(url: String): ClientBuilder` Sets the homeserver URL (required). ```kotlin builder.homeserverUrl("https://matrix.org") ``` #### `sessionPath(path: String): ClientBuilder` Sets the directory path for storing session state. ```kotlin builder.sessionPath(context.filesDir.absolutePath) ``` #### `serverName(name: String): ClientBuilder` Sets the server name explicitly (usually extracted from User ID). ```kotlin builder.serverName("matrix.org") ``` #### `passphrase(passphrase: String?): ClientBuilder` Sets an optional passphrase for encrypting stored credentials. ```kotlin builder.passphrase("my_secure_passphrase") ``` #### `build(): Client` (suspend) Creates and returns the configured Client instance. ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath("/data/session") .serverName("matrix.org") .build() ``` ``` -------------------------------- ### Get Display Name Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Fetch the user's display name from their profile. This is a suspend function. ```kotlin val name = client.displayName() ``` -------------------------------- ### Upload Media and Send Image Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Upload media data (e.g., an image) to the homeserver and then send it as an image message in a room. ```kotlin val url = client.uploadMedia( mimeType = "image/jpeg", data = imageBytes, filename = "photo.jpg" ) room.sendImage(MediaSource(url), null) ``` -------------------------------- ### OlmMachine Creation Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Instantiates the core cryptography engine with user ID, device ID, and storage path. ```APIDOC ## OlmMachine Creation Instantiates the core cryptography engine. ### Constructor ```kotlin OlmMachine( userId: String, deviceId: String, path: String ) ``` ### Parameters - **userId** (String) - Required - The user ID. - **deviceId** (String) - Required - The device ID. - **path** (String) - Required - The path to the crypto state storage. ``` -------------------------------- ### Get Main Room List Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md Fetches the primary list of rooms managed by the RoomListService. This is a suspend function. ```kotlin val list = service.roomList() ``` -------------------------------- ### Verification Request - Get Room ID Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the room ID where the device verification request originated. ```kotlin val roomId = request.roomId() ``` -------------------------------- ### Build SDK/Crypto Library Binaries Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/README.md Use this script to build the SDK or crypto library binaries from the matrix-rust-sdk repository. Specify the path to the SDK and the module (sdk/crypto). The -r flag produces a release build. ```bash # To build the SDK/crypto library binaries from the matrix-rust-sdk repo: ./scripts/build.sh -p -m -r ``` ```bash # To build the main crate (eg, for Element-X): ./scripts/build.sh -p -m sdk -l ``` ```bash # Or: ./scripts/build.sh -p -m sdk -t ``` ```bash # To build just the crypto crate (eg, for Element Android classic), use this instead: ./scripts/build.sh -p -m crypto -l ``` -------------------------------- ### Get Room by ID Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve a specific room using its ID. Returns null if the room is not found. ```kotlin val room = client.roomOrNull("!abc:matrix.org") ``` -------------------------------- ### Login with Username and Password Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Perform a homeserver login using username and password credentials. Ensure the homeserver supports password authentication. ```kotlin val loginDetails = client.homeserverLoginDetails() if (loginDetails.supportsPassword()) { val credentials = PasswordAuthData( identifier = "alice@matrix.org", password = "secret" ) client.login(credentials, "My Device") } ``` -------------------------------- ### Build SDK/Crypto Library with Output Directory Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/README.md This command builds the SDK or crypto library and allows you to specify an output directory for the generated AAR file using the -o flag. The -r flag produces a release build. ```bash # Other useful flags: # -o OUTPUT_DIR: Moves the generated AAR file to the dir OUTPUT_DIR. # -r: Produces a release build instead of a development one. ``` -------------------------------- ### Get Parent Spaces of a Room Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieve a list of all spaces that a given room belongs to, including their display names. ```kotlin val parents = room.parentSpaces() for (parent in parents) { println("Parent: ${parent.displayName()}") } ``` -------------------------------- ### Set Media Path Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Specify the directory for storing downloaded media cache. ```kotlin builder.mediaPath(context.cacheDir.absolutePath) ``` -------------------------------- ### Get Room Avatar URL Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves the avatar URL for a Matrix room. Returns null if no avatar is set. ```kotlin val avatar = room.avatarUrl() ``` -------------------------------- ### Verification Session - Get QR Code Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the QR code object if it is available for the current verification session. ```kotlin val qr = verification.qrCode() ``` -------------------------------- ### Import SDK Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Import necessary classes from the Matrix Rust Components SDK for Kotlin. ```kotlin import org.matrix.rustcomponents.sdk.* import org.matrix.rustcomponents.sdk.crypto.* ``` -------------------------------- ### Verification Session - Get Other Request Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the associated verification request object if the session was initiated by another user. ```kotlin val request = verification.other() ``` -------------------------------- ### Client Lifecycle with Try-With-Resources Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Use this pattern for automatic cleanup of client and sync service resources. Ensures `destroy()` is called on `Client` and `SyncService`. ```kotlin ClientBuilder().build().use { client -> client.syncService().use { syncService -> syncService.start() } } // Automatic cleanup ``` -------------------------------- ### Verification Request - Get Other User ID Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the user ID of the person initiating the device verification request. ```kotlin val theirId = request.otherUserId() ``` -------------------------------- ### Enable Cross-Process Synchronization Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Enable experimental cross-process synchronization for the Matrix client. ```kotlin builder.initCrossProcess(true) ``` -------------------------------- ### Send a Message Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/README.md Demonstrates how to initialize a Matrix client and send a simple text message to a specified room. ```APIDOC ## Send a Message ### Description Initializes a Matrix client and sends a text message to a room. ### Method POST (implied by sendMessage) ### Endpoint Not explicitly defined, but relates to room operations. ### Parameters #### Path Parameters None explicitly defined. #### Query Parameters None explicitly defined. #### Request Body None explicitly defined for `sendMessage`. ### Request Example ```kotlin val client = ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath("/path/to/session") .serverName("matrix.org") .build() client.roomOrNull("!roomid:matrix.org")?.use { room -> room.sendMessage("Hello!") } ``` ### Response #### Success Response (200) Indicates successful message delivery. #### Response Example None explicitly defined. ``` -------------------------------- ### Enable Encryption Backups Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Initiate the process to enable end-to-end encryption backups to the server. This is a suspend function and may take time to complete. ```kotlin encryption.enableBackups() ``` -------------------------------- ### Commit Sign-off Example Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/CONTRIBUTING.md The required format for signing off a contribution in a commit or pull request comment. This confirms agreement with the DCO. ```git Signed-off-by: Your Name ``` -------------------------------- ### Room Lifecycle Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Demonstrates how to obtain a Room object, send messages, and properly destroy the room instance to release resources. It also shows usage with AutoCloseable for automatic resource management. ```APIDOC ## Room Lifecycle ### Description Demonstrates how to obtain a Room object, send messages, and properly destroy the room instance to release resources. It also shows usage with AutoCloseable for automatic resource management. ### Usage ```kotlin val room = client.roomOrNull("!abc:matrix.org") try { // Use room room.sendMessage("Hello") } finally { room.destroy() } // Or using AutoCloseable client.roomOrNull("!abc:matrix.org")?.use { room -> room.sendMessage("Hello") } ``` ``` -------------------------------- ### Get Current Device Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieves the unique identifier for the current device. This is often used in conjunction with other device management operations. ```APIDOC ## Get Current Device Retrieves the ID of the current device. ### Method Signature ```kotlin val deviceId = client.deviceId() val displayName = "My iPhone" ``` ``` -------------------------------- ### Get Account Data Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieve user-level account data for a specified event type. The returned data is a JSON string. ```kotlin val directRooms = client.accountData("m.direct") // Returns JSON string ``` -------------------------------- ### Project Structure Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/01-overview.md Illustrates the directory layout of the matrix-rust-components-kotlin project, showing the organization of SDK and Crypto modules for both Android and JVM platforms, along with build and script directories. ```tree matrix-rust-components-kotlin/ ├── sdk/ │ ├── sdk-android/ # Android SDK bindings │ │ └── src/main/kotlin/ │ │ ├── org/matrix/rustcomponents/sdk/ │ │ └── uniffi/ # Generated UniFFI bindings │ └── sdk-jvm/ # JVM SDK bindings ├── crypto/ │ ├── crypto-android/ # Android crypto bindings │ │ └── src/main/kotlin/ │ └── crypto-jvm/ # JVM crypto bindings ├── buildSrc/ # Gradle build configuration └── scripts/ # Build and release scripts ``` -------------------------------- ### Release Built SDK/Crypto Library to Maven Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/README.md This script publishes the built SDK or crypto library binaries to the Maven repository. You need to provide the version, a linkable reference (SDK branch or SHA), and the module name. ```python python3 ./scripts/publish_release.py --version --linkable-ref --module ``` -------------------------------- ### Get Room Canonical Alias Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves the primary alias for a Matrix room. Returns null if no primary alias is set. ```kotlin val alias = room.canonicalAlias() ``` -------------------------------- ### Set Login Path Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Configure the filesystem path for caching the login flow. ```kotlin builder.loginPath("/path/to/login/cache") ``` -------------------------------- ### Get Room Display Name Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves the display name of a Matrix room. Returns null if the display name is not set. ```kotlin val name = room.displayName() ``` -------------------------------- ### Verification Session - Get SAS Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the SAS (Short Authentication String) object if it is available for the current verification session. ```kotlin val sas = verification.sas() if (sas != null) { val emojis = sas.emoji() } ``` -------------------------------- ### Client Resource Management Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Safely manage Client resources using try-with-resources or explicit cleanup with destroy(). ```kotlin // Using try-with-resources client.use { it.syncService().use { syncService -> syncService.start() } } ``` ```kotlin // Or explicit cleanup try { // Use client } finally { client.destroy() } ``` -------------------------------- ### Username/Password Login Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Log in to the homeserver using username and password credentials. ```APIDOC ### Username/Password Login ```kotlin val credentials = HomeserverLoginDetails.LoginCredentials( address = "alice@matrix.org", password = "secret" ) client.login(credentials, "My Device") ``` ``` -------------------------------- ### Provide Matrix Client with Hilt Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Provides the Matrix client as a singleton dependency using Hilt. Configures the homeserver URL and session path for the client. ```kotlin @Module @InstallIn(SingletonComponent::class) object MatrixModule { @Singleton @Provides fun provideMatrixClient(context: Context): Client { return ClientBuilder() .homeserverUrl("https://matrix.org") .sessionPath(context.filesDir.absolutePath) .build() } } ``` -------------------------------- ### OAuthAuthorizationData Class Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/03-types.md Handles data for the OAuth 2.0 authorization flow. Use the loginUrl() method to get the URL for the browser. ```kotlin open class OAuthAuthorizationData { fun loginUrl(): String } ``` ```kotlin val oauthData = client.startOauthAuth() val url = oauthData.loginUrl() // Open in browser ``` -------------------------------- ### Enable Logging Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/09-quick-reference.md Sets the log level for the 'MatrixSDK' tag to DEBUG, enabling detailed logging. ```kotlin Log.setLoggable("MatrixSDK", Log.DEBUG) ``` -------------------------------- ### MediaSource URL and Filename Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/03-types.md Represents a media source, providing its mxc:// URL and an optional filename. ```kotlin open class MediaSource { fun url(): String // mxc:// URL suspend fun getFileName(): String? // Filename if known } ``` -------------------------------- ### Get Account Data Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieves arbitrary user-level data stored for the account. This function fetches data based on the event type. ```APIDOC ## Get Account Data Retrieves user-specific data. ### Method Signature ```kotlin val directRooms = client.accountData("m.direct") // Returns JSON string ``` ``` -------------------------------- ### Get Send Queue Metrics in Kotlin Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves metrics related to the message send queue for the room, such as the number of messages sent. ```kotlin val metrics = room.sendQueueMetrics() println("${metrics.sentCount} messages sent") ``` -------------------------------- ### Bootstrap Cross-Signing Keys Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Initializes the cross-signing keys for end-to-end encryption. The result contains requests that must be sent to the server. ```kotlin val result = client.encryption().bootstrapCrossSigning() // Send returned requests to server ``` -------------------------------- ### Get Space Children Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves a list of child rooms that belong to a space. This function is typically called after confirming a room is a space. ```kotlin val children = room.spaceChildren() ``` -------------------------------- ### Join Room Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Initiates the process of joining the current room. ```kotlin room.join() ``` -------------------------------- ### Get Pinned Messages Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/04-room-api.md Retrieves a list of EventIds for all messages that are currently pinned in the room. This is useful for quickly accessing important messages. ```kotlin val pinned = room.pinnedMessages() ``` -------------------------------- ### Manage Room List with Filters and Search Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/06-timeline-sync-api.md Shows how to obtain and interact with the Room List Service to subscribe to room updates, add/remove filters, and perform searches. Useful for displaying and filtering rooms in a UI. ```kotlin client.syncService().use { syncService -> val roomListService = syncService.roomListService() roomListService.roomList().use { roomList -> // Subscribe to updates roomList.subscribe(20u).collect { updates -> for (item in updates.items) { when (item) { is RoomListItemJoined -> { println("Room: ${item.roomId}") println("Unread: ${item.unreadCount}") } is RoomListItemInvited -> { println("Invited to: ${item.roomId}") } else -> {} } } } // Add filters roomList.addFilter(RoomListEntriesDynamicFilterKind.Unread) // Search roomList.search("matrix") // Remove filter roomList.removeFilter(RoomListEntriesDynamicFilterKind.Unread) } } ``` -------------------------------- ### Verification Request - Get Available Flows Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Retrieves the available verification methods (flows) for the current request, such as SAS or QR code. ```kotlin val flow = request.flow() // flow.sas, flow.qrCode, etc. ``` -------------------------------- ### Generate Media Thumbnail Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Create a thumbnail for a given media URL with specified dimensions and resizing method. Useful for displaying previews. ```kotlin val thumb = client.getThumbnail( url = "mxc://matrix.org/abc123", width = 256u, height = 256u, resizingMethod = ResizingMethod.Crop ) ``` -------------------------------- ### Get Encryption Status Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/05-crypto-api.md Check the current state of the encryption module. Use this to determine if encryption is enabled, disabled, or in a pre-setup state. ```kotlin when (encryption.status()) { EncryptionState.Unknown -> { /* Unknown */ } EncryptionState.Enabled -> { /* Enabled */ } EncryptionState.Disabled -> { /* Disabled */ } EncryptionState.Pregame -> { /* Pre-setup */ } } ``` -------------------------------- ### Get Cached Avatar URL Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Retrieve a cached avatar URL without making new network requests. This is a suspend function. ```kotlin val cached = client.cachedAvatarUrl() ``` -------------------------------- ### Discover Sliding Sync Versions Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Asynchronously discover the available sliding sync versions supported by the homeserver. This involves making requests to the `.well-known` and `/versions` endpoints. ```kotlin val versions = client.availableSlidingSyncVersions() for (version in versions) { println("Sliding sync ${version.version}") } ``` -------------------------------- ### Search and Discovery Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Search for users on the homeserver and obtain a client for managing push notifications. ```APIDOC ## searchUsers(searchTerm: String, limit: UInt) ### Description Searches for users on the homeserver. ### Method `suspend fun searchUsers(searchTerm: String, limit: UInt): List` ### Parameters * `searchTerm` (String) - Required - The term to search for. * `limit` (UInt) - Required - The maximum number of results to return. ### Usage Example ```kotlin val results = client.searchUsers("alice", 20u) for (user in results) { println("${user.userId}: ${user.displayName}") } ``` ``` ```APIDOC ## notificationClient() ### Description Returns a client for handling push notifications. ### Method `suspend fun notificationClient(): NotificationClient` ### Usage Example ```kotlin val notifClient = client.notificationClient() ``` ``` -------------------------------- ### Get Avatar URL Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/02-client-api.md Fetch the user's avatar URL from their profile. Returns null if no avatar is set. This is a suspend function. ```kotlin val avatarUrl = client.avatarUrl() ``` -------------------------------- ### Enable Guest Access in Kotlin Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Allow users to access a room without joining or logging in by enabling guest access. ```kotlin room.setGuestAccess(true) ``` -------------------------------- ### SDK Version Migration Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Existing sessions are automatically migrated when upgrading the SDK version. If migration fails, sessions can be cleared to start fresh. ```kotlin // Old SDK version val oldClient = ClientBuilder().build() oldClient.destroy() ``` ```kotlin // New SDK version val newClient = ClientBuilder().build() // Session automatically migrated ``` ```kotlin context.filesDir.deleteRecursively() val client = ClientBuilder().build() // Fresh start ``` -------------------------------- ### Room Configuration Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/07-configuration.md Methods for managing room visibility and guest access. ```APIDOC ## setRoomVisibility(roomId: String, public: Boolean) (suspend) Sets whether a room is listed in the directory. ### Request Example ```kotlin client.setRoomVisibility("!abc:matrix.org", true) ``` ``` ```APIDOC ## setRoomGuestAccess(roomId: String, allowGuests: Boolean) (suspend) Enables guest access to a room. ### Request Example ```kotlin client.setRoomGuestAccess("!abc:matrix.org", false) ``` ``` -------------------------------- ### List All Devices Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieve a list of all devices associated with the user's account. Each device object contains its ID and display name. ```kotlin val devices = client.devices() for (device in devices) { println("${device.id}: ${device.displayName}") } ``` -------------------------------- ### Get Read Receipts for Event Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieves all read receipts for a given timeline item. This allows you to see which users have read a specific message and when. ```APIDOC ## Get Read Receipts for Event Retrieves read receipts for a specific event. ### Method Signature ```kotlin val receipts = timelineItem.readReceipts for ((userId, receipt) in receipts) { println("$userId read at ${receipt.timestamp}") } ``` ``` -------------------------------- ### Reference Documentation in Kotlin Code Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/README.md Use this format to add comments in your Kotlin code that link directly to specific sections of the project's documentation. ```kotlin // See documentation/04-room-api.md#send-message room.sendMessage("Hello") ``` -------------------------------- ### Get Read Receipts for an Event Source: https://github.com/matrix-org/matrix-rust-components-kotlin/blob/main/_autodocs/10-advanced-features.md Retrieve all read receipts for a given timeline item. Iterates through user IDs and their corresponding receipt timestamps. ```kotlin val receipts = timelineItem.readReceipts for ((userId, receipt) in receipts) { println("$userId read at ${receipt.timestamp}") } ```