Changes code style method parameters new line around parentheses to true

This commit is contained in:
ericdecanini 2022-05-23 12:30:42 +02:00
parent 98999c754f
commit 3f3662e605
539 changed files with 5638 additions and 3997 deletions

View File

@ -810,8 +810,8 @@ ij_kotlin_line_comment_add_space = false
ij_kotlin_line_comment_at_first_column = true ij_kotlin_line_comment_at_first_column = true
ij_kotlin_method_annotation_wrap = split_into_lines ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = off ij_kotlin_method_call_chain_wrap = off
ij_kotlin_method_parameters_new_line_after_left_paren = false ij_kotlin_method_parameters_new_line_after_left_paren = true
ij_kotlin_method_parameters_right_paren_on_new_line = false ij_kotlin_method_parameters_right_paren_on_new_line = true
ij_kotlin_method_parameters_wrap = off ij_kotlin_method_parameters_wrap = off
ij_kotlin_name_count_to_use_star_import = 2147483647 ij_kotlin_name_count_to_use_star_import = 2147483647
ij_kotlin_name_count_to_use_star_import_for_members = 2147483647 ij_kotlin_name_count_to_use_star_import_for_members = 2147483647

View File

@ -216,7 +216,8 @@ class CommonTestHelper(context: Context) {
message: String, message: String,
numberOfMessages: Int, numberOfMessages: Int,
rootThreadEventId: String, rootThreadEventId: String,
timeout: Long = TestConstants.timeOutMillis): List<TimelineEvent> { timeout: Long = TestConstants.timeOutMillis
): List<TimelineEvent> {
val timeline = room.timelineService().createTimeline(null, TimelineSettings(10)) val timeline = room.timelineService().createTimeline(null, TimelineSettings(10))
timeline.start() timeline.start()
val sentEvents = sendTextMessagesBatched(timeline, room, message, numberOfMessages, timeout, rootThreadEventId) val sentEvents = sendTextMessagesBatched(timeline, room, message, numberOfMessages, timeout, rootThreadEventId)
@ -236,9 +237,11 @@ class CommonTestHelper(context: Context) {
* @param testParams test params about the session * @param testParams test params about the session
* @return the session associated with the newly created account * @return the session associated with the newly created account
*/ */
private fun createAccount(userNamePrefix: String, private fun createAccount(
userNamePrefix: String,
password: String, password: String,
testParams: SessionTestParams): Session { testParams: SessionTestParams
): Session {
val session = createAccountAndSync( val session = createAccountAndSync(
userNamePrefix + "_" + accountNumber++ + "_" + UUID.randomUUID(), userNamePrefix + "_" + accountNumber++ + "_" + UUID.randomUUID(),
password, password,
@ -256,9 +259,11 @@ class CommonTestHelper(context: Context) {
* @param testParams test params about the session * @param testParams test params about the session
* @return the session associated with the existing account * @return the session associated with the existing account
*/ */
fun logIntoAccount(userId: String, fun logIntoAccount(
userId: String,
password: String, password: String,
testParams: SessionTestParams): Session { testParams: SessionTestParams
): Session {
val session = logAccountAndSync(userId, password, testParams) val session = logAccountAndSync(userId, password, testParams)
assertNotNull(session) assertNotNull(session)
return session return session
@ -271,9 +276,11 @@ class CommonTestHelper(context: Context) {
* @param password the password * @param password the password
* @param sessionTestParams parameters for the test * @param sessionTestParams parameters for the test
*/ */
private fun createAccountAndSync(userName: String, private fun createAccountAndSync(
userName: String,
password: String, password: String,
sessionTestParams: SessionTestParams): Session { sessionTestParams: SessionTestParams
): Session {
val hs = createHomeServerConfig() val hs = createHomeServerConfig()
runBlockingTest { runBlockingTest {
@ -309,9 +316,11 @@ class CommonTestHelper(context: Context) {
* @param password the password * @param password the password
* @param sessionTestParams session test params * @param sessionTestParams session test params
*/ */
private fun logAccountAndSync(userName: String, private fun logAccountAndSync(
userName: String,
password: String, password: String,
sessionTestParams: SessionTestParams): Session { sessionTestParams: SessionTestParams
): Session {
val hs = createHomeServerConfig() val hs = createHomeServerConfig()
runBlockingTest { runBlockingTest {
@ -337,8 +346,10 @@ class CommonTestHelper(context: Context) {
* @param userName the account username * @param userName the account username
* @param password the password * @param password the password
*/ */
fun logAccountWithError(userName: String, fun logAccountWithError(
password: String): Throwable { userName: String,
password: String
): Throwable {
val hs = createHomeServerConfig() val hs = createHomeServerConfig()
runBlockingTest { runBlockingTest {

View File

@ -18,8 +18,10 @@ package org.matrix.android.sdk.common
import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.Session
data class CryptoTestData(val roomId: String, data class CryptoTestData(
val sessions: List<Session>) { val roomId: String,
val sessions: List<Session>
) {
val firstSession: Session val firstSession: Session
get() = sessions.first() get() = sessions.first()

View File

@ -73,9 +73,11 @@ class MockOkHttpInterceptor : TestInterceptor {
/** /**
* Simple rule that reply with the given body for any request that matches the match param * Simple rule that reply with the given body for any request that matches the match param
*/ */
class SimpleRule(match: String, class SimpleRule(
match: String,
private val code: Int = HttpsURLConnection.HTTP_OK, private val code: Int = HttpsURLConnection.HTTP_OK,
private val body: String = "{}") : Rule(match) { private val body: String = "{}"
) : Rule(match) {
override fun process(originalRequest: Request): Response? { override fun process(originalRequest: Request): Response? {
return Response.Builder() return Response.Builder()

View File

@ -27,8 +27,10 @@ import java.util.concurrent.CountDownLatch
* @param onlySuccessful true to fail if an error occurs. This is the default behavior * @param onlySuccessful true to fail if an error occurs. This is the default behavior
* @param <T> * @param <T>
*/ */
open class TestMatrixCallback<T>(private val countDownLatch: CountDownLatch, open class TestMatrixCallback<T>(
private val onlySuccessful: Boolean = true) : MatrixCallback<T> { private val countDownLatch: CountDownLatch,
private val onlySuccessful: Boolean = true
) : MatrixCallback<T> {
@CallSuper @CallSuper
override fun onSuccess(data: T) { override fun onSuccess(data: T) {

View File

@ -47,7 +47,9 @@ internal interface TestMatrixComponent : MatrixComponent {
@Component.Factory @Component.Factory
interface Factory { interface Factory {
fun create(@BindsInstance context: Context, fun create(
@BindsInstance matrixConfiguration: MatrixConfiguration): TestMatrixComponent @BindsInstance context: Context,
@BindsInstance matrixConfiguration: MatrixConfiguration
): TestMatrixComponent
} }
} }

View File

@ -83,7 +83,8 @@ class ExportEncryptionTest {
@Test @Test
fun checkExportDecrypt1() { fun checkExportDecrypt1() {
val password = "password" val password = "password"
val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXNhbHRzYWx0c2FsdHNhbHSIiIiIiIiIiIiIiIiIiIiIAAAACmIRUW2OjZ3L2l6j9h0lHlV3M2dx\n" + "cissyYBxjsfsAndErh065A8=\n-----END MEGOLM SESSION DATA-----" val input =
"-----BEGIN MEGOLM SESSION DATA-----\nAXNhbHRzYWx0c2FsdHNhbHSIiIiIiIiIiIiIiIiIiIiIAAAACmIRUW2OjZ3L2l6j9h0lHlV3M2dx\n" + "cissyYBxjsfsAndErh065A8=\n-----END MEGOLM SESSION DATA-----"
val expectedString = "plain" val expectedString = "plain"
var decodedString: String? = null var decodedString: String? = null
@ -103,7 +104,8 @@ class ExportEncryptionTest {
@Test @Test
fun checkExportDecrypt2() { fun checkExportDecrypt2() {
val password = "betterpassword" val password = "betterpassword"
val input = "-----BEGIN MEGOLM SESSION DATA-----\nAW1vcmVzYWx0bW9yZXNhbHT//////////wAAAAAAAAAAAAAD6KyBpe1Niv5M5NPm4ZATsJo5nghk\n" + "KYu63a0YQ5DRhUWEKk7CcMkrKnAUiZny\n-----END MEGOLM SESSION DATA-----" val input =
"-----BEGIN MEGOLM SESSION DATA-----\nAW1vcmVzYWx0bW9yZXNhbHT//////////wAAAAAAAAAAAAAD6KyBpe1Niv5M5NPm4ZATsJo5nghk\n" + "KYu63a0YQ5DRhUWEKk7CcMkrKnAUiZny\n-----END MEGOLM SESSION DATA-----"
val expectedString = "Hello, World" val expectedString = "Hello, World"
var decodedString: String? = null var decodedString: String? = null
@ -123,7 +125,8 @@ class ExportEncryptionTest {
@Test @Test
fun checkExportDecrypt3() { fun checkExportDecrypt3() {
val password = "SWORDFISH" val password = "SWORDFISH"
val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXllc3NhbHR5Z29vZG5lc3P//////////wAAAAAAAAAAAAAD6OIW+Je7gwvjd4kYrb+49gKCfExw\n" + "MgJBMD4mrhLkmgAngwR1pHjbWXaoGybtiAYr0moQ93GrBQsCzPbvl82rZhaXO3iH5uHo/RCEpOqp\nPgg29363BGR+/Ripq/VCLKGNbw==\n-----END MEGOLM SESSION DATA-----" val input =
"-----BEGIN MEGOLM SESSION DATA-----\nAXllc3NhbHR5Z29vZG5lc3P//////////wAAAAAAAAAAAAAD6OIW+Je7gwvjd4kYrb+49gKCfExw\n" + "MgJBMD4mrhLkmgAngwR1pHjbWXaoGybtiAYr0moQ93GrBQsCzPbvl82rZhaXO3iH5uHo/RCEpOqp\nPgg29363BGR+/Ripq/VCLKGNbw==\n-----END MEGOLM SESSION DATA-----"
val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically" val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically"
var decodedString: String? = null var decodedString: String? = null
@ -202,7 +205,8 @@ class ExportEncryptionTest {
@Test @Test
fun checkExportEncrypt4() { fun checkExportEncrypt4() {
val password = "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" val password =
"passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword"
val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically" val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically"
var decodedString: String? = null var decodedString: String? = null

View File

@ -33,7 +33,8 @@ import java.util.concurrent.CountDownLatch
internal class KeysBackupTestHelper( internal class KeysBackupTestHelper(
private val testHelper: CommonTestHelper, private val testHelper: CommonTestHelper,
private val cryptoTestHelper: CryptoTestHelper) { private val cryptoTestHelper: CryptoTestHelper
) {
fun waitForKeybackUpBatching() { fun waitForKeybackUpBatching() {
Thread.sleep(400) Thread.sleep(400)
@ -96,8 +97,10 @@ internal class KeysBackupTestHelper(
) )
} }
fun prepareAndCreateKeysBackupData(keysBackup: KeysBackupService, fun prepareAndCreateKeysBackupData(
password: String? = null): PrepareKeysBackupDataResult { keysBackup: KeysBackupService,
password: String? = null
): PrepareKeysBackupDataResult {
val stateObserver = StateObserver(keysBackup) val stateObserver = StateObserver(keysBackup)
val megolmBackupCreationInfo = testHelper.doSync<MegolmBackupCreationInfo> { val megolmBackupCreationInfo = testHelper.doSync<MegolmBackupCreationInfo> {
@ -169,9 +172,11 @@ internal class KeysBackupTestHelper(
* - The new device must have the same count of megolm keys * - The new device must have the same count of megolm keys
* - Alice must have the same keys on both devices * - Alice must have the same keys on both devices
*/ */
fun checkRestoreSuccess(testData: KeysBackupScenarioData, fun checkRestoreSuccess(
testData: KeysBackupScenarioData,
total: Int, total: Int,
imported: Int) { imported: Int
) {
// - Imported keys number must be correct // - Imported keys number must be correct
Assert.assertEquals(testData.aliceKeys.size, total) Assert.assertEquals(testData.aliceKeys.size, total)
Assert.assertEquals(total, imported) Assert.assertEquals(total, imported)

View File

@ -18,5 +18,7 @@ package org.matrix.android.sdk.internal.crypto.keysbackup
import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo
data class PrepareKeysBackupDataResult(val megolmBackupCreationInfo: MegolmBackupCreationInfo, data class PrepareKeysBackupDataResult(
val version: String) val megolmBackupCreationInfo: MegolmBackupCreationInfo,
val version: String
)

View File

@ -27,9 +27,11 @@ import java.util.concurrent.CountDownLatch
* This class observe the state change of a KeysBackup object and provide a method to check the several state change * This class observe the state change of a KeysBackup object and provide a method to check the several state change
* It checks all state transitions and detected forbidden transition * It checks all state transitions and detected forbidden transition
*/ */
internal class StateObserver(private val keysBackup: KeysBackupService, internal class StateObserver(
private val keysBackup: KeysBackupService,
private val latch: CountDownLatch? = null, private val latch: CountDownLatch? = null,
private val expectedStateChange: Int = -1) : KeysBackupStateListener { private val expectedStateChange: Int = -1
) : KeysBackupStateListener {
private val allowedStateTransitions = listOf( private val allowedStateTransitions = listOf(
KeysBackupState.BackingUp to KeysBackupState.ReadyToBackUp, KeysBackupState.BackingUp to KeysBackupState.ReadyToBackUp,

View File

@ -281,14 +281,16 @@ class SASTest : InstrumentedTest {
cryptoTestData.cleanUp(testHelper) cryptoTestData.cleanUp(testHelper)
} }
private fun fakeBobStart(bobSession: Session, private fun fakeBobStart(
bobSession: Session,
aliceUserID: String?, aliceUserID: String?,
aliceDevice: String?, aliceDevice: String?,
tid: String, tid: String,
protocols: List<String> = SASDefaultVerificationTransaction.KNOWN_AGREEMENT_PROTOCOLS, protocols: List<String> = SASDefaultVerificationTransaction.KNOWN_AGREEMENT_PROTOCOLS,
hashes: List<String> = SASDefaultVerificationTransaction.KNOWN_HASHES, hashes: List<String> = SASDefaultVerificationTransaction.KNOWN_HASHES,
mac: List<String> = SASDefaultVerificationTransaction.KNOWN_MACS, mac: List<String> = SASDefaultVerificationTransaction.KNOWN_MACS,
codes: List<String> = SASDefaultVerificationTransaction.KNOWN_SHORT_CODES) { codes: List<String> = SASDefaultVerificationTransaction.KNOWN_SHORT_CODES
) {
val startMessage = KeyVerificationStart( val startMessage = KeyVerificationStart(
fromDevice = bobSession.cryptoService().getMyDevice().deviceId, fromDevice = bobSession.cryptoService().getMyDevice().deviceId,
method = VerificationMethod.SAS.toValue(), method = VerificationMethod.SAS.toValue(),

View File

@ -151,10 +151,12 @@ class VerificationTest : InstrumentedTest {
// TODO Add tests without SAS // TODO Add tests without SAS
private fun doTest(aliceSupportedMethods: List<VerificationMethod>, private fun doTest(
aliceSupportedMethods: List<VerificationMethod>,
bobSupportedMethods: List<VerificationMethod>, bobSupportedMethods: List<VerificationMethod>,
expectedResultForAlice: ExpectedResult, expectedResultForAlice: ExpectedResult,
expectedResultForBob: ExpectedResult) { expectedResultForBob: ExpectedResult
) {
val testHelper = CommonTestHelper(context()) val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper) val cryptoTestHelper = CryptoTestHelper(testHelper)
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom()

View File

@ -289,9 +289,11 @@ class MarkdownParserTest : InstrumentedTest {
markdownParser.parse(text).expect(text, null) markdownParser.parse(text).expect(text, null)
} }
private fun testType(name: String, private fun testType(
name: String,
markdownPattern: String, markdownPattern: String,
htmlExpectedTag: String) { htmlExpectedTag: String
) {
// Test simple case // Test simple case
"$markdownPattern$name$markdownPattern" "$markdownPattern$name$markdownPattern"
.let { .let {
@ -376,10 +378,12 @@ class MarkdownParserTest : InstrumentedTest {
} }
} }
private fun testTypeNewLines(name: String, private fun testTypeNewLines(
name: String,
markdownPattern: String, markdownPattern: String,
htmlExpectedTag: String, htmlExpectedTag: String,
softBreak: String = "<br />") { softBreak: String = "<br />"
) {
// With new line inside the block // With new line inside the block
"$markdownPattern$name\n$name$markdownPattern" "$markdownPattern$name\n$name$markdownPattern"
.let { .let {

View File

@ -154,9 +154,11 @@ internal class ChunkEntityTest : InstrumentedTest {
} }
} }
private fun ChunkEntity.addAll(roomId: String, private fun ChunkEntity.addAll(
roomId: String,
events: List<Event>, events: List<Event>,
direction: PaginationDirection) { direction: PaginationDirection
) {
events.forEach { event -> events.forEach { event ->
val fakeEvent = event.toEntity(roomId, SendState.SYNCED, clock.epochMillis()).let { val fakeEvent = event.toEntity(roomId, SendState.SYNCED, clock.epochMillis()).let {
realm.copyToRealm(it) realm.copyToRealm(it)

View File

@ -19,7 +19,8 @@ package org.matrix.android.sdk.session.room.timeline
import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.Event
import org.matrix.android.sdk.internal.session.room.timeline.TokenChunkEvent import org.matrix.android.sdk.internal.session.room.timeline.TokenChunkEvent
internal data class FakeTokenChunkEvent(override val start: String?, internal data class FakeTokenChunkEvent(
override val start: String?,
override val end: String?, override val end: String?,
override val events: List<Event> = emptyList(), override val events: List<Event> = emptyList(),
override val stateEvents: List<Event> = emptyList() override val stateEvents: List<Event> = emptyList()

View File

@ -41,7 +41,8 @@ object RoomDataHelper {
} }
} }
private fun createFakeEvent(type: String, private fun createFakeEvent(
type: String,
content: Content? = null, content: Content? = null,
prevContent: Content? = null, prevContent: Content? = null,
sender: String = FAKE_TEST_SENDER, sender: String = FAKE_TEST_SENDER,

View File

@ -390,7 +390,8 @@ class SpaceHierarchyTest : InstrumentedTest {
val roomIds: List<String> val roomIds: List<String>
) )
private fun createPublicSpace(session: Session, private fun createPublicSpace(
session: Session,
spaceName: String, spaceName: String,
childInfo: List<Triple<String, Boolean, Boolean?>> childInfo: List<Triple<String, Boolean, Boolean?>>
/** Name, auto-join, canonical*/ /** Name, auto-join, canonical*/
@ -418,7 +419,8 @@ class SpaceHierarchyTest : InstrumentedTest {
return TestSpaceCreationResult(spaceId, roomIds) return TestSpaceCreationResult(spaceId, roomIds)
} }
private fun createPrivateSpace(session: Session, private fun createPrivateSpace(
session: Session,
spaceName: String, spaceName: String,
childInfo: List<Triple<String, Boolean, Boolean?>> childInfo: List<Triple<String, Boolean, Boolean?>>
/** Name, auto-join, canonical*/ /** Name, auto-join, canonical*/

View File

@ -93,14 +93,18 @@ interface AuthenticationService {
/** /**
* Create a session after a SSO successful login. * Create a session after a SSO successful login.
*/ */
suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig, suspend fun createSessionFromSso(
credentials: Credentials): Session homeServerConnectionConfig: HomeServerConnectionConfig,
credentials: Credentials
): Session
/** /**
* Perform a wellknown request, using the domain from the matrixId. * Perform a wellknown request, using the domain from the matrixId.
*/ */
suspend fun getWellKnownData(matrixId: String, suspend fun getWellKnownData(
homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult matrixId: String,
homeServerConnectionConfig: HomeServerConnectionConfig?
): WellknownResult
/** /**
* Authenticate with a matrixId and a password. * Authenticate with a matrixId and a password.
@ -111,9 +115,11 @@ interface AuthenticationService {
* @param initialDeviceName the initial device name * @param initialDeviceName the initial device name
* @param deviceId the device id, optional. If not provided or null, the server will generate one. * @param deviceId the device id, optional. If not provided or null, the server will generate one.
*/ */
suspend fun directAuthentication(homeServerConnectionConfig: HomeServerConnectionConfig, suspend fun directAuthentication(
homeServerConnectionConfig: HomeServerConnectionConfig,
matrixId: String, matrixId: String,
password: String, password: String,
initialDeviceName: String, initialDeviceName: String,
deviceId: String? = null): Session deviceId: String? = null
): Session
} }

View File

@ -41,8 +41,10 @@ import org.matrix.android.sdk.api.auth.registration.TermPolicies
* @param userLanguage the user language * @param userLanguage the user language
* @param defaultLanguage the default language to use if the user language is not found for a policy in registrationFlowResponse * @param defaultLanguage the default language to use if the user language is not found for a policy in registrationFlowResponse
*/ */
fun TermPolicies.toLocalizedLoginTerms(userLanguage: String, fun TermPolicies.toLocalizedLoginTerms(
defaultLanguage: String = "en"): List<LocalizedFlowDataLoginTerms> { userLanguage: String,
defaultLanguage: String = "en"
): List<LocalizedFlowDataLoginTerms> {
val result = ArrayList<LocalizedFlowDataLoginTerms>() val result = ArrayList<LocalizedFlowDataLoginTerms>()
val policies = get("policies") val policies = get("policies")

View File

@ -39,10 +39,12 @@ interface LoginWizard {
* @param deviceId the device id, optional. If not provided or null, the server will generate one. * @param deviceId the device id, optional. If not provided or null, the server will generate one.
* @return a [Session] if the login is successful * @return a [Session] if the login is successful
*/ */
suspend fun login(login: String, suspend fun login(
login: String,
password: String, password: String,
initialDeviceName: String, initialDeviceName: String,
deviceId: String? = null): Session deviceId: String? = null
): Session
/** /**
* Exchange a login token to an access token. * Exchange a login token to an access token.
@ -65,8 +67,10 @@ interface LoginWizard {
* @param email an email previously associated to the account the user wants the password to be reset. * @param email an email previously associated to the account the user wants the password to be reset.
* @param newPassword the desired new password * @param newPassword the desired new password
*/ */
suspend fun resetPassword(email: String, suspend fun resetPassword(
newPassword: String) email: String,
newPassword: String
)
/** /**
* Confirm the new password, once the user has checked their email * Confirm the new password, once the user has checked their email

View File

@ -54,9 +54,11 @@ interface RegistrationWizard {
* @param password the desired password * @param password the desired password
* @param initialDeviceDisplayName the device display name * @param initialDeviceDisplayName the device display name
*/ */
suspend fun createAccount(userName: String?, suspend fun createAccount(
userName: String?,
password: String?, password: String?,
initialDeviceDisplayName: String?): RegistrationResult initialDeviceDisplayName: String?
): RegistrationResult
/** /**
* Perform the "m.login.recaptcha" stage. * Perform the "m.login.recaptcha" stage.

View File

@ -26,9 +26,11 @@ sealed class WellknownResult {
* Retrieve the specific piece of information from the user in a way which fits within the existing client user experience, * Retrieve the specific piece of information from the user in a way which fits within the existing client user experience,
* if the client is inclined to do so. Failure can take place instead if no good user experience for this is possible at this point. * if the client is inclined to do so. Failure can take place instead if no good user experience for this is possible at this point.
*/ */
data class Prompt(val homeServerUrl: String, data class Prompt(
val homeServerUrl: String,
val identityServerUrl: String?, val identityServerUrl: String?,
val wellKnown: WellKnown) : WellknownResult() val wellKnown: WellKnown
) : WellknownResult()
/** /**
* Stop the current auto-discovery mechanism. If no more auto-discovery mechanisms are available, * Stop the current auto-discovery mechanism. If no more auto-discovery mechanisms are available,

View File

@ -27,8 +27,10 @@ interface AccountService {
* @param password Current password. * @param password Current password.
* @param newPassword New password * @param newPassword New password
*/ */
suspend fun changePassword(password: String, suspend fun changePassword(
newPassword: String) password: String,
newPassword: String
)
/** /**
* Deactivate the account. * Deactivate the account.
@ -46,6 +48,8 @@ interface AccountService {
* an incomplete view of conversations * an incomplete view of conversations
* @param userInteractiveAuthInterceptor see [UserInteractiveAuthInterceptor] * @param userInteractiveAuthInterceptor see [UserInteractiveAuthInterceptor]
*/ */
suspend fun deactivateAccount(eraseAllData: Boolean, suspend fun deactivateAccount(
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor) eraseAllData: Boolean,
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor
)
} }

View File

@ -91,10 +91,12 @@ interface MxCall : MxCallDetail {
* Send a m.call.replaces event to initiate call transfer. * Send a m.call.replaces event to initiate call transfer.
* See [org.matrix.android.sdk.api.session.room.model.call.CallReplacesContent] for documentation about the parameters * See [org.matrix.android.sdk.api.session.room.model.call.CallReplacesContent] for documentation about the parameters
*/ */
suspend fun transfer(targetUserId: String, suspend fun transfer(
targetUserId: String,
targetRoomId: String?, targetRoomId: String?,
createCallId: String?, createCallId: String?,
awaitCallId: String?) awaitCallId: String?
)
fun addListener(listener: StateListener) fun addListener(listener: StateListener)
fun removeListener(listener: StateListener) fun removeListener(listener: StateListener)

View File

@ -88,9 +88,11 @@ interface CryptoService {
fun getDeviceTrackingStatus(userId: String): Int fun getDeviceTrackingStatus(userId: String): Int
suspend fun importRoomKeys(roomKeysAsArray: ByteArray, suspend fun importRoomKeys(
roomKeysAsArray: ByteArray,
password: String, password: String,
progressListener: ProgressListener?): ImportRoomKeysResult progressListener: ProgressListener?
): ImportRoomKeysResult
suspend fun exportRoomKeys(password: String): ByteArray suspend fun exportRoomKeys(password: String): ByteArray
@ -119,10 +121,12 @@ interface CryptoService {
fun isRoomEncrypted(roomId: String): Boolean fun isRoomEncrypted(roomId: String): Boolean
// TODO This could be removed from this interface // TODO This could be removed from this interface
fun encryptEventContent(eventContent: Content, fun encryptEventContent(
eventContent: Content,
eventType: String, eventType: String,
roomId: String, roomId: String,
callback: MatrixCallback<MXEncryptEventContentResult>) callback: MatrixCallback<MXEncryptEventContentResult>
)
fun discardOutboundSession(roomId: String) fun discardOutboundSession(roomId: String)

View File

@ -25,12 +25,14 @@ import org.matrix.olm.OlmException
*/ */
sealed class MXCryptoError : Throwable() { sealed class MXCryptoError : Throwable() {
data class Base(val errorType: ErrorType, data class Base(
val errorType: ErrorType,
val technicalMessage: String, val technicalMessage: String,
/** /**
* Describe the error with more details. * Describe the error with more details.
*/ */
val detailedErrorDescription: String? = null) : MXCryptoError() val detailedErrorDescription: String? = null
) : MXCryptoError()
data class OlmError(val olmException: OlmException) : MXCryptoError() data class OlmError(val olmException: OlmException) : MXCryptoError()

View File

@ -37,14 +37,18 @@ interface CrossSigningService {
* Initialize cross signing for this user. * Initialize cross signing for this user.
* Users needs to enter credentials * Users needs to enter credentials
*/ */
fun initializeCrossSigning(uiaInterceptor: UserInteractiveAuthInterceptor?, fun initializeCrossSigning(
callback: MatrixCallback<Unit>) uiaInterceptor: UserInteractiveAuthInterceptor?,
callback: MatrixCallback<Unit>
)
fun isCrossSigningInitialized(): Boolean = getMyCrossSigningKeys() != null fun isCrossSigningInitialized(): Boolean = getMyCrossSigningKeys() != null
fun checkTrustFromPrivateKeys(masterKeyPrivateKey: String?, fun checkTrustFromPrivateKeys(
masterKeyPrivateKey: String?,
uskKeyPrivateKey: String?, uskKeyPrivateKey: String?,
sskPrivateKey: String?): UserTrustResult sskPrivateKey: String?
): UserTrustResult
fun getUserCrossSigningKeys(otherUserId: String): MXCrossSigningInfo? fun getUserCrossSigningKeys(otherUserId: String): MXCrossSigningInfo?
@ -60,20 +64,26 @@ interface CrossSigningService {
fun allPrivateKeysKnown(): Boolean fun allPrivateKeysKnown(): Boolean
fun trustUser(otherUserId: String, fun trustUser(
callback: MatrixCallback<Unit>) otherUserId: String,
callback: MatrixCallback<Unit>
)
fun markMyMasterKeyAsTrusted() fun markMyMasterKeyAsTrusted()
/** /**
* Sign one of your devices and upload the signature. * Sign one of your devices and upload the signature.
*/ */
fun trustDevice(deviceId: String, fun trustDevice(
callback: MatrixCallback<Unit>) deviceId: String,
callback: MatrixCallback<Unit>
)
fun checkDeviceTrust(otherUserId: String, fun checkDeviceTrust(
otherUserId: String,
otherDeviceId: String, otherDeviceId: String,
locallyTrusted: Boolean?): DeviceTrustResult locallyTrusted: Boolean?
): DeviceTrustResult
// FIXME Those method do not have to be in the service // FIXME Those method do not have to be in the service
fun onSecretMSKGossip(mskPrivateKey: String) fun onSecretMSKGossip(mskPrivateKey: String)

View File

@ -36,8 +36,10 @@ interface KeysBackupService {
* @param keysBackupCreationInfo the info object from [prepareKeysBackupVersion]. * @param keysBackupCreationInfo the info object from [prepareKeysBackupVersion].
* @param callback Asynchronous callback * @param callback Asynchronous callback
*/ */
fun createKeysBackupVersion(keysBackupCreationInfo: MegolmBackupCreationInfo, fun createKeysBackupVersion(
callback: MatrixCallback<KeysVersion>) keysBackupCreationInfo: MegolmBackupCreationInfo,
callback: MatrixCallback<KeysVersion>
)
/** /**
* Facility method to get the total number of locally stored keys. * Facility method to get the total number of locally stored keys.
@ -55,8 +57,10 @@ interface KeysBackupService {
* @param progressListener the callback to follow the progress * @param progressListener the callback to follow the progress
* @param callback the main callback * @param callback the main callback
*/ */
fun backupAllGroupSessions(progressListener: ProgressListener?, fun backupAllGroupSessions(
callback: MatrixCallback<Unit>?) progressListener: ProgressListener?,
callback: MatrixCallback<Unit>?
)
/** /**
* Check trust on a key backup version. * Check trust on a key backup version.
@ -64,8 +68,10 @@ interface KeysBackupService {
* @param keysBackupVersion the backup version to check. * @param keysBackupVersion the backup version to check.
* @param callback block called when the operations completes. * @param callback block called when the operations completes.
*/ */
fun getKeysBackupTrust(keysBackupVersion: KeysVersionResult, fun getKeysBackupTrust(
callback: MatrixCallback<KeysBackupVersionTrust>) keysBackupVersion: KeysVersionResult,
callback: MatrixCallback<KeysBackupVersionTrust>
)
/** /**
* Return the current progress of the backup. * Return the current progress of the backup.
@ -79,8 +85,10 @@ interface KeysBackupService {
* @param version the backup version * @param version the backup version
* @param callback * @param callback
*/ */
fun getVersion(version: String, fun getVersion(
callback: MatrixCallback<KeysVersionResult?>) version: String,
callback: MatrixCallback<KeysVersionResult?>
)
/** /**
* This method fetches the last backup version on the server, then compare to the currently backup version use. * This method fetches the last backup version on the server, then compare to the currently backup version use.
@ -114,9 +122,11 @@ interface KeysBackupService {
* @param progressListener a progress listener, as generating private key from password may take a while * @param progressListener a progress listener, as generating private key from password may take a while
* @param callback Asynchronous callback * @param callback Asynchronous callback
*/ */
fun prepareKeysBackupVersion(password: String?, fun prepareKeysBackupVersion(
password: String?,
progressListener: ProgressListener?, progressListener: ProgressListener?,
callback: MatrixCallback<MegolmBackupCreationInfo>) callback: MatrixCallback<MegolmBackupCreationInfo>
)
/** /**
* Delete a keys backup version. It will delete all backed up keys on the server, and the backup itself. * Delete a keys backup version. It will delete all backed up keys on the server, and the backup itself.
@ -125,8 +135,10 @@ interface KeysBackupService {
* @param version the backup version to delete. * @param version the backup version to delete.
* @param callback Asynchronous callback * @param callback Asynchronous callback
*/ */
fun deleteBackup(version: String, fun deleteBackup(
callback: MatrixCallback<Unit>?) version: String,
callback: MatrixCallback<Unit>?
)
/** /**
* Ask if the backup on the server contains keys that we may do not have locally. * Ask if the backup on the server contains keys that we may do not have locally.
@ -142,9 +154,11 @@ interface KeysBackupService {
* @param trust the trust to set to the keys backup. * @param trust the trust to set to the keys backup.
* @param callback block called when the operations completes. * @param callback block called when the operations completes.
*/ */
fun trustKeysBackupVersion(keysBackupVersion: KeysVersionResult, fun trustKeysBackupVersion(
keysBackupVersion: KeysVersionResult,
trust: Boolean, trust: Boolean,
callback: MatrixCallback<Unit>) callback: MatrixCallback<Unit>
)
/** /**
* Set trust on a keys backup version. * Set trust on a keys backup version.
@ -153,9 +167,11 @@ interface KeysBackupService {
* @param recoveryKey the recovery key to challenge with the key backup public key. * @param recoveryKey the recovery key to challenge with the key backup public key.
* @param callback block called when the operations completes. * @param callback block called when the operations completes.
*/ */
fun trustKeysBackupVersionWithRecoveryKey(keysBackupVersion: KeysVersionResult, fun trustKeysBackupVersionWithRecoveryKey(
keysBackupVersion: KeysVersionResult,
recoveryKey: String, recoveryKey: String,
callback: MatrixCallback<Unit>) callback: MatrixCallback<Unit>
)
/** /**
* Set trust on a keys backup version. * Set trust on a keys backup version.
@ -164,9 +180,11 @@ interface KeysBackupService {
* @param password the pass phrase to challenge with the keyBackupVersion public key. * @param password the pass phrase to challenge with the keyBackupVersion public key.
* @param callback block called when the operations completes. * @param callback block called when the operations completes.
*/ */
fun trustKeysBackupVersionWithPassphrase(keysBackupVersion: KeysVersionResult, fun trustKeysBackupVersionWithPassphrase(
keysBackupVersion: KeysVersionResult,
password: String, password: String,
callback: MatrixCallback<Unit>) callback: MatrixCallback<Unit>
)
fun onSecretKeyGossip(secret: String) fun onSecretKeyGossip(secret: String)
@ -180,11 +198,13 @@ interface KeysBackupService {
* @param stepProgressListener the step progress listener * @param stepProgressListener the step progress listener
* @param callback Callback. It provides the number of found keys and the number of successfully imported keys. * @param callback Callback. It provides the number of found keys and the number of successfully imported keys.
*/ */
fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult, fun restoreKeysWithRecoveryKey(
keysVersionResult: KeysVersionResult,
recoveryKey: String, roomId: String?, recoveryKey: String, roomId: String?,
sessionId: String?, sessionId: String?,
stepProgressListener: StepProgressListener?, stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>) callback: MatrixCallback<ImportRoomKeysResult>
)
/** /**
* Restore a backup with a password from a given backup version stored on the homeserver. * Restore a backup with a password from a given backup version stored on the homeserver.
@ -196,12 +216,14 @@ interface KeysBackupService {
* @param stepProgressListener the step progress listener * @param stepProgressListener the step progress listener
* @param callback Callback. It provides the number of found keys and the number of successfully imported keys. * @param callback Callback. It provides the number of found keys and the number of successfully imported keys.
*/ */
fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult, fun restoreKeyBackupWithPassword(
keysBackupVersion: KeysVersionResult,
password: String, password: String,
roomId: String?, roomId: String?,
sessionId: String?, sessionId: String?,
stepProgressListener: StepProgressListener?, stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>) callback: MatrixCallback<ImportRoomKeysResult>
)
val keysBackupVersion: KeysVersionResult? val keysBackupVersion: KeysVersionResult?
val currentBackupVersion: String? val currentBackupVersion: String?
@ -215,8 +237,10 @@ interface KeysBackupService {
fun isValidRecoveryKeyForCurrentVersion(recoveryKey: String, callback: MatrixCallback<Boolean>) fun isValidRecoveryKeyForCurrentVersion(recoveryKey: String, callback: MatrixCallback<Boolean>)
fun computePrivateKey(passphrase: String, fun computePrivateKey(
passphrase: String,
privateKeySalt: String, privateKeySalt: String,
privateKeyIterations: Int, privateKeyIterations: Int,
progressListener: ProgressListener): ByteArray progressListener: ProgressListener
): ByteArray
} }

View File

@ -40,7 +40,8 @@ sealed class KeysBackupVersionTrustSignature {
/** /**
* Flag to indicate the signature from this device is valid. * Flag to indicate the signature from this device is valid.
*/ */
val valid: Boolean) : KeysBackupVersionTrustSignature() val valid: Boolean
) : KeysBackupVersionTrustSignature()
data class UserSignature( data class UserSignature(
val keyId: String?, val keyId: String?,

View File

@ -19,7 +19,8 @@ package org.matrix.android.sdk.api.session.crypto.verification
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.annotation.StringRes import androidx.annotation.StringRes
data class EmojiRepresentation(val emoji: String, data class EmojiRepresentation(
val emoji: String,
@StringRes val nameResId: Int, @StringRes val nameResId: Int,
@DrawableRes val drawableRes: Int? = null @DrawableRes val drawableRes: Int? = null
) )

View File

@ -46,54 +46,68 @@ interface VerificationService {
fun getExistingVerificationRequestInRoom(roomId: String, tid: String?): PendingVerificationRequest? fun getExistingVerificationRequestInRoom(roomId: String, tid: String?): PendingVerificationRequest?
fun beginKeyVerification(method: VerificationMethod, fun beginKeyVerification(
method: VerificationMethod,
otherUserId: String, otherUserId: String,
otherDeviceId: String, otherDeviceId: String,
transactionId: String?): String? transactionId: String?
): String?
/** /**
* Request key verification with another user via room events (instead of the to-device API). * Request key verification with another user via room events (instead of the to-device API).
*/ */
fun requestKeyVerificationInDMs(methods: List<VerificationMethod>, fun requestKeyVerificationInDMs(
methods: List<VerificationMethod>,
otherUserId: String, otherUserId: String,
roomId: String, roomId: String,
localId: String? = LocalEcho.createLocalEchoId()): PendingVerificationRequest localId: String? = LocalEcho.createLocalEchoId()
): PendingVerificationRequest
fun cancelVerificationRequest(request: PendingVerificationRequest) fun cancelVerificationRequest(request: PendingVerificationRequest)
/** /**
* Request a key verification from another user using toDevice events. * Request a key verification from another user using toDevice events.
*/ */
fun requestKeyVerification(methods: List<VerificationMethod>, fun requestKeyVerification(
methods: List<VerificationMethod>,
otherUserId: String, otherUserId: String,
otherDevices: List<String>?): PendingVerificationRequest otherDevices: List<String>?
): PendingVerificationRequest
fun declineVerificationRequestInDMs(otherUserId: String, fun declineVerificationRequestInDMs(
otherUserId: String,
transactionId: String, transactionId: String,
roomId: String) roomId: String
)
// Only SAS method is supported for the moment // Only SAS method is supported for the moment
// TODO Parameter otherDeviceId should be removed in this case // TODO Parameter otherDeviceId should be removed in this case
fun beginKeyVerificationInDMs(method: VerificationMethod, fun beginKeyVerificationInDMs(
method: VerificationMethod,
transactionId: String, transactionId: String,
roomId: String, roomId: String,
otherUserId: String, otherUserId: String,
otherDeviceId: String): String otherDeviceId: String
): String
/** /**
* Returns false if the request is unknown. * Returns false if the request is unknown.
*/ */
fun readyPendingVerificationInDMs(methods: List<VerificationMethod>, fun readyPendingVerificationInDMs(
methods: List<VerificationMethod>,
otherUserId: String, otherUserId: String,
roomId: String, roomId: String,
transactionId: String): Boolean transactionId: String
): Boolean
/** /**
* Returns false if the request is unknown. * Returns false if the request is unknown.
*/ */
fun readyPendingVerification(methods: List<VerificationMethod>, fun readyPendingVerification(
methods: List<VerificationMethod>,
otherUserId: String, otherUserId: String,
transactionId: String): Boolean transactionId: String
): Boolean
interface Listener { interface Listener {
/** /**

View File

@ -24,6 +24,8 @@ interface EventService {
* Ask the homeserver for an event content. The SDK will try to decrypt it if it is possible * Ask the homeserver for an event content. The SDK will try to decrypt it if it is possible
* The result will not be stored into cache * The result will not be stored into cache
*/ */
suspend fun getEvent(roomId: String, suspend fun getEvent(
eventId: String): Event roomId: String,
eventId: String
): Event
} }

View File

@ -44,10 +44,12 @@ interface FileService {
* Download a file if necessary and ensure that if the file is encrypted, the file is decrypted. * Download a file if necessary and ensure that if the file is encrypted, the file is decrypted.
* Result will be a decrypted file, stored in the cache folder. url parameter will be used to create unique filename to avoid name collision. * Result will be a decrypted file, stored in the cache folder. url parameter will be used to create unique filename to avoid name collision.
*/ */
suspend fun downloadFile(fileName: String, suspend fun downloadFile(
fileName: String,
mimeType: String?, mimeType: String?,
url: String?, url: String?,
elementToDecrypt: ElementToDecrypt?): File elementToDecrypt: ElementToDecrypt?
): File
suspend fun downloadFile(messageContent: MessageWithAttachmentContent): File = suspend fun downloadFile(messageContent: MessageWithAttachmentContent): File =
downloadFile( downloadFile(
@ -57,7 +59,8 @@ interface FileService {
elementToDecrypt = messageContent.encryptedFileInfo?.toElementToDecrypt() elementToDecrypt = messageContent.encryptedFileInfo?.toElementToDecrypt()
) )
fun isFileInCache(mxcUrl: String?, fun isFileInCache(
mxcUrl: String?,
fileName: String, fileName: String,
mimeType: String?, mimeType: String?,
elementToDecrypt: ElementToDecrypt? elementToDecrypt: ElementToDecrypt?
@ -75,10 +78,12 @@ interface FileService {
* Use this URI and pass it to intent using flag Intent.FLAG_GRANT_READ_URI_PERMISSION * Use this URI and pass it to intent using flag Intent.FLAG_GRANT_READ_URI_PERMISSION
* (if not other app won't be able to access it). * (if not other app won't be able to access it).
*/ */
fun getTemporarySharableURI(mxcUrl: String?, fun getTemporarySharableURI(
mxcUrl: String?,
fileName: String, fileName: String,
mimeType: String?, mimeType: String?,
elementToDecrypt: ElementToDecrypt?): Uri? elementToDecrypt: ElementToDecrypt?
): Uri?
fun getTemporarySharableURI(messageContent: MessageWithAttachmentContent): Uri? = fun getTemporarySharableURI(messageContent: MessageWithAttachmentContent): Uri? =
getTemporarySharableURI( getTemporarySharableURI(
@ -92,10 +97,12 @@ interface FileService {
* Get information on the given file. * Get information on the given file.
* Mimetype should be the same one as passed to downloadFile (limitation for now) * Mimetype should be the same one as passed to downloadFile (limitation for now)
*/ */
fun fileState(mxcUrl: String?, fun fileState(
mxcUrl: String?,
fileName: String, fileName: String,
mimeType: String?, mimeType: String?,
elementToDecrypt: ElementToDecrypt?): FileState elementToDecrypt: ElementToDecrypt?
): FileState
fun fileState(messageContent: MessageWithAttachmentContent): FileState = fun fileState(messageContent: MessageWithAttachmentContent): FileState =
fileState( fileState(

View File

@ -25,8 +25,10 @@ import org.matrix.android.sdk.api.session.permalinks.MatrixPermalinkSpan.Callbac
* @property url the permalink url tied to the span * @property url the permalink url tied to the span
* @property callback the callback to use. * @property callback the callback to use.
*/ */
class MatrixPermalinkSpan(private val url: String, class MatrixPermalinkSpan(
private val callback: Callback? = null) : ClickableSpan() { private val url: String,
private val callback: Callback? = null
) : ClickableSpan() {
interface Callback { interface Callback {
fun onUrlClicked(url: String) fun onUrlClicked(url: String)

View File

@ -107,8 +107,10 @@ interface ProfileService {
/** /**
* Finalize adding a 3Pids. Call this method once the user has validated that he owns the ThreePid. * Finalize adding a 3Pids. Call this method once the user has validated that he owns the ThreePid.
*/ */
suspend fun finalizeAddingThreePid(threePid: ThreePid, suspend fun finalizeAddingThreePid(
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor) threePid: ThreePid,
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor
)
/** /**
* Cancel adding a threepid. It will remove locally stored data about this ThreePid. * Cancel adding a threepid. It will remove locally stored data about this ThreePid.

View File

@ -58,12 +58,14 @@ interface PushersService {
* email pushers since we don't want to stop other accounts notifying to the same email address. * email pushers since we don't want to stop other accounts notifying to the same email address.
* @throws [InvalidParameterException] if a parameter is not correct * @throws [InvalidParameterException] if a parameter is not correct
*/ */
suspend fun addEmailPusher(email: String, suspend fun addEmailPusher(
email: String,
lang: String, lang: String,
emailBranding: String, emailBranding: String,
appDisplayName: String, appDisplayName: String,
deviceDisplayName: String, deviceDisplayName: String,
append: Boolean = true) append: Boolean = true
)
/** /**
* Directly ask the push gateway to send a push to this device. * Directly ask the push gateway to send a push to this device.
@ -75,10 +77,12 @@ interface PushersService {
* @param pushkey the FCM token * @param pushkey the FCM token
* @param eventId the eventId which will be sent in the Push message. Use a fake eventId. * @param eventId the eventId which will be sent in the Push message. Use a fake eventId.
*/ */
suspend fun testPush(url: String, suspend fun testPush(
url: String,
appId: String, appId: String,
pushkey: String, pushkey: String,
eventId: String) eventId: String
)
/** /**
* Remove a registered pusher. * Remove a registered pusher.

View File

@ -22,15 +22,23 @@ import org.matrix.android.sdk.api.session.events.model.Event
* This class as all required context needed to evaluate rules * This class as all required context needed to evaluate rules
*/ */
interface ConditionResolver { interface ConditionResolver {
fun resolveEventMatchCondition(event: Event, fun resolveEventMatchCondition(
condition: EventMatchCondition): Boolean event: Event,
condition: EventMatchCondition
): Boolean
fun resolveRoomMemberCountCondition(event: Event, fun resolveRoomMemberCountCondition(
condition: RoomMemberCountCondition): Boolean event: Event,
condition: RoomMemberCountCondition
): Boolean
fun resolveSenderNotificationPermissionCondition(event: Event, fun resolveSenderNotificationPermissionCondition(
condition: SenderNotificationPermissionCondition): Boolean event: Event,
condition: SenderNotificationPermissionCondition
): Boolean
fun resolveContainsDisplayNameCondition(event: Event, fun resolveContainsDisplayNameCondition(
condition: ContainsDisplayNameCondition): Boolean event: Event,
condition: ContainsDisplayNameCondition
): Boolean
} }

View File

@ -51,8 +51,10 @@ interface PushRuleService {
// fun fulfilledBingRule(event: Event, rules: List<PushRule>): PushRule? // fun fulfilledBingRule(event: Event, rules: List<PushRule>): PushRule?
fun resolveSenderNotificationPermissionCondition(event: Event, fun resolveSenderNotificationPermissionCondition(
condition: SenderNotificationPermissionCondition): Boolean event: Event,
condition: SenderNotificationPermissionCondition
): Boolean
interface PushRuleListener { interface PushRuleListener {
fun onEvents(pushEvents: PushEvents) fun onEvents(pushEvents: PushEvents)

View File

@ -28,8 +28,10 @@ interface RoomDirectoryService {
/** /**
* Get rooms from directory. * Get rooms from directory.
*/ */
suspend fun getPublicRooms(server: String?, suspend fun getPublicRooms(
publicRoomsParams: PublicRoomsParams): PublicRoomsResponse server: String?,
publicRoomsParams: PublicRoomsParams
): PublicRoomsResponse
/** /**
* Get the visibility of a room in the directory. * Get the visibility of a room in the directory.

View File

@ -60,9 +60,11 @@ interface RoomService {
* @param reason optional reason for joining the room * @param reason optional reason for joining the room
* @param viaServers the servers to attempt to join the room through. One of the servers must be participating in the room. * @param viaServers the servers to attempt to join the room through. One of the servers must be participating in the room.
*/ */
suspend fun joinRoom(roomIdOrAlias: String, suspend fun joinRoom(
roomIdOrAlias: String,
reason: String? = null, reason: String? = null,
viaServers: List<String> = emptyList()) viaServers: List<String> = emptyList()
)
/** /**
* @param roomId the roomId of the room to join * @param roomId the roomId of the room to join
@ -101,15 +103,19 @@ interface RoomService {
* Get a snapshot list of room summaries. * Get a snapshot list of room summaries.
* @return the immutable list of [RoomSummary] * @return the immutable list of [RoomSummary]
*/ */
fun getRoomSummaries(queryParams: RoomSummaryQueryParams, fun getRoomSummaries(
sortOrder: RoomSortOrder = RoomSortOrder.NONE): List<RoomSummary> queryParams: RoomSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE
): List<RoomSummary>
/** /**
* Get a live list of room summaries. This list is refreshed as soon as the data changes. * Get a live list of room summaries. This list is refreshed as soon as the data changes.
* @return the [LiveData] of List[RoomSummary] * @return the [LiveData] of List[RoomSummary]
*/ */
fun getRoomSummariesLive(queryParams: RoomSummaryQueryParams, fun getRoomSummariesLive(
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData<List<RoomSummary>> queryParams: RoomSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY
): LiveData<List<RoomSummary>>
/** /**
* Get a snapshot list of Breadcrumbs. * Get a snapshot list of Breadcrumbs.
@ -139,8 +145,10 @@ interface RoomService {
/** /**
* Resolve a room alias to a room ID. * Resolve a room alias to a room ID.
*/ */
suspend fun getRoomIdByAlias(roomAlias: String, suspend fun getRoomIdByAlias(
searchOnServer: Boolean): Optional<RoomAliasDescription> roomAlias: String,
searchOnServer: Boolean
): Optional<RoomAliasDescription>
/** /**
* Delete a room alias. * Delete a room alias.
@ -205,16 +213,20 @@ interface RoomService {
/** /**
* TODO Doc. * TODO Doc.
*/ */
fun getPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams, fun getPagedRoomSummariesLive(
queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig, pagedListConfig: PagedList.Config = defaultPagedListConfig,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData<PagedList<RoomSummary>> sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY
): LiveData<PagedList<RoomSummary>>
/** /**
* TODO Doc. * TODO Doc.
*/ */
fun getFilteredPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams, fun getFilteredPagedRoomSummariesLive(
queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig, pagedListConfig: PagedList.Config = defaultPagedListConfig,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): UpdatableLivePageResult sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY
): UpdatableLivePageResult
/** /**
* Return a LiveData on the number of rooms. * Return a LiveData on the number of rooms.
@ -240,8 +252,10 @@ interface RoomService {
/** /**
* Returns all the children of this space, as LiveData. * Returns all the children of this space, as LiveData.
*/ */
fun getFlattenRoomSummaryChildrenOfLive(spaceId: String?, fun getFlattenRoomSummaryChildrenOfLive(
memberships: List<Membership> = Membership.activeMemberships()): LiveData<List<RoomSummary>> spaceId: String?,
memberships: List<Membership> = Membership.activeMemberships()
): LiveData<List<RoomSummary>>
/** /**
* Refreshes the RoomSummary LatestPreviewContent for the given @param roomId. * Refreshes the RoomSummary LatestPreviewContent for the given @param roomId.

View File

@ -40,12 +40,14 @@ internal data class MessageVerificationAcceptContent(
companion object : VerificationInfoAcceptFactory { companion object : VerificationInfoAcceptFactory {
override fun create(tid: String, override fun create(
tid: String,
keyAgreementProtocol: String, keyAgreementProtocol: String,
hash: String, hash: String,
commitment: String, commitment: String,
messageAuthenticationCode: String, messageAuthenticationCode: String,
shortAuthenticationStrings: List<String>): VerificationInfoAccept { shortAuthenticationStrings: List<String>
): VerificationInfoAccept {
return MessageVerificationAcceptContent( return MessageVerificationAcceptContent(
hash, hash,
keyAgreementProtocol, keyAgreementProtocol,

View File

@ -58,16 +58,20 @@ interface RelationService {
* @param targetEventId the id of the event being reacted * @param targetEventId the id of the event being reacted
* @param reaction the reaction (preferably emoji) * @param reaction the reaction (preferably emoji)
*/ */
fun sendReaction(targetEventId: String, fun sendReaction(
reaction: String): Cancelable targetEventId: String,
reaction: String
): Cancelable
/** /**
* Undo a reaction (emoji) to the targetedEvent. * Undo a reaction (emoji) to the targetedEvent.
* @param targetEventId the id of the event being reacted * @param targetEventId the id of the event being reacted
* @param reaction the reaction (preferably emoji) * @param reaction the reaction (preferably emoji)
*/ */
suspend fun undoReaction(targetEventId: String, suspend fun undoReaction(
reaction: String): Cancelable targetEventId: String,
reaction: String
): Cancelable
/** /**
* Edit a poll. * Edit a poll.
@ -76,10 +80,12 @@ interface RelationService {
* @param question The edited question * @param question The edited question
* @param options The edited options * @param options The edited options
*/ */
fun editPoll(targetEvent: TimelineEvent, fun editPoll(
targetEvent: TimelineEvent,
pollType: PollType, pollType: PollType,
question: String, question: String,
options: List<String>): Cancelable options: List<String>
): Cancelable
/** /**
* Edit a text message body. Limited to "m.text" contentType. * Edit a text message body. Limited to "m.text" contentType.
@ -89,11 +95,13 @@ interface RelationService {
* @param newBodyAutoMarkdown true to parse markdown on the new body * @param newBodyAutoMarkdown true to parse markdown on the new body
* @param compatibilityBodyText The text that will appear on clients that don't support yet edition * @param compatibilityBodyText The text that will appear on clients that don't support yet edition
*/ */
fun editTextMessage(targetEvent: TimelineEvent, fun editTextMessage(
targetEvent: TimelineEvent,
msgType: String, msgType: String,
newBodyText: CharSequence, newBodyText: CharSequence,
newBodyAutoMarkdown: Boolean, newBodyAutoMarkdown: Boolean,
compatibilityBodyText: String = "* $newBodyText"): Cancelable compatibilityBodyText: String = "* $newBodyText"
): Cancelable
/** /**
* Edit a reply. This is a special case because replies contains fallback text as a prefix. * Edit a reply. This is a special case because replies contains fallback text as a prefix.
@ -103,10 +111,12 @@ interface RelationService {
* @param newBodyText The edited body (stripped from in reply to content) * @param newBodyText The edited body (stripped from in reply to content)
* @param compatibilityBodyText The text that will appear on clients that don't support yet edition * @param compatibilityBodyText The text that will appear on clients that don't support yet edition
*/ */
fun editReply(replyToEdit: TimelineEvent, fun editReply(
replyToEdit: TimelineEvent,
originalTimelineEvent: TimelineEvent, originalTimelineEvent: TimelineEvent,
newBodyText: String, newBodyText: String,
compatibilityBodyText: String = "* $newBodyText"): Cancelable compatibilityBodyText: String = "* $newBodyText"
): Cancelable
/** /**
* Get the edit history of the given event. * Get the edit history of the given event.
@ -127,7 +137,8 @@ interface RelationService {
* @param showInThread If true, relation will be added to the reply in order to be visible from within threads * @param showInThread If true, relation will be added to the reply in order to be visible from within threads
* @param rootThreadEventId If show in thread is true then we need the rootThreadEventId to generate the relation * @param rootThreadEventId If show in thread is true then we need the rootThreadEventId to generate the relation
*/ */
fun replyToMessage(eventReplied: TimelineEvent, fun replyToMessage(
eventReplied: TimelineEvent,
replyText: CharSequence, replyText: CharSequence,
autoMarkdown: Boolean = false, autoMarkdown: Boolean = false,
showInThread: Boolean = false, showInThread: Boolean = false,
@ -159,10 +170,12 @@ interface RelationService {
* @param formattedText The formatted body using MessageType#FORMAT_MATRIX_HTML * @param formattedText The formatted body using MessageType#FORMAT_MATRIX_HTML
* @param eventReplied the event referenced by the reply within a thread * @param eventReplied the event referenced by the reply within a thread
*/ */
fun replyInThread(rootThreadEventId: String, fun replyInThread(
rootThreadEventId: String,
replyInThreadText: CharSequence, replyInThreadText: CharSequence,
msgType: String = MessageType.MSGTYPE_TEXT, msgType: String = MessageType.MSGTYPE_TEXT,
autoMarkdown: Boolean = false, autoMarkdown: Boolean = false,
formattedText: String? = null, formattedText: String? = null,
eventReplied: TimelineEvent? = null): Cancelable? eventReplied: TimelineEvent? = null
): Cancelable?
} }

View File

@ -76,10 +76,12 @@ interface SendService {
* @param rootThreadEventId when this param is not null, the Media will be sent in this specific thread * @param rootThreadEventId when this param is not null, the Media will be sent in this specific thread
* @return a [Cancelable] * @return a [Cancelable]
*/ */
fun sendMedia(attachment: ContentAttachmentData, fun sendMedia(
attachment: ContentAttachmentData,
compressBeforeSending: Boolean, compressBeforeSending: Boolean,
roomIds: Set<String>, roomIds: Set<String>,
rootThreadEventId: String? = null): Cancelable rootThreadEventId: String? = null
): Cancelable
/** /**
* Method to send a list of media asynchronously. * Method to send a list of media asynchronously.
@ -90,10 +92,12 @@ interface SendService {
* @param rootThreadEventId when this param is not null, all the Media will be sent in this specific thread * @param rootThreadEventId when this param is not null, all the Media will be sent in this specific thread
* @return a [Cancelable] * @return a [Cancelable]
*/ */
fun sendMedias(attachments: List<ContentAttachmentData>, fun sendMedias(
attachments: List<ContentAttachmentData>,
compressBeforeSending: Boolean, compressBeforeSending: Boolean,
roomIds: Set<String>, roomIds: Set<String>,
rootThreadEventId: String? = null): Cancelable rootThreadEventId: String? = null
): Cancelable
/** /**
* Send a poll to the room. * Send a poll to the room.

View File

@ -16,5 +16,7 @@
package org.matrix.android.sdk.api.session.room.threads.model package org.matrix.android.sdk.api.session.room.threads.model
data class ThreadEditions(var rootThreadEdition: String? = null, data class ThreadEditions(
var latestThreadEdition: String? = null) var rootThreadEdition: String? = null,
var latestThreadEdition: String? = null
)

View File

@ -22,7 +22,8 @@ import org.matrix.android.sdk.api.session.room.sender.SenderInfo
/** /**
* The main thread Summary model, mainly used to display the thread list. * The main thread Summary model, mainly used to display the thread list.
*/ */
data class ThreadSummary(val roomId: String, data class ThreadSummary(
val roomId: String,
val rootEvent: Event?, val rootEvent: Event?,
val latestEvent: Event?, val latestEvent: Event?,
val rootEventId: String, val rootEventId: String,
@ -30,4 +31,5 @@ data class ThreadSummary(val roomId: String,
val latestThreadSenderInfo: SenderInfo, val latestThreadSenderInfo: SenderInfo,
val isUserParticipating: Boolean, val isUserParticipating: Boolean,
val numberOfThreads: Int, val numberOfThreads: Int,
val threadEditions: ThreadEditions = ThreadEditions()) val threadEditions: ThreadEditions = ThreadEditions()
)

View File

@ -33,12 +33,14 @@ interface SearchService {
* @param afterLimit how many events after the result are returned. * @param afterLimit how many events after the result are returned.
* @param includeProfile requests that the server returns the historic profile information for the users that sent the events that were returned. * @param includeProfile requests that the server returns the historic profile information for the users that sent the events that were returned.
*/ */
suspend fun search(searchTerm: String, suspend fun search(
searchTerm: String,
roomId: String, roomId: String,
nextBatch: String?, nextBatch: String?,
orderByRecent: Boolean, orderByRecent: Boolean,
limit: Int, limit: Int,
beforeLimit: Int, beforeLimit: Int,
afterLimit: Int, afterLimit: Int,
includeProfile: Boolean): SearchResult includeProfile: Boolean
): SearchResult
} }

View File

@ -44,10 +44,12 @@ interface SharedSecretStorageService {
* *
* @return key creation info * @return key creation info
*/ */
suspend fun generateKey(keyId: String, suspend fun generateKey(
keyId: String,
key: SsssKeySpec?, key: SsssKeySpec?,
keyName: String, keyName: String,
keySigner: KeySigner?): SsssKeyCreationInfo keySigner: KeySigner?
): SsssKeyCreationInfo
/** /**
* Generates a SSSS key using the given passphrase. * Generates a SSSS key using the given passphrase.
@ -61,11 +63,13 @@ interface SharedSecretStorageService {
* *
* @return key creation info * @return key creation info
*/ */
suspend fun generateKeyWithPassphrase(keyId: String, suspend fun generateKeyWithPassphrase(
keyId: String,
keyName: String, keyName: String,
passphrase: String, passphrase: String,
keySigner: KeySigner, keySigner: KeySigner,
progressListener: ProgressListener?): SsssKeyCreationInfo progressListener: ProgressListener?
): SsssKeyCreationInfo
fun getKey(keyId: String): KeyInfoResult fun getKey(keyId: String): KeyInfoResult

View File

@ -31,11 +31,13 @@ interface Space {
*/ */
fun spaceSummary(): RoomSummary? fun spaceSummary(): RoomSummary?
suspend fun addChildren(roomId: String, suspend fun addChildren(
roomId: String,
viaServers: List<String>?, viaServers: List<String>?,
order: String?, order: String?,
// autoJoin: Boolean = false, // autoJoin: Boolean = false,
suggested: Boolean? = false) suggested: Boolean? = false
)
fun getChildInfo(roomId: String): SpaceChildContent? fun getChildInfo(roomId: String): SpaceChildContent?

View File

@ -37,11 +37,13 @@ interface SpaceService {
/** /**
* Just a shortcut for space creation for ease of use. * Just a shortcut for space creation for ease of use.
*/ */
suspend fun createSpace(name: String, suspend fun createSpace(
name: String,
topic: String?, topic: String?,
avatarUri: Uri?, avatarUri: Uri?,
isPublic: Boolean, isPublic: Boolean,
roomAliasLocalPart: String? = null): String roomAliasLocalPart: String? = null
): String
/** /**
* Get a space from a spaceId. * Get a space from a spaceId.
@ -68,25 +70,33 @@ interface SpaceService {
* then the parameters given for suggested_only and max_depth must be the same. * then the parameters given for suggested_only and max_depth must be the same.
* @param knownStateList when paginating, pass back the m.space.child state events * @param knownStateList when paginating, pass back the m.space.child state events
*/ */
suspend fun querySpaceChildren(spaceId: String, suspend fun querySpaceChildren(
spaceId: String,
suggestedOnly: Boolean? = null, suggestedOnly: Boolean? = null,
limit: Int? = null, limit: Int? = null,
from: String? = null, from: String? = null,
knownStateList: List<Event>? = null): SpaceHierarchyData knownStateList: List<Event>? = null
): SpaceHierarchyData
/** /**
* Get a live list of space summaries. This list is refreshed as soon as the data changes. * Get a live list of space summaries. This list is refreshed as soon as the data changes.
* @return the [LiveData] of List[SpaceSummary] * @return the [LiveData] of List[SpaceSummary]
*/ */
fun getSpaceSummariesLive(queryParams: SpaceSummaryQueryParams, fun getSpaceSummariesLive(
sortOrder: RoomSortOrder = RoomSortOrder.NONE): LiveData<List<RoomSummary>> queryParams: SpaceSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE
): LiveData<List<RoomSummary>>
fun getSpaceSummaries(spaceSummaryQueryParams: SpaceSummaryQueryParams, fun getSpaceSummaries(
sortOrder: RoomSortOrder = RoomSortOrder.NONE): List<RoomSummary> spaceSummaryQueryParams: SpaceSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE
): List<RoomSummary>
suspend fun joinSpace(spaceIdOrAlias: String, suspend fun joinSpace(
spaceIdOrAlias: String,
reason: String? = null, reason: String? = null,
viaServers: List<String> = emptyList()): JoinSpaceResult viaServers: List<String> = emptyList()
): JoinSpaceResult
suspend fun rejectInvite(spaceId: String, reason: String?) suspend fun rejectInvite(spaceId: String, reason: String?)

View File

@ -23,15 +23,19 @@ sealed interface StatisticEvent {
/** /**
* Initial sync request, response downloading, and treatment (parsing and storage) of response. * Initial sync request, response downloading, and treatment (parsing and storage) of response.
*/ */
data class InitialSyncRequest(val requestDurationMs: Int, data class InitialSyncRequest(
val requestDurationMs: Int,
val downloadDurationMs: Int, val downloadDurationMs: Int,
val treatmentDurationMs: Int, val treatmentDurationMs: Int,
val nbOfJoinedRooms: Int) : StatisticEvent val nbOfJoinedRooms: Int
) : StatisticEvent
/** /**
* Incremental sync event. * Incremental sync event.
*/ */
data class SyncTreatment(val durationMs: Int, data class SyncTreatment(
val durationMs: Int,
val afterPause: Boolean, val afterPause: Boolean,
val nbOfJoinedRooms: Int) : StatisticEvent val nbOfJoinedRooms: Int
) : StatisticEvent
} }

View File

@ -38,4 +38,5 @@ data class RoomSyncUnreadNotifications(
/** /**
* The number of highlighted unread messages (subset of notifications). * The number of highlighted unread messages (subset of notifications).
*/ */
@Json(name = "highlight_count") val highlightCount: Int? = null) @Json(name = "highlight_count") val highlightCount: Int? = null
)

View File

@ -30,8 +30,10 @@ data class TermsResponse(
val policies: JsonDict? = null val policies: JsonDict? = null
) { ) {
fun getLocalizedTerms(userLanguage: String, fun getLocalizedTerms(
defaultLanguage: String = "en"): List<LocalizedFlowDataLoginTerms> { userLanguage: String,
defaultLanguage: String = "en"
): List<LocalizedFlowDataLoginTerms> {
return policies?.map { return policies?.map {
val tos = policies[it.key] as? Map<*, *> ?: return@map null val tos = policies[it.key] as? Map<*, *> ?: return@map null
((tos[userLanguage] ?: tos[defaultLanguage]) as? Map<*, *>)?.let { termsMap -> ((tos[userLanguage] ?: tos[defaultLanguage]) as? Map<*, *>)?.let { termsMap ->

View File

@ -24,10 +24,12 @@ interface TermsService {
suspend fun getTerms(serviceType: ServiceType, baseUrl: String): GetTermsResponse suspend fun getTerms(serviceType: ServiceType, baseUrl: String): GetTermsResponse
suspend fun agreeToTerms(serviceType: ServiceType, suspend fun agreeToTerms(
serviceType: ServiceType,
baseUrl: String, baseUrl: String,
agreedUrls: List<String>, agreedUrls: List<String>,
token: String?) token: String?
)
/** /**
* Get the homeserver terms, from the register API. * Get the homeserver terms, from the register API.

View File

@ -33,9 +33,11 @@ sealed class MatrixItem(
open val displayName: String?, open val displayName: String?,
open val avatarUrl: String? open val avatarUrl: String?
) { ) {
data class UserItem(override val id: String, data class UserItem(
override val id: String,
override val displayName: String? = null, override val displayName: String? = null,
override val avatarUrl: String? = null) : override val avatarUrl: String? = null
) :
MatrixItem(id, displayName?.removeSuffix(IRC_PATTERN), avatarUrl) { MatrixItem(id, displayName?.removeSuffix(IRC_PATTERN), avatarUrl) {
init { init {
@ -45,10 +47,12 @@ sealed class MatrixItem(
override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar)
} }
data class EveryoneInRoomItem(override val id: String, data class EveryoneInRoomItem(
override val id: String,
override val displayName: String = NOTIFY_EVERYONE, override val displayName: String = NOTIFY_EVERYONE,
override val avatarUrl: String? = null, override val avatarUrl: String? = null,
val roomDisplayName: String? = null) : val roomDisplayName: String? = null
) :
MatrixItem(id, displayName, avatarUrl) { MatrixItem(id, displayName, avatarUrl) {
init { init {
if (BuildConfig.DEBUG) checkId() if (BuildConfig.DEBUG) checkId()
@ -57,9 +61,11 @@ sealed class MatrixItem(
override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar)
} }
data class EventItem(override val id: String, data class EventItem(
override val id: String,
override val displayName: String? = null, override val displayName: String? = null,
override val avatarUrl: String? = null) : override val avatarUrl: String? = null
) :
MatrixItem(id, displayName, avatarUrl) { MatrixItem(id, displayName, avatarUrl) {
init { init {
if (BuildConfig.DEBUG) checkId() if (BuildConfig.DEBUG) checkId()
@ -68,9 +74,11 @@ sealed class MatrixItem(
override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar)
} }
data class RoomItem(override val id: String, data class RoomItem(
override val id: String,
override val displayName: String? = null, override val displayName: String? = null,
override val avatarUrl: String? = null) : override val avatarUrl: String? = null
) :
MatrixItem(id, displayName, avatarUrl) { MatrixItem(id, displayName, avatarUrl) {
init { init {
if (BuildConfig.DEBUG) checkId() if (BuildConfig.DEBUG) checkId()
@ -79,9 +87,11 @@ sealed class MatrixItem(
override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar)
} }
data class SpaceItem(override val id: String, data class SpaceItem(
override val id: String,
override val displayName: String? = null, override val displayName: String? = null,
override val avatarUrl: String? = null) : override val avatarUrl: String? = null
) :
MatrixItem(id, displayName, avatarUrl) { MatrixItem(id, displayName, avatarUrl) {
init { init {
if (BuildConfig.DEBUG) checkId() if (BuildConfig.DEBUG) checkId()
@ -90,9 +100,11 @@ sealed class MatrixItem(
override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar)
} }
data class RoomAliasItem(override val id: String, data class RoomAliasItem(
override val id: String,
override val displayName: String? = null, override val displayName: String? = null,
override val avatarUrl: String? = null) : override val avatarUrl: String? = null
) :
MatrixItem(id, displayName, avatarUrl) { MatrixItem(id, displayName, avatarUrl) {
init { init {
if (BuildConfig.DEBUG) checkId() if (BuildConfig.DEBUG) checkId()
@ -101,9 +113,11 @@ sealed class MatrixItem(
override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar) override fun updateAvatar(newAvatar: String?) = copy(avatarUrl = newAvatar)
} }
data class GroupItem(override val id: String, data class GroupItem(
override val id: String,
override val displayName: String? = null, override val displayName: String? = null,
override val avatarUrl: String? = null) : override val avatarUrl: String? = null
) :
MatrixItem(id, displayName, avatarUrl) { MatrixItem(id, displayName, avatarUrl) {
init { init {
if (BuildConfig.DEBUG) checkId() if (BuildConfig.DEBUG) checkId()

View File

@ -27,8 +27,10 @@ import org.matrix.android.sdk.internal.session.SessionComponent
import javax.inject.Inject import javax.inject.Inject
@MatrixScope @MatrixScope
internal class SessionManager @Inject constructor(private val matrixComponent: MatrixComponent, internal class SessionManager @Inject constructor(
private val sessionParamsStore: SessionParamsStore) { private val matrixComponent: MatrixComponent,
private val sessionParamsStore: SessionParamsStore
) {
// SessionId -> SessionComponent // SessionId -> SessionComponent
private val sessionComponents = HashMap<String, SessionComponent>() private val sessionComponents = HashMap<String, SessionComponent>()

View File

@ -98,15 +98,19 @@ internal interface AuthAPI {
* https://github.com/matrix-org/matrix-doc/pull/2290 * https://github.com/matrix-org/matrix-doc/pull/2290
*/ */
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "register/{threePid}/requestToken") @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "register/{threePid}/requestToken")
suspend fun add3Pid(@Path("threePid") threePid: String, suspend fun add3Pid(
@Body params: AddThreePidRegistrationParams): AddThreePidRegistrationResponse @Path("threePid") threePid: String,
@Body params: AddThreePidRegistrationParams
): AddThreePidRegistrationResponse
/** /**
* Validate 3pid. * Validate 3pid.
*/ */
@POST @POST
suspend fun validate3Pid(@Url url: String, suspend fun validate3Pid(
@Body params: ValidationCodeBody): SuccessResult @Url url: String,
@Body params: ValidationCodeBody
): SuccessResult
/** /**
* Get the supported login flow. * Get the supported login flow.

View File

@ -46,9 +46,11 @@ internal abstract class AuthModule {
@JvmStatic @JvmStatic
@Provides @Provides
@AuthDatabase @AuthDatabase
fun providesRealmConfiguration(context: Context, fun providesRealmConfiguration(
context: Context,
realmKeysUtils: RealmKeysUtils, realmKeysUtils: RealmKeysUtils,
authRealmMigration: AuthRealmMigration): RealmConfiguration { authRealmMigration: AuthRealmMigration
): RealmConfiguration {
val old = File(context.filesDir, "matrix-sdk-auth") val old = File(context.filesDir, "matrix-sdk-auth")
if (old.exists()) { if (old.exists()) {
old.renameTo(File(context.filesDir, "matrix-sdk-auth.realm")) old.renameTo(File(context.filesDir, "matrix-sdk-auth.realm"))

View File

@ -368,13 +368,17 @@ internal class DefaultAuthenticationService @Inject constructor(
pendingSessionStore.delete() pendingSessionStore.delete()
} }
override suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig, override suspend fun createSessionFromSso(
credentials: Credentials): Session { homeServerConnectionConfig: HomeServerConnectionConfig,
credentials: Credentials
): Session {
return sessionCreator.createSession(credentials, homeServerConnectionConfig) return sessionCreator.createSession(credentials, homeServerConnectionConfig)
} }
override suspend fun getWellKnownData(matrixId: String, override suspend fun getWellKnownData(
homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult { matrixId: String,
homeServerConnectionConfig: HomeServerConnectionConfig?
): WellknownResult {
if (!MatrixPatterns.isUserId(matrixId)) { if (!MatrixPatterns.isUserId(matrixId)) {
throw MatrixIdFailure.InvalidMatrixId throw MatrixIdFailure.InvalidMatrixId
} }
@ -392,11 +396,13 @@ internal class DefaultAuthenticationService @Inject constructor(
.withHomeServerUri("https://dummy.org") .withHomeServerUri("https://dummy.org")
.build() .build()
override suspend fun directAuthentication(homeServerConnectionConfig: HomeServerConnectionConfig, override suspend fun directAuthentication(
homeServerConnectionConfig: HomeServerConnectionConfig,
matrixId: String, matrixId: String,
password: String, password: String,
initialDeviceName: String, initialDeviceName: String,
deviceId: String?): Session { deviceId: String?
): Session {
return directLoginTask.execute( return directLoginTask.execute(
DirectLoginTask.Params( DirectLoginTask.Params(
homeServerConnectionConfig = homeServerConnectionConfig, homeServerConnectionConfig = homeServerConnectionConfig,

View File

@ -31,7 +31,8 @@ internal data class PasswordLoginParams(
@Json(name = "password") val password: String, @Json(name = "password") val password: String,
@Json(name = "type") override val type: String, @Json(name = "type") override val type: String,
@Json(name = "initial_device_display_name") val deviceDisplayName: String?, @Json(name = "initial_device_display_name") val deviceDisplayName: String?,
@Json(name = "device_id") val deviceId: String?) : LoginParams { @Json(name = "device_id") val deviceId: String?
) : LoginParams {
companion object { companion object {
private const val IDENTIFIER_KEY_TYPE = "type" private const val IDENTIFIER_KEY_TYPE = "type"
@ -47,10 +48,12 @@ internal data class PasswordLoginParams(
private const val IDENTIFIER_KEY_COUNTRY = "country" private const val IDENTIFIER_KEY_COUNTRY = "country"
private const val IDENTIFIER_KEY_PHONE = "phone" private const val IDENTIFIER_KEY_PHONE = "phone"
fun userIdentifier(user: String, fun userIdentifier(
user: String,
password: String, password: String,
deviceDisplayName: String?, deviceDisplayName: String?,
deviceId: String?): PasswordLoginParams { deviceId: String?
): PasswordLoginParams {
return PasswordLoginParams( return PasswordLoginParams(
identifier = mapOf( identifier = mapOf(
IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_USER, IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_USER,
@ -63,11 +66,13 @@ internal data class PasswordLoginParams(
) )
} }
fun thirdPartyIdentifier(medium: String, fun thirdPartyIdentifier(
medium: String,
address: String, address: String,
password: String, password: String,
deviceDisplayName: String?, deviceDisplayName: String?,
deviceId: String?): PasswordLoginParams { deviceId: String?
): PasswordLoginParams {
return PasswordLoginParams( return PasswordLoginParams(
identifier = mapOf( identifier = mapOf(
IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_THIRD_PARTY, IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_THIRD_PARTY,
@ -81,11 +86,13 @@ internal data class PasswordLoginParams(
) )
} }
fun phoneIdentifier(country: String, fun phoneIdentifier(
country: String,
phone: String, phone: String,
password: String, password: String,
deviceDisplayName: String?, deviceDisplayName: String?,
deviceId: String?): PasswordLoginParams { deviceId: String?
): PasswordLoginParams {
return PasswordLoginParams( return PasswordLoginParams(
identifier = mapOf( identifier = mapOf(
IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_PHONE, IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_PHONE,

View File

@ -23,7 +23,8 @@ import org.matrix.android.sdk.internal.database.awaitTransaction
import org.matrix.android.sdk.internal.di.AuthDatabase import org.matrix.android.sdk.internal.di.AuthDatabase
import javax.inject.Inject import javax.inject.Inject
internal class RealmPendingSessionStore @Inject constructor(private val mapper: PendingSessionMapper, internal class RealmPendingSessionStore @Inject constructor(
private val mapper: PendingSessionMapper,
@AuthDatabase @AuthDatabase
private val realmConfiguration: RealmConfiguration private val realmConfiguration: RealmConfiguration
) : PendingSessionStore { ) : PendingSessionStore {

View File

@ -28,7 +28,8 @@ import org.matrix.android.sdk.internal.di.AuthDatabase
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
internal class RealmSessionParamsStore @Inject constructor(private val mapper: SessionParamsMapper, internal class RealmSessionParamsStore @Inject constructor(
private val mapper: SessionParamsMapper,
@AuthDatabase @AuthDatabase
private val realmConfiguration: RealmConfiguration private val realmConfiguration: RealmConfiguration
) : SessionParamsStore { ) : SessionParamsStore {

View File

@ -52,10 +52,12 @@ internal class DefaultLoginWizard(
return getProfileTask.execute(GetProfileTask.Params(matrixId)) return getProfileTask.execute(GetProfileTask.Params(matrixId))
} }
override suspend fun login(login: String, override suspend fun login(
login: String,
password: String, password: String,
initialDeviceName: String, initialDeviceName: String,
deviceId: String?): Session { deviceId: String?
): Session {
val loginParams = if (Patterns.EMAIL_ADDRESS.matcher(login).matches()) { val loginParams = if (Patterns.EMAIL_ADDRESS.matcher(login).matches()) {
PasswordLoginParams.thirdPartyIdentifier( PasswordLoginParams.thirdPartyIdentifier(
medium = ThreePidMedium.EMAIL, medium = ThreePidMedium.EMAIL,

View File

@ -69,9 +69,11 @@ internal class DefaultRegistrationWizard(
return performRegistrationRequest(params) return performRegistrationRequest(params)
} }
override suspend fun createAccount(userName: String?, override suspend fun createAccount(
userName: String?,
password: String?, password: String?,
initialDeviceDisplayName: String?): RegistrationResult { initialDeviceDisplayName: String?
): RegistrationResult {
val params = RegistrationParams( val params = RegistrationParams(
username = userName, username = userName,
password = password, password = password,

View File

@ -40,9 +40,11 @@ internal data class ThreePidData(
} }
companion object { companion object {
fun from(threePid: RegisterThreePid, fun from(
threePid: RegisterThreePid,
addThreePidRegistrationResponse: AddThreePidRegistrationResponse, addThreePidRegistrationResponse: AddThreePidRegistrationResponse,
registrationParams: RegistrationParams): ThreePidData { registrationParams: RegistrationParams
): ThreePidData {
return when (threePid) { return when (threePid) {
is RegisterThreePid.Email -> is RegisterThreePid.Email ->
ThreePidData(threePid.email, "", "", addThreePidRegistrationResponse, registrationParams) ThreePidData(threePid.email, "", "", addThreePidRegistrationResponse, registrationParams)

View File

@ -35,9 +35,11 @@ import kotlin.coroutines.suspendCoroutine
* @return UiaResult if UIA handled, failed or cancelled * @return UiaResult if UIA handled, failed or cancelled
* *
*/ */
internal suspend fun handleUIA(failure: Throwable, internal suspend fun handleUIA(
failure: Throwable,
interceptor: UserInteractiveAuthInterceptor, interceptor: UserInteractiveAuthInterceptor,
retryBlock: suspend (UIABaseAuth) -> Unit): UiaResult { retryBlock: suspend (UIABaseAuth) -> Unit
): UiaResult {
Timber.d("## UIA: check error ${failure.message}") Timber.d("## UIA: check error ${failure.message}")
val flowResponse = failure.toRegistrationFlowResponse() val flowResponse = failure.toRegistrationFlowResponse()
?: return UiaResult.FAILURE.also { ?: return UiaResult.FAILURE.also {

View File

@ -110,10 +110,12 @@ internal abstract class CryptoModule {
@Provides @Provides
@CryptoDatabase @CryptoDatabase
@SessionScope @SessionScope
fun providesRealmConfiguration(@SessionFilesDirectory directory: File, fun providesRealmConfiguration(
@SessionFilesDirectory directory: File,
@UserMd5 userMd5: String, @UserMd5 userMd5: String,
realmKeysUtils: RealmKeysUtils, realmKeysUtils: RealmKeysUtils,
realmCryptoStoreMigration: RealmCryptoStoreMigration): RealmConfiguration { realmCryptoStoreMigration: RealmCryptoStoreMigration
): RealmConfiguration {
return RealmConfiguration.Builder() return RealmConfiguration.Builder()
.directory(directory) .directory(directory)
.apply { .apply {

View File

@ -592,10 +592,12 @@ internal class DefaultCryptoService @Inject constructor(
* @param membersId list of members to start tracking their devices * @param membersId list of members to start tracking their devices
* @return true if the operation succeeds. * @return true if the operation succeeds.
*/ */
private suspend fun setEncryptionInRoom(roomId: String, private suspend fun setEncryptionInRoom(
roomId: String,
algorithm: String?, algorithm: String?,
inhibitDeviceQuery: Boolean, inhibitDeviceQuery: Boolean,
membersId: List<String>): Boolean { membersId: List<String>
): Boolean {
// If we already have encryption in this room, we should ignore this event // If we already have encryption in this room, we should ignore this event
// (for now at least. Maybe we should alert the user somehow?) // (for now at least. Maybe we should alert the user somehow?)
val existingAlgorithm = cryptoStore.getRoomAlgorithm(roomId) val existingAlgorithm = cryptoStore.getRoomAlgorithm(roomId)
@ -691,10 +693,12 @@ internal class DefaultCryptoService @Inject constructor(
* @param roomId the room identifier the event will be sent. * @param roomId the room identifier the event will be sent.
* @param callback the asynchronous callback * @param callback the asynchronous callback
*/ */
override fun encryptEventContent(eventContent: Content, override fun encryptEventContent(
eventContent: Content,
eventType: String, eventType: String,
roomId: String, roomId: String,
callback: MatrixCallback<MXEncryptEventContentResult>) { callback: MatrixCallback<MXEncryptEventContentResult>
) {
// moved to crypto scope to have uptodate values // moved to crypto scope to have uptodate values
cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
val userIds = getRoomUserIds(roomId) val userIds = getRoomUserIds(roomId)
@ -879,8 +883,10 @@ internal class DefaultCryptoService @Inject constructor(
/** /**
* Returns true if handled by SDK, otherwise should be sent to application layer. * Returns true if handled by SDK, otherwise should be sent to application layer.
*/ */
private fun handleSDKLevelGossip(secretName: String?, private fun handleSDKLevelGossip(
secretValue: String): Boolean { secretName: String?,
secretValue: String
): Boolean {
return when (secretName) { return when (secretName) {
MASTER_KEY_SSSS_NAME -> { MASTER_KEY_SSSS_NAME -> {
crossSigningService.onSecretMSKGossip(secretValue) crossSigningService.onSecretMSKGossip(secretValue)
@ -1022,9 +1028,11 @@ internal class DefaultCryptoService @Inject constructor(
* @param progressListener the progress listener * @param progressListener the progress listener
* @return the result ImportRoomKeysResult * @return the result ImportRoomKeysResult
*/ */
override suspend fun importRoomKeys(roomKeysAsArray: ByteArray, override suspend fun importRoomKeys(
roomKeysAsArray: ByteArray,
password: String, password: String,
progressListener: ProgressListener?): ImportRoomKeysResult { progressListener: ProgressListener?
): ImportRoomKeysResult {
return withContext(coroutineDispatchers.crypto) { return withContext(coroutineDispatchers.crypto) {
Timber.tag(loggerTag.value).v("importRoomKeys starts") Timber.tag(loggerTag.value).v("importRoomKeys starts")

View File

@ -44,7 +44,8 @@ private val loggerTag = LoggerTag("InboundGroupSessionStore", LoggerTag.CRYPTO)
internal class InboundGroupSessionStore @Inject constructor( internal class InboundGroupSessionStore @Inject constructor(
private val store: IMXCryptoStore, private val store: IMXCryptoStore,
private val cryptoCoroutineScope: CoroutineScope, private val cryptoCoroutineScope: CoroutineScope,
private val coroutineDispatchers: MatrixCoroutineDispatchers) { private val coroutineDispatchers: MatrixCoroutineDispatchers
) {
private data class CacheKey( private data class CacheKey(
val sessionId: String, val sessionId: String,

View File

@ -369,9 +369,11 @@ internal class IncomingKeyRequestManager @Inject constructor(
shareMegolmKey(validReq, requestingDevice, null) shareMegolmKey(validReq, requestingDevice, null)
} }
private suspend fun shareMegolmKey(validRequest: ValidMegolmRequestBody, private suspend fun shareMegolmKey(
validRequest: ValidMegolmRequestBody,
requestingDevice: CryptoDeviceInfo, requestingDevice: CryptoDeviceInfo,
chainIndex: Long?): Boolean { chainIndex: Long?
): Boolean {
Timber.tag(loggerTag.value) Timber.tag(loggerTag.value)
.d("try to re-share Megolm Key at index $chainIndex for ${validRequest.shortDbgString()}") .d("try to re-share Megolm Key at index $chainIndex for ${validRequest.shortDbgString()}")

View File

@ -599,13 +599,15 @@ internal class MXOlmDevice @Inject constructor(
* @param exportFormat true if the megolm keys are in export format * @param exportFormat true if the megolm keys are in export format
* @return true if the operation succeeds. * @return true if the operation succeeds.
*/ */
fun addInboundGroupSession(sessionId: String, fun addInboundGroupSession(
sessionId: String,
sessionKey: String, sessionKey: String,
roomId: String, roomId: String,
senderKey: String, senderKey: String,
forwardingCurve25519KeyChain: List<String>, forwardingCurve25519KeyChain: List<String>,
keysClaimed: Map<String, String>, keysClaimed: Map<String, String>,
exportFormat: Boolean): AddSessionResult { exportFormat: Boolean
): AddSessionResult {
val candidateSession = OlmInboundGroupSessionWrapper2(sessionKey, exportFormat) val candidateSession = OlmInboundGroupSessionWrapper2(sessionKey, exportFormat)
val existingSessionHolder = tryOrNull { getInboundGroupSession(sessionId, senderKey, roomId) } val existingSessionHolder = tryOrNull { getInboundGroupSession(sessionId, senderKey, roomId) }
val existingSession = existingSessionHolder?.wrapper val existingSession = existingSessionHolder?.wrapper
@ -760,11 +762,13 @@ internal class MXOlmDevice @Inject constructor(
* @return the decrypting result. Nil if the sessionId is unknown. * @return the decrypting result. Nil if the sessionId is unknown.
*/ */
@Throws(MXCryptoError::class) @Throws(MXCryptoError::class)
suspend fun decryptGroupMessage(body: String, suspend fun decryptGroupMessage(
body: String,
roomId: String, roomId: String,
timeline: String?, timeline: String?,
sessionId: String, sessionId: String,
senderKey: String): OlmDecryptionResult { senderKey: String
): OlmDecryptionResult {
val sessionHolder = getInboundGroupSession(sessionId, senderKey, roomId) val sessionHolder = getInboundGroupSession(sessionId, senderKey, roomId)
val wrapper = sessionHolder.wrapper val wrapper = sessionHolder.wrapper
val inboundGroupSession = wrapper.olmInboundGroupSession val inboundGroupSession = wrapper.olmInboundGroupSession

View File

@ -19,8 +19,10 @@ package org.matrix.android.sdk.internal.crypto
import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.Credentials
import javax.inject.Inject import javax.inject.Inject
internal class ObjectSigner @Inject constructor(private val credentials: Credentials, internal class ObjectSigner @Inject constructor(
private val olmDevice: MXOlmDevice) { private val credentials: Credentials,
private val olmDevice: MXOlmDevice
) {
/** /**
* Sign Object. * Sign Object.

View File

@ -71,7 +71,8 @@ internal class OutgoingKeyRequestManager @Inject constructor(
private val inboundGroupSessionStore: InboundGroupSessionStore, private val inboundGroupSessionStore: InboundGroupSessionStore,
private val sendToDeviceTask: SendToDeviceTask, private val sendToDeviceTask: SendToDeviceTask,
private val deviceListManager: DeviceListManager, private val deviceListManager: DeviceListManager,
private val perSessionBackupQueryRateLimiter: PerSessionBackupQueryRateLimiter) { private val perSessionBackupQueryRateLimiter: PerSessionBackupQueryRateLimiter
) {
private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
private val outgoingRequestScope = CoroutineScope(SupervisorJob() + dispatcher) private val outgoingRequestScope = CoroutineScope(SupervisorJob() + dispatcher)
@ -180,13 +181,15 @@ internal class OutgoingKeyRequestManager @Inject constructor(
} }
} }
fun onRoomKeyForwarded(sessionId: String, fun onRoomKeyForwarded(
sessionId: String,
algorithm: String, algorithm: String,
roomId: String, roomId: String,
senderKey: String, senderKey: String,
fromDevice: String?, fromDevice: String?,
fromIndex: Int, fromIndex: Int,
event: Event) { event: Event
) {
Timber.tag(loggerTag.value).d("Key forwarded for $sessionId from ${event.senderId}|$fromDevice at index $fromIndex") Timber.tag(loggerTag.value).d("Key forwarded for $sessionId from ${event.senderId}|$fromDevice at index $fromIndex")
outgoingRequestScope.launch { outgoingRequestScope.launch {
sequencer.post { sequencer.post {
@ -208,12 +211,14 @@ internal class OutgoingKeyRequestManager @Inject constructor(
} }
} }
fun onRoomKeyWithHeld(sessionId: String, fun onRoomKeyWithHeld(
sessionId: String,
algorithm: String, algorithm: String,
roomId: String, roomId: String,
senderKey: String, senderKey: String,
fromDevice: String?, fromDevice: String?,
event: Event) { event: Event
) {
outgoingRequestScope.launch { outgoingRequestScope.launch {
sequencer.post { sequencer.post {
Timber.tag(loggerTag.value).d("Withheld received for $sessionId from ${event.senderId}|$fromDevice") Timber.tag(loggerTag.value).d("Withheld received for $sessionId from ${event.senderId}|$fromDevice")

View File

@ -39,7 +39,8 @@ private val loggerTag = LoggerTag("EnsureOlmSessionsForDevicesAction", LoggerTag
internal class EnsureOlmSessionsForDevicesAction @Inject constructor( internal class EnsureOlmSessionsForDevicesAction @Inject constructor(
private val olmDevice: MXOlmDevice, private val olmDevice: MXOlmDevice,
private val coroutineDispatchers: MatrixCoroutineDispatchers, private val coroutineDispatchers: MatrixCoroutineDispatchers,
private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask) { private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask
) {
private val ensureMutex = Mutex() private val ensureMutex = Mutex()

View File

@ -23,9 +23,11 @@ import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
internal class EnsureOlmSessionsForUsersAction @Inject constructor(private val olmDevice: MXOlmDevice, internal class EnsureOlmSessionsForUsersAction @Inject constructor(
private val olmDevice: MXOlmDevice,
private val cryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction) { private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction
) {
/** /**
* Try to make sure we have established olm sessions for the given users. * Try to make sure we have established olm sessions for the given users.

View File

@ -33,7 +33,8 @@ import javax.inject.Inject
private val loggerTag = LoggerTag("MegolmSessionDataImporter", LoggerTag.CRYPTO) private val loggerTag = LoggerTag("MegolmSessionDataImporter", LoggerTag.CRYPTO)
internal class MegolmSessionDataImporter @Inject constructor(private val olmDevice: MXOlmDevice, internal class MegolmSessionDataImporter @Inject constructor(
private val olmDevice: MXOlmDevice,
private val roomDecryptorProvider: RoomDecryptorProvider, private val roomDecryptorProvider: RoomDecryptorProvider,
private val outgoingKeyRequestManager: OutgoingKeyRequestManager, private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
private val cryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
@ -50,9 +51,11 @@ internal class MegolmSessionDataImporter @Inject constructor(private val olmDevi
* @return import room keys result * @return import room keys result
*/ */
@WorkerThread @WorkerThread
fun handle(megolmSessionsData: List<MegolmSessionData>, fun handle(
megolmSessionsData: List<MegolmSessionData>,
fromBackup: Boolean, fromBackup: Boolean,
progressListener: ProgressListener?): ImportRoomKeysResult { progressListener: ProgressListener?
): ImportRoomKeysResult {
val t0 = clock.epochMillis() val t0 = clock.epochMillis()
val totalNumbersOfKeys = megolmSessionsData.size val totalNumbersOfKeys = megolmSessionsData.size

View File

@ -36,7 +36,8 @@ internal class MessageEncrypter @Inject constructor(
private val userId: String, private val userId: String,
@DeviceId @DeviceId
private val deviceId: String?, private val deviceId: String?,
private val olmDevice: MXOlmDevice) { private val olmDevice: MXOlmDevice
) {
/** /**
* Encrypt an event payload for a list of devices. * Encrypt an event payload for a list of devices.
* This method must be called from the getCryptoHandler() thread. * This method must be called from the getCryptoHandler() thread.

View File

@ -26,7 +26,8 @@ import javax.inject.Inject
internal class SetDeviceVerificationAction @Inject constructor( internal class SetDeviceVerificationAction @Inject constructor(
private val cryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
@UserId private val userId: String, @UserId private val userId: String,
private val defaultKeysBackupService: DefaultKeysBackupService) { private val defaultKeysBackupService: DefaultKeysBackupService
) {
fun handle(trustLevel: DeviceTrustLevel, userId: String, deviceId: String) { fun handle(trustLevel: DeviceTrustLevel, userId: String, deviceId: String) {
val device = cryptoStore.getUserDevice(userId, deviceId) val device = cryptoStore.getUserDevice(userId, deviceId)

View File

@ -45,8 +45,10 @@ internal interface IMXGroupEncryption {
* *
* @return true in case of success * @return true in case of success
*/ */
suspend fun reshareKey(groupSessionId: String, suspend fun reshareKey(
groupSessionId: String,
userId: String, userId: String,
deviceId: String, deviceId: String,
senderKey: String): Boolean senderKey: String
): Boolean
} }

View File

@ -148,7 +148,8 @@ internal class MXMegolmDecryption(
throw MXCryptoError.Base( throw MXCryptoError.Base(
MXCryptoError.ErrorType.KEYS_WITHHELD, MXCryptoError.ErrorType.KEYS_WITHHELD,
withHeldInfo.code?.value ?: "", withHeldInfo.code?.value ?: "",
withHeldInfo.reason) withHeldInfo.reason
)
} }
if (requestKeysOnFail) { if (requestKeysOnFail) {
@ -267,7 +268,8 @@ internal class MXMegolmDecryption(
senderKey = senderKey, senderKey = senderKey,
fromIndex = index, fromIndex = index,
fromDevice = fromDevice, fromDevice = fromDevice,
event = event) event = event
)
cryptoStore.saveIncomingForwardKeyAuditTrail( cryptoStore.saveIncomingForwardKeyAuditTrail(
roomId = roomKeyContent.roomId, roomId = roomKeyContent.roomId,
@ -276,7 +278,8 @@ internal class MXMegolmDecryption(
algorithm = roomKeyContent.algorithm ?: "", algorithm = roomKeyContent.algorithm ?: "",
userId = event.senderId ?: "", userId = event.senderId ?: "",
deviceId = fromDevice ?: "", deviceId = fromDevice ?: "",
chainIndex = index.toLong()) chainIndex = index.toLong()
)
// The index is used to decide if we cancel sent request or if we wait for a better key // The index is used to decide if we cancel sent request or if we wait for a better key
outgoingKeyRequestManager.postCancelRequestForSessionIfNeeded(roomKeyContent.sessionId, roomKeyContent.roomId, senderKey, index) outgoingKeyRequestManager.postCancelRequestForSessionIfNeeded(roomKeyContent.sessionId, roomKeyContent.roomId, senderKey, index)

View File

@ -35,6 +35,7 @@ internal class MXMegolmDecryptionFactory @Inject constructor(
olmDevice, olmDevice,
outgoingKeyRequestManager, outgoingKeyRequestManager,
cryptoStore, cryptoStore,
eventsManager) eventsManager
)
} }
} }

View File

@ -84,9 +84,11 @@ internal class MXMegolmEncryption(
private var sessionRotationPeriodMsgs: Int = 100 private var sessionRotationPeriodMsgs: Int = 100
private var sessionRotationPeriodMs: Int = 7 * 24 * 3600 * 1000 private var sessionRotationPeriodMs: Int = 7 * 24 * 3600 * 1000
override suspend fun encryptEventContent(eventContent: Content, override suspend fun encryptEventContent(
eventContent: Content,
eventType: String, eventType: String,
userIds: List<String>): Content { userIds: List<String>
): Content {
val ts = clock.epochMillis() val ts = clock.epochMillis()
Timber.tag(loggerTag.value).v("encryptEventContent : getDevicesInRoom") Timber.tag(loggerTag.value).v("encryptEventContent : getDevicesInRoom")
val devices = getDevicesInRoom(userIds) val devices = getDevicesInRoom(userIds)
@ -201,8 +203,10 @@ internal class MXMegolmEncryption(
* @param session the session info * @param session the session info
* @param devicesByUsers the devices map * @param devicesByUsers the devices map
*/ */
private suspend fun shareKey(session: MXOutboundSessionInfo, private suspend fun shareKey(
devicesByUsers: Map<String, List<CryptoDeviceInfo>>) { session: MXOutboundSessionInfo,
devicesByUsers: Map<String, List<CryptoDeviceInfo>>
) {
// nothing to send, the task is done // nothing to send, the task is done
if (devicesByUsers.isEmpty()) { if (devicesByUsers.isEmpty()) {
Timber.tag(loggerTag.value).v("shareKey() : nothing more to do") Timber.tag(loggerTag.value).v("shareKey() : nothing more to do")
@ -230,8 +234,10 @@ internal class MXMegolmEncryption(
* @param session the session info * @param session the session info
* @param devicesByUser the devices map * @param devicesByUser the devices map
*/ */
private suspend fun shareUserDevicesKey(session: MXOutboundSessionInfo, private suspend fun shareUserDevicesKey(
devicesByUser: Map<String, List<CryptoDeviceInfo>>) { session: MXOutboundSessionInfo,
devicesByUser: Map<String, List<CryptoDeviceInfo>>
) {
val sessionKey = olmDevice.getSessionKey(session.sessionId) val sessionKey = olmDevice.getSessionKey(session.sessionId)
val chainIndex = olmDevice.getMessageIndex(session.sessionId) val chainIndex = olmDevice.getMessageIndex(session.sessionId)
@ -321,10 +327,12 @@ internal class MXMegolmEncryption(
} }
} }
private suspend fun notifyKeyWithHeld(targets: List<UserDevice>, private suspend fun notifyKeyWithHeld(
targets: List<UserDevice>,
sessionId: String, sessionId: String,
senderKey: String?, senderKey: String?,
code: WithHeldCode) { code: WithHeldCode
) {
Timber.tag(loggerTag.value).d( Timber.tag(loggerTag.value).d(
"notifyKeyWithHeld() :sending withheld for session:$sessionId and code $code to" + "notifyKeyWithHeld() :sending withheld for session:$sessionId and code $code to" +
" ${targets.joinToString { "${it.userId}|${it.deviceId}" }}" " ${targets.joinToString { "${it.userId}|${it.deviceId}" }}"
@ -435,10 +443,12 @@ internal class MXMegolmEncryption(
} }
} }
override suspend fun reshareKey(groupSessionId: String, override suspend fun reshareKey(
groupSessionId: String,
userId: String, userId: String,
deviceId: String, deviceId: String,
senderKey: String): Boolean { senderKey: String
): Boolean {
Timber.tag(loggerTag.value).i("process reshareKey for $groupSessionId to $userId:$deviceId") Timber.tag(loggerTag.value).i("process reshareKey for $groupSessionId to $userId:$deviceId")
val deviceInfo = cryptoStore.getUserDevice(userId, deviceId) ?: return false val deviceInfo = cryptoStore.getUserDevice(userId, deviceId) ?: return false
.also { Timber.tag(loggerTag.value).w("reshareKey: Device not found") } .also { Timber.tag(loggerTag.value).w("reshareKey: Device not found") }

View File

@ -23,7 +23,8 @@ import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
internal class SharedWithHelper( internal class SharedWithHelper(
private val roomId: String, private val roomId: String,
private val sessionId: String, private val sessionId: String,
private val cryptoStore: IMXCryptoStore) { private val cryptoStore: IMXCryptoStore
) {
fun sharedWithDevices(): MXUsersDevicesMap<Int> { fun sharedWithDevices(): MXUsersDevicesMap<Int> {
return cryptoStore.getSharedWithInfo(roomId, sessionId) return cryptoStore.getSharedWithInfo(roomId, sessionId)

View File

@ -38,7 +38,8 @@ internal class MXOlmDecryption(
// The olm device interface // The olm device interface
private val olmDevice: MXOlmDevice, private val olmDevice: MXOlmDevice,
// the matrix userId // the matrix userId
private val userId: String) : private val userId: String
) :
IMXDecrypting { IMXDecrypting {
@Throws(MXCryptoError::class) @Throws(MXCryptoError::class)

View File

@ -20,8 +20,10 @@ import org.matrix.android.sdk.internal.crypto.MXOlmDevice
import org.matrix.android.sdk.internal.di.UserId import org.matrix.android.sdk.internal.di.UserId
import javax.inject.Inject import javax.inject.Inject
internal class MXOlmDecryptionFactory @Inject constructor(private val olmDevice: MXOlmDevice, internal class MXOlmDecryptionFactory @Inject constructor(
@UserId private val userId: String) { private val olmDevice: MXOlmDevice,
@UserId private val userId: String
) {
fun create(): MXOlmDecryption { fun create(): MXOlmDecryption {
return MXOlmDecryption( return MXOlmDecryption(

View File

@ -32,7 +32,8 @@ internal class MXOlmEncryption(
private val cryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val messageEncrypter: MessageEncrypter, private val messageEncrypter: MessageEncrypter,
private val deviceListManager: DeviceListManager, private val deviceListManager: DeviceListManager,
private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) : private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction
) :
IMXEncrypting { IMXEncrypting {
override suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List<String>): Content { override suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List<String>): Content {

View File

@ -24,12 +24,14 @@ import org.matrix.android.sdk.internal.crypto.actions.MessageEncrypter
import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
import javax.inject.Inject import javax.inject.Inject
internal class MXOlmEncryptionFactory @Inject constructor(private val olmDevice: MXOlmDevice, internal class MXOlmEncryptionFactory @Inject constructor(
private val olmDevice: MXOlmDevice,
private val cryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val messageEncrypter: MessageEncrypter, private val messageEncrypter: MessageEncrypter,
private val deviceListManager: DeviceListManager, private val deviceListManager: DeviceListManager,
private val coroutineDispatchers: MatrixCoroutineDispatchers, private val coroutineDispatchers: MatrixCoroutineDispatchers,
private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) { private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction
) {
fun create(roomId: String): MXOlmEncryption { fun create(roomId: String): MXOlmEncryption {
return MXOlmEncryption( return MXOlmEncryption(

View File

@ -117,9 +117,11 @@ internal interface CryptoApi {
* @param body the body * @param body the body
*/ */
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sendToDevice/{eventType}/{txnId}") @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sendToDevice/{eventType}/{txnId}")
suspend fun sendToDevice(@Path("eventType") eventType: String, suspend fun sendToDevice(
@Path("eventType") eventType: String,
@Path("txnId") transactionId: String, @Path("txnId") transactionId: String,
@Body body: SendToDeviceBody) @Body body: SendToDeviceBody
)
/** /**
* Delete a device. * Delete a device.
@ -129,8 +131,10 @@ internal interface CryptoApi {
* @param params the deletion parameters * @param params the deletion parameters
*/ */
@HTTP(path = NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}", method = "DELETE", hasBody = true) @HTTP(path = NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}", method = "DELETE", hasBody = true)
suspend fun deleteDevice(@Path("device_id") deviceId: String, suspend fun deleteDevice(
@Body params: DeleteDeviceParams) @Path("device_id") deviceId: String,
@Body params: DeleteDeviceParams
)
/** /**
* Update the device information. * Update the device information.
@ -140,8 +144,10 @@ internal interface CryptoApi {
* @param params the params * @param params the params
*/ */
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}") @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}")
suspend fun updateDeviceInfo(@Path("device_id") deviceId: String, suspend fun updateDeviceInfo(
@Body params: UpdateDeviceInfoBody) @Path("device_id") deviceId: String,
@Body params: UpdateDeviceInfoBody
)
/** /**
* Get the update devices list from two sync token. * Get the update devices list from two sync token.
@ -151,6 +157,8 @@ internal interface CryptoApi {
* @param newToken the up-to token. * @param newToken the up-to token.
*/ */
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/changes") @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/changes")
suspend fun getKeyChanges(@Query("from") oldToken: String, suspend fun getKeyChanges(
@Query("to") newToken: String): KeyChangesResponse @Query("from") oldToken: String,
@Query("to") newToken: String
): KeyChangesResponse
} }

View File

@ -41,10 +41,12 @@ internal object MXEncryptedAttachments {
private const val SECRET_KEY_SPEC_ALGORITHM = "AES" private const val SECRET_KEY_SPEC_ALGORITHM = "AES"
private const val MESSAGE_DIGEST_ALGORITHM = "SHA-256" private const val MESSAGE_DIGEST_ALGORITHM = "SHA-256"
fun encrypt(clearStream: InputStream, fun encrypt(
clearStream: InputStream,
outputFile: File, outputFile: File,
clock: Clock, clock: Clock,
progress: ((current: Int, total: Int) -> Unit)): EncryptedFileInfo { progress: ((current: Int, total: Int) -> Unit)
): EncryptedFileInfo {
val t0 = clock.epochMillis() val t0 = clock.epochMillis()
val secureRandom = SecureRandom() val secureRandom = SecureRandom()
val initVectorBytes = ByteArray(16) { 0.toByte() } val initVectorBytes = ByteArray(16) { 0.toByte() }
@ -236,7 +238,8 @@ internal object MXEncryptedAttachments {
* @param clock a clock to retrieve current time * @param clock a clock to retrieve current time
* @return true in case of success, false in case of error * @return true in case of success, false in case of error
*/ */
fun decryptAttachment(attachmentStream: InputStream?, fun decryptAttachment(
attachmentStream: InputStream?,
elementToDecrypt: ElementToDecrypt?, elementToDecrypt: ElementToDecrypt?,
outputStream: OutputStream, outputStream: OutputStream,
clock: Clock clock: Clock

View File

@ -261,7 +261,8 @@ internal class DefaultCrossSigningService @Inject constructor(
} }
} }
override fun checkTrustFromPrivateKeys(masterKeyPrivateKey: String?, override fun checkTrustFromPrivateKeys(
masterKeyPrivateKey: String?,
uskKeyPrivateKey: String?, uskKeyPrivateKey: String?,
sskPrivateKey: String? sskPrivateKey: String?
): UserTrustResult { ): UserTrustResult {

View File

@ -276,10 +276,12 @@ internal class UpdateTrustWorker(context: Context, params: WorkerParameters, ses
} }
} }
private fun computeRoomShield(myCrossSigningInfo: MXCrossSigningInfo?, private fun computeRoomShield(
myCrossSigningInfo: MXCrossSigningInfo?,
cryptoRealm: Realm, cryptoRealm: Realm,
activeMemberUserIds: List<String>, activeMemberUserIds: List<String>,
roomSummaryEntity: RoomSummaryEntity): RoomEncryptionTrustLevel { roomSummaryEntity: RoomSummaryEntity
): RoomEncryptionTrustLevel {
Timber.v("## CrossSigning - computeRoomShield ${roomSummaryEntity.roomId} -> ${activeMemberUserIds.logLimit()}") Timber.v("## CrossSigning - computeRoomShield ${roomSummaryEntity.roomId} -> ${activeMemberUserIds.logLimit()}")
// The set of “all users” depends on the type of room: // The set of “all users” depends on the type of room:
// For regular / topic rooms which have more than 2 members (including yourself) are considered when decorating a room // For regular / topic rooms which have more than 2 members (including yourself) are considered when decorating a room

View File

@ -157,9 +157,11 @@ internal class DefaultKeysBackupService @Inject constructor(
keysBackupStateManager.removeListener(listener) keysBackupStateManager.removeListener(listener)
} }
override fun prepareKeysBackupVersion(password: String?, override fun prepareKeysBackupVersion(
password: String?,
progressListener: ProgressListener?, progressListener: ProgressListener?,
callback: MatrixCallback<MegolmBackupCreationInfo>) { callback: MatrixCallback<MegolmBackupCreationInfo>
) {
cryptoCoroutineScope.launch(coroutineDispatchers.io) { cryptoCoroutineScope.launch(coroutineDispatchers.io) {
try { try {
val olmPkDecryption = OlmPkDecryption() val olmPkDecryption = OlmPkDecryption()
@ -233,8 +235,10 @@ internal class DefaultKeysBackupService @Inject constructor(
} }
} }
override fun createKeysBackupVersion(keysBackupCreationInfo: MegolmBackupCreationInfo, override fun createKeysBackupVersion(
callback: MatrixCallback<KeysVersion>) { keysBackupCreationInfo: MegolmBackupCreationInfo,
callback: MatrixCallback<KeysVersion>
) {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
val createKeysBackupVersionBody = CreateKeysBackupVersionBody( val createKeysBackupVersionBody = CreateKeysBackupVersionBody(
algorithm = keysBackupCreationInfo.algorithm, algorithm = keysBackupCreationInfo.algorithm,
@ -345,8 +349,10 @@ internal class DefaultKeysBackupService @Inject constructor(
return cryptoStore.inboundGroupSessionsCount(true) return cryptoStore.inboundGroupSessionsCount(true)
} }
override fun backupAllGroupSessions(progressListener: ProgressListener?, override fun backupAllGroupSessions(
callback: MatrixCallback<Unit>?) { progressListener: ProgressListener?,
callback: MatrixCallback<Unit>?
) {
if (!isEnabled || backupOlmPkEncryption == null || keysBackupVersion == null) { if (!isEnabled || backupOlmPkEncryption == null || keysBackupVersion == null) {
callback?.onFailure(Throwable("Backup not enabled")) callback?.onFailure(Throwable("Backup not enabled"))
return return
@ -397,8 +403,10 @@ internal class DefaultKeysBackupService @Inject constructor(
}) })
} }
override fun getKeysBackupTrust(keysBackupVersion: KeysVersionResult, override fun getKeysBackupTrust(
callback: MatrixCallback<KeysBackupVersionTrust>) { keysBackupVersion: KeysVersionResult,
callback: MatrixCallback<KeysBackupVersionTrust>
) {
// TODO Validate with François that this is correct // TODO Validate with François that this is correct
object : Task<KeysVersionResult, KeysBackupVersionTrust> { object : Task<KeysVersionResult, KeysBackupVersionTrust> {
override suspend fun execute(params: KeysVersionResult): KeysBackupVersionTrust { override suspend fun execute(params: KeysVersionResult): KeysBackupVersionTrust {
@ -505,9 +513,11 @@ internal class DefaultKeysBackupService @Inject constructor(
) )
} }
override fun trustKeysBackupVersion(keysBackupVersion: KeysVersionResult, override fun trustKeysBackupVersion(
keysBackupVersion: KeysVersionResult,
trust: Boolean, trust: Boolean,
callback: MatrixCallback<Unit>) { callback: MatrixCallback<Unit>
) {
Timber.v("trustKeyBackupVersion: $trust, version ${keysBackupVersion.version}") Timber.v("trustKeyBackupVersion: $trust, version ${keysBackupVersion.version}")
// Get auth data to update it // Get auth data to update it
@ -589,9 +599,11 @@ internal class DefaultKeysBackupService @Inject constructor(
} }
} }
override fun trustKeysBackupVersionWithRecoveryKey(keysBackupVersion: KeysVersionResult, override fun trustKeysBackupVersionWithRecoveryKey(
keysBackupVersion: KeysVersionResult,
recoveryKey: String, recoveryKey: String,
callback: MatrixCallback<Unit>) { callback: MatrixCallback<Unit>
) {
Timber.v("trustKeysBackupVersionWithRecoveryKey: version ${keysBackupVersion.version}") Timber.v("trustKeysBackupVersionWithRecoveryKey: version ${keysBackupVersion.version}")
cryptoCoroutineScope.launch(coroutineDispatchers.io) { cryptoCoroutineScope.launch(coroutineDispatchers.io) {
@ -608,9 +620,11 @@ internal class DefaultKeysBackupService @Inject constructor(
} }
} }
override fun trustKeysBackupVersionWithPassphrase(keysBackupVersion: KeysVersionResult, override fun trustKeysBackupVersionWithPassphrase(
keysBackupVersion: KeysVersionResult,
password: String, password: String,
callback: MatrixCallback<Unit>) { callback: MatrixCallback<Unit>
) {
Timber.v("trustKeysBackupVersionWithPassphrase: version ${keysBackupVersion.version}") Timber.v("trustKeysBackupVersionWithPassphrase: version ${keysBackupVersion.version}")
cryptoCoroutineScope.launch(coroutineDispatchers.io) { cryptoCoroutineScope.launch(coroutineDispatchers.io) {
@ -707,12 +721,14 @@ internal class DefaultKeysBackupService @Inject constructor(
progressListener.onProgress(backedUpKeys, total) progressListener.onProgress(backedUpKeys, total)
} }
override fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult, override fun restoreKeysWithRecoveryKey(
keysVersionResult: KeysVersionResult,
recoveryKey: String, recoveryKey: String,
roomId: String?, roomId: String?,
sessionId: String?, sessionId: String?,
stepProgressListener: StepProgressListener?, stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>) { callback: MatrixCallback<ImportRoomKeysResult>
) {
Timber.v("restoreKeysWithRecoveryKey: From backup version: ${keysVersionResult.version}") Timber.v("restoreKeysWithRecoveryKey: From backup version: ${keysVersionResult.version}")
cryptoCoroutineScope.launch(coroutineDispatchers.io) { cryptoCoroutineScope.launch(coroutineDispatchers.io) {
@ -806,12 +822,14 @@ internal class DefaultKeysBackupService @Inject constructor(
} }
} }
override fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult, override fun restoreKeyBackupWithPassword(
keysBackupVersion: KeysVersionResult,
password: String, password: String,
roomId: String?, roomId: String?,
sessionId: String?, sessionId: String?,
stepProgressListener: StepProgressListener?, stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>) { callback: MatrixCallback<ImportRoomKeysResult>
) {
Timber.v("[MXKeyBackup] restoreKeyBackup with password: From backup version: ${keysBackupVersion.version}") Timber.v("[MXKeyBackup] restoreKeyBackup with password: From backup version: ${keysBackupVersion.version}")
cryptoCoroutineScope.launch(coroutineDispatchers.io) { cryptoCoroutineScope.launch(coroutineDispatchers.io) {
@ -859,9 +877,11 @@ internal class DefaultKeysBackupService @Inject constructor(
* Same method as [RoomKeysRestClient.getRoomKey] except that it accepts nullable * Same method as [RoomKeysRestClient.getRoomKey] except that it accepts nullable
* parameters and always returns a KeysBackupData object through the Callback. * parameters and always returns a KeysBackupData object through the Callback.
*/ */
private suspend fun getKeys(sessionId: String?, private suspend fun getKeys(
sessionId: String?,
roomId: String?, roomId: String?,
version: String): KeysBackupData { version: String
): KeysBackupData {
return if (roomId != null && sessionId != null) { return if (roomId != null && sessionId != null) {
// Get key for the room and for the session // Get key for the room and for the session
val data = getRoomSessionDataTask.execute(GetRoomSessionDataTask.Params(roomId, sessionId, version)) val data = getRoomSessionDataTask.execute(GetRoomSessionDataTask.Params(roomId, sessionId, version))
@ -939,8 +959,10 @@ internal class DefaultKeysBackupService @Inject constructor(
} }
} }
override fun getVersion(version: String, override fun getVersion(
callback: MatrixCallback<KeysVersionResult?>) { version: String,
callback: MatrixCallback<KeysVersionResult?>
) {
getKeysBackupVersionTask getKeysBackupVersionTask
.configureWith(version) { .configureWith(version) {
this.callback = object : MatrixCallback<KeysVersionResult> { this.callback = object : MatrixCallback<KeysVersionResult> {
@ -1179,10 +1201,12 @@ internal class DefaultKeysBackupService @Inject constructor(
} }
} }
override fun computePrivateKey(passphrase: String, override fun computePrivateKey(
passphrase: String,
privateKeySalt: String, privateKeySalt: String,
privateKeyIterations: Int, privateKeyIterations: Int,
progressListener: ProgressListener): ByteArray { progressListener: ProgressListener
): ByteArray {
return deriveKey(passphrase, privateKeySalt, privateKeyIterations, progressListener) return deriveKey(passphrase, privateKeySalt, privateKeyIterations, progressListener)
} }
@ -1482,8 +1506,10 @@ internal class DefaultKeysBackupService @Inject constructor(
get() = cryptoStore get() = cryptoStore
@VisibleForTesting @VisibleForTesting
fun createFakeKeysBackupVersion(keysBackupCreationInfo: MegolmBackupCreationInfo, fun createFakeKeysBackupVersion(
callback: MatrixCallback<KeysVersion>) { keysBackupCreationInfo: MegolmBackupCreationInfo,
callback: MatrixCallback<KeysVersion>
) {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
val createKeysBackupVersionBody = CreateKeysBackupVersionBody( val createKeysBackupVersionBody = CreateKeysBackupVersionBody(
algorithm = keysBackupCreationInfo.algorithm, algorithm = keysBackupCreationInfo.algorithm,

View File

@ -49,7 +49,8 @@ internal data class GeneratePrivateKeyResult(
* @return a {privateKey, salt, iterations} tuple. * @return a {privateKey, salt, iterations} tuple.
*/ */
@WorkerThread @WorkerThread
internal fun generatePrivateKeyWithPassword(password: String, internal fun generatePrivateKeyWithPassword(
password: String,
progressListener: ProgressListener? progressListener: ProgressListener?
): GeneratePrivateKeyResult { ): GeneratePrivateKeyResult {
val salt = generateSalt() val salt = generateSalt()
@ -70,10 +71,12 @@ internal fun generatePrivateKeyWithPassword(password: String,
* @return a private key. * @return a private key.
*/ */
@WorkerThread @WorkerThread
internal fun retrievePrivateKeyWithPassword(password: String, internal fun retrievePrivateKeyWithPassword(
password: String,
salt: String, salt: String,
iterations: Int, iterations: Int,
progressListener: ProgressListener? = null): ByteArray { progressListener: ProgressListener? = null
): ByteArray {
return deriveKey(password, salt, iterations, progressListener) return deriveKey(password, salt, iterations, progressListener)
} }
@ -88,10 +91,12 @@ internal fun retrievePrivateKeyWithPassword(password: String,
* @return a private key. * @return a private key.
*/ */
@WorkerThread @WorkerThread
internal fun deriveKey(password: String, internal fun deriveKey(
password: String,
salt: String, salt: String,
iterations: Int, iterations: Int,
progressListener: ProgressListener?): ByteArray { progressListener: ProgressListener?
): ByteArray {
// Note: copied and adapted from MXMegolmExportEncryption // Note: copied and adapted from MXMegolmExportEncryption
// based on https://en.wikipedia.org/wiki/PBKDF2 algorithm // based on https://en.wikipedia.org/wiki/PBKDF2 algorithm
// it is simpler than the generic algorithm because the expected key length is equal to the mac key length. // it is simpler than the generic algorithm because the expected key length is equal to the mac key length.

View File

@ -71,8 +71,10 @@ internal interface RoomKeysApi {
* @param updateKeysBackupVersionBody the body * @param updateKeysBackupVersionBody the body
*/ */
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version/{version}") @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version/{version}")
suspend fun updateKeysBackupVersion(@Path("version") version: String, suspend fun updateKeysBackupVersion(
@Body updateKeysBackupVersionBody: UpdateKeysBackupVersionBody) @Path("version") version: String,
@Body updateKeysBackupVersionBody: UpdateKeysBackupVersionBody
)
/* ========================================================================================== /* ==========================================================================================
* Storing keys * Storing keys
@ -93,10 +95,12 @@ internal interface RoomKeysApi {
* @param keyBackupData the data to send * @param keyBackupData the data to send
*/ */
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}") @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}")
suspend fun storeRoomSessionData(@Path("roomId") roomId: String, suspend fun storeRoomSessionData(
@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String, @Path("sessionId") sessionId: String,
@Query("version") version: String, @Query("version") version: String,
@Body keyBackupData: KeyBackupData): BackupKeysResult @Body keyBackupData: KeyBackupData
): BackupKeysResult
/** /**
* Store several keys for the given room, using the given backup version. * Store several keys for the given room, using the given backup version.
@ -106,9 +110,11 @@ internal interface RoomKeysApi {
* @param roomKeysBackupData the data to send * @param roomKeysBackupData the data to send
*/ */
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}") @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}")
suspend fun storeRoomSessionsData(@Path("roomId") roomId: String, suspend fun storeRoomSessionsData(
@Path("roomId") roomId: String,
@Query("version") version: String, @Query("version") version: String,
@Body roomKeysBackupData: RoomKeysBackupData): BackupKeysResult @Body roomKeysBackupData: RoomKeysBackupData
): BackupKeysResult
/** /**
* Store several keys, using the given backup version. * Store several keys, using the given backup version.
@ -117,8 +123,10 @@ internal interface RoomKeysApi {
* @param keysBackupData the data to send * @param keysBackupData the data to send
*/ */
@PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys") @PUT(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys")
suspend fun storeSessionsData(@Query("version") version: String, suspend fun storeSessionsData(
@Body keysBackupData: KeysBackupData): BackupKeysResult @Query("version") version: String,
@Body keysBackupData: KeysBackupData
): BackupKeysResult
/* ========================================================================================== /* ==========================================================================================
* Retrieving keys * Retrieving keys
@ -132,9 +140,11 @@ internal interface RoomKeysApi {
* @param version the version of the backup, or empty String to retrieve the last version * @param version the version of the backup, or empty String to retrieve the last version
*/ */
@GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}") @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}")
suspend fun getRoomSessionData(@Path("roomId") roomId: String, suspend fun getRoomSessionData(
@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String, @Path("sessionId") sessionId: String,
@Query("version") version: String): KeyBackupData @Query("version") version: String
): KeyBackupData
/** /**
* Retrieve all the keys for the given room from the backup. * Retrieve all the keys for the given room from the backup.
@ -143,8 +153,10 @@ internal interface RoomKeysApi {
* @param version the version of the backup, or empty String to retrieve the last version * @param version the version of the backup, or empty String to retrieve the last version
*/ */
@GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}") @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}")
suspend fun getRoomSessionsData(@Path("roomId") roomId: String, suspend fun getRoomSessionsData(
@Query("version") version: String): RoomKeysBackupData @Path("roomId") roomId: String,
@Query("version") version: String
): RoomKeysBackupData
/** /**
* Retrieve all the keys from the backup. * Retrieve all the keys from the backup.
@ -162,16 +174,20 @@ internal interface RoomKeysApi {
* Deletes keys from the backup. * Deletes keys from the backup.
*/ */
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}") @DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}/{sessionId}")
suspend fun deleteRoomSessionData(@Path("roomId") roomId: String, suspend fun deleteRoomSessionData(
@Path("roomId") roomId: String,
@Path("sessionId") sessionId: String, @Path("sessionId") sessionId: String,
@Query("version") version: String) @Query("version") version: String
)
/** /**
* Deletes keys from the backup. * Deletes keys from the backup.
*/ */
@DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}") @DELETE(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/keys/{roomId}")
suspend fun deleteRoomSessionsData(@Path("roomId") roomId: String, suspend fun deleteRoomSessionsData(
@Query("version") version: String) @Path("roomId") roomId: String,
@Query("version") version: String
)
/** /**
* Deletes keys from the backup. * Deletes keys from the backup.

View File

@ -69,12 +69,14 @@ internal data class KeyVerificationAccept(
override fun toSendToDeviceObject() = this override fun toSendToDeviceObject() = this
companion object : VerificationInfoAcceptFactory { companion object : VerificationInfoAcceptFactory {
override fun create(tid: String, override fun create(
tid: String,
keyAgreementProtocol: String, keyAgreementProtocol: String,
hash: String, hash: String,
commitment: String, commitment: String,
messageAuthenticationCode: String, messageAuthenticationCode: String,
shortAuthenticationStrings: List<String>): VerificationInfoAccept { shortAuthenticationStrings: List<String>
): VerificationInfoAccept {
return KeyVerificationAccept( return KeyVerificationAccept(
transactionId = tid, transactionId = tid,
keyAgreementProtocol = keyAgreementProtocol, keyAgreementProtocol = keyAgreementProtocol,

View File

@ -62,10 +62,12 @@ internal class DefaultSharedSecretStorageService @Inject constructor(
private val cryptoCoroutineScope: CoroutineScope private val cryptoCoroutineScope: CoroutineScope
) : SharedSecretStorageService { ) : SharedSecretStorageService {
override suspend fun generateKey(keyId: String, override suspend fun generateKey(
keyId: String,
key: SsssKeySpec?, key: SsssKeySpec?,
keyName: String, keyName: String,
keySigner: KeySigner?): SsssKeyCreationInfo { keySigner: KeySigner?
): SsssKeyCreationInfo {
return withContext(cryptoCoroutineScope.coroutineContext + coroutineDispatchers.computation) { return withContext(cryptoCoroutineScope.coroutineContext + coroutineDispatchers.computation) {
val bytes = (key as? RawBytesKeySpec)?.privateKey val bytes = (key as? RawBytesKeySpec)?.privateKey
?: ByteArray(32).also { ?: ByteArray(32).also {
@ -94,11 +96,13 @@ internal class DefaultSharedSecretStorageService @Inject constructor(
} }
} }
override suspend fun generateKeyWithPassphrase(keyId: String, override suspend fun generateKeyWithPassphrase(
keyId: String,
keyName: String, keyName: String,
passphrase: String, passphrase: String,
keySigner: KeySigner, keySigner: KeySigner,
progressListener: ProgressListener?): SsssKeyCreationInfo { progressListener: ProgressListener?
): SsssKeyCreationInfo {
return withContext(cryptoCoroutineScope.coroutineContext + coroutineDispatchers.computation) { return withContext(cryptoCoroutineScope.coroutineContext + coroutineDispatchers.computation) {
val privatePart = generatePrivateKeyWithPassword(passphrase, progressListener) val privatePart = generatePrivateKeyWithPassword(passphrase, progressListener)

View File

@ -192,10 +192,12 @@ internal interface IMXCryptoStore {
*/ */
fun storeUserDevices(userId: String, devices: Map<String, CryptoDeviceInfo>?) fun storeUserDevices(userId: String, devices: Map<String, CryptoDeviceInfo>?)
fun storeUserCrossSigningKeys(userId: String, fun storeUserCrossSigningKeys(
userId: String,
masterKey: CryptoCrossSigningKey?, masterKey: CryptoCrossSigningKey?,
selfSigningKey: CryptoCrossSigningKey?, selfSigningKey: CryptoCrossSigningKey?,
userSigningKey: CryptoCrossSigningKey?) userSigningKey: CryptoCrossSigningKey?
)
/** /**
* Retrieve the known devices for a user. * Retrieve the known devices for a user.
@ -392,7 +394,8 @@ internal interface IMXCryptoStore {
algorithm: String, algorithm: String,
senderKey: String, senderKey: String,
fromDevice: String?, fromDevice: String?,
event: Event) event: Event
)
fun deleteOutgoingRoomKeyRequest(requestId: String) fun deleteOutgoingRoomKeyRequest(requestId: String)
fun deleteOutgoingRoomKeyRequestInState(state: OutgoingRoomKeyRequestState) fun deleteOutgoingRoomKeyRequestInState(state: OutgoingRoomKeyRequestState)
@ -479,8 +482,10 @@ internal interface IMXCryptoStore {
fun addWithHeldMegolmSession(withHeldContent: RoomKeyWithHeldContent) fun addWithHeldMegolmSession(withHeldContent: RoomKeyWithHeldContent)
fun getWithHeldMegolmSession(roomId: String, sessionId: String): RoomKeyWithHeldContent? fun getWithHeldMegolmSession(roomId: String, sessionId: String): RoomKeyWithHeldContent?
fun markedSessionAsShared(roomId: String?, sessionId: String, userId: String, deviceId: String, fun markedSessionAsShared(
deviceIdentityKey: String, chainIndex: Int) roomId: String?, sessionId: String, userId: String, deviceId: String,
deviceIdentityKey: String, chainIndex: Int
)
/** /**
* Query for information on this session sharing history. * Query for information on this session sharing history.

View File

@ -322,10 +322,12 @@ internal class RealmCryptoStore @Inject constructor(
} }
} }
override fun storeUserCrossSigningKeys(userId: String, override fun storeUserCrossSigningKeys(
userId: String,
masterKey: CryptoCrossSigningKey?, masterKey: CryptoCrossSigningKey?,
selfSigningKey: CryptoCrossSigningKey?, selfSigningKey: CryptoCrossSigningKey?,
userSigningKey: CryptoCrossSigningKey?) { userSigningKey: CryptoCrossSigningKey?
) {
doRealmTransaction(realmConfiguration) { realm -> doRealmTransaction(realmConfiguration) { realm ->
UserEntity.getOrCreate(realm, userId) UserEntity.getOrCreate(realm, userId)
.let { userEntity -> .let { userEntity ->
@ -1154,9 +1156,11 @@ internal class RealmCryptoStore @Inject constructor(
} }
} }
override fun getOrAddOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody, override fun getOrAddOutgoingRoomKeyRequest(
requestBody: RoomKeyRequestBody,
recipients: Map<String, List<String>>, recipients: Map<String, List<String>>,
fromIndex: Int): OutgoingKeyRequest { fromIndex: Int
): OutgoingKeyRequest {
// Insert the request and return the one passed in parameter // Insert the request and return the one passed in parameter
lateinit var request: OutgoingKeyRequest lateinit var request: OutgoingKeyRequest
doRealmTransaction(realmConfiguration) { realm -> doRealmTransaction(realmConfiguration) { realm ->
@ -1220,12 +1224,14 @@ internal class RealmCryptoStore @Inject constructor(
} }
} }
override fun updateOutgoingRoomKeyReply(roomId: String, override fun updateOutgoingRoomKeyReply(
roomId: String,
sessionId: String, sessionId: String,
algorithm: String, algorithm: String,
senderKey: String, senderKey: String,
fromDevice: String?, fromDevice: String?,
event: Event) { event: Event
) {
doRealmTransaction(realmConfiguration) { realm -> doRealmTransaction(realmConfiguration) { realm ->
realm.where<OutgoingKeyRequestEntity>() realm.where<OutgoingKeyRequestEntity>()
.equalTo(OutgoingKeyRequestEntityFields.ROOM_ID, roomId) .equalTo(OutgoingKeyRequestEntityFields.ROOM_ID, roomId)
@ -1266,7 +1272,8 @@ internal class RealmCryptoStore @Inject constructor(
senderKey: String, senderKey: String,
algorithm: String, algorithm: String,
fromUser: String, fromUser: String,
fromDevice: String) { fromDevice: String
) {
monarchy.writeAsync { realm -> monarchy.writeAsync { realm ->
val now = clock.epochMillis() val now = clock.epochMillis()
realm.createObject<AuditTrailEntity>().apply { realm.createObject<AuditTrailEntity>().apply {
@ -1288,13 +1295,15 @@ internal class RealmCryptoStore @Inject constructor(
} }
} }
override fun saveWithheldAuditTrail(roomId: String, override fun saveWithheldAuditTrail(
roomId: String,
sessionId: String, sessionId: String,
senderKey: String, senderKey: String,
algorithm: String, algorithm: String,
code: WithHeldCode, code: WithHeldCode,
userId: String, userId: String,
deviceId: String) { deviceId: String
) {
monarchy.writeAsync { realm -> monarchy.writeAsync { realm ->
val now = clock.epochMillis() val now = clock.epochMillis()
realm.createObject<AuditTrailEntity>().apply { realm.createObject<AuditTrailEntity>().apply {
@ -1316,27 +1325,32 @@ internal class RealmCryptoStore @Inject constructor(
} }
} }
override fun saveForwardKeyAuditTrail(roomId: String, override fun saveForwardKeyAuditTrail(
roomId: String,
sessionId: String, sessionId: String,
senderKey: String, senderKey: String,
algorithm: String, algorithm: String,
userId: String, userId: String,
deviceId: String, deviceId: String,
chainIndex: Long?) { chainIndex: Long?
) {
saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, false) saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, false)
} }
override fun saveIncomingForwardKeyAuditTrail(roomId: String, override fun saveIncomingForwardKeyAuditTrail(
roomId: String,
sessionId: String, sessionId: String,
senderKey: String, senderKey: String,
algorithm: String, algorithm: String,
userId: String, userId: String,
deviceId: String, deviceId: String,
chainIndex: Long?) { chainIndex: Long?
) {
saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, true) saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, true)
} }
private fun saveForwardKeyTrail(roomId: String, private fun saveForwardKeyTrail(
roomId: String,
sessionId: String, sessionId: String,
senderKey: String, senderKey: String,
algorithm: String, algorithm: String,
@ -1617,12 +1631,14 @@ internal class RealmCryptoStore @Inject constructor(
} }
} }
override fun markedSessionAsShared(roomId: String?, override fun markedSessionAsShared(
roomId: String?,
sessionId: String, sessionId: String,
userId: String, userId: String,
deviceId: String, deviceId: String,
deviceIdentityKey: String, deviceIdentityKey: String,
chainIndex: Int) { chainIndex: Int
) {
doRealmTransaction(realmConfiguration) { realm -> doRealmTransaction(realmConfiguration) { realm ->
SharedSessionEntity.create( SharedSessionEntity.create(
realm = realm, realm = realm,

View File

@ -33,7 +33,8 @@ internal open class OlmInboundGroupSessionEntity(
// olmInboundGroupSessionData contains Json // olmInboundGroupSessionData contains Json
var olmInboundGroupSessionData: String? = null, var olmInboundGroupSessionData: String? = null,
// Indicate if the key has been backed up to the homeserver // Indicate if the key has been backed up to the homeserver
var backedUp: Boolean = false) : var backedUp: Boolean = false
) :
RealmObject() { RealmObject() {
fun getInboundGroupSession(): OlmInboundGroupSessionWrapper2? { fun getInboundGroupSession(): OlmInboundGroupSessionWrapper2? {

View File

@ -25,11 +25,13 @@ import org.matrix.olm.OlmSession
internal fun OlmSessionEntity.Companion.createPrimaryKey(sessionId: String, deviceKey: String) = "$sessionId|$deviceKey" internal fun OlmSessionEntity.Companion.createPrimaryKey(sessionId: String, deviceKey: String) = "$sessionId|$deviceKey"
// olmSessionData is a serialized OlmSession // olmSessionData is a serialized OlmSession
internal open class OlmSessionEntity(@PrimaryKey var primaryKey: String = "", internal open class OlmSessionEntity(
@PrimaryKey var primaryKey: String = "",
var sessionId: String? = null, var sessionId: String? = null,
var deviceKey: String? = null, var deviceKey: String? = null,
var olmSessionData: String? = null, var olmSessionData: String? = null,
var lastReceivedMessageTs: Long = 0) : var lastReceivedMessageTs: Long = 0
) :
RealmObject() { RealmObject() {
fun getOlmSession(): OlmSession? { fun getOlmSession(): OlmSession? {

View File

@ -24,12 +24,14 @@ import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntity import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntity
import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntityFields import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntityFields
internal fun SharedSessionEntity.Companion.get(realm: Realm, internal fun SharedSessionEntity.Companion.get(
realm: Realm,
roomId: String?, roomId: String?,
sessionId: String, sessionId: String,
userId: String, userId: String,
deviceId: String, deviceId: String,
deviceIdentityKey: String?): SharedSessionEntity? { deviceIdentityKey: String?
): SharedSessionEntity? {
return realm.where<SharedSessionEntity>() return realm.where<SharedSessionEntity>()
.equalTo(SharedSessionEntityFields.ROOM_ID, roomId) .equalTo(SharedSessionEntityFields.ROOM_ID, roomId)
.equalTo(SharedSessionEntityFields.SESSION_ID, sessionId) .equalTo(SharedSessionEntityFields.SESSION_ID, sessionId)
@ -48,12 +50,14 @@ internal fun SharedSessionEntity.Companion.get(realm: Realm, roomId: String?, se
.findAll() .findAll()
} }
internal fun SharedSessionEntity.Companion.create(realm: Realm, roomId: String?, internal fun SharedSessionEntity.Companion.create(
realm: Realm, roomId: String?,
sessionId: String, sessionId: String,
userId: String, userId: String,
deviceId: String, deviceId: String,
deviceIdentityKey: String, deviceIdentityKey: String,
chainIndex: Int): SharedSessionEntity { chainIndex: Int
): SharedSessionEntity {
return realm.createObject<SharedSessionEntity>().apply { return realm.createObject<SharedSessionEntity>().apply {
this.roomId = roomId this.roomId = roomId
this.algorithm = MXCRYPTO_ALGORITHM_MEGOLM this.algorithm = MXCRYPTO_ALGORITHM_MEGOLM

Some files were not shown because too many files have changed in this diff Show More