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

File diff suppressed because it is too large Load Diff

View File

@ -44,7 +44,7 @@ class SwipeToDismissHandler(
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
MotionEvent.ACTION_DOWN -> {
if (swipeView.hitRect.contains(event.x.toInt(), event.y.toInt())) {
isTracking = true
}
@ -58,7 +58,7 @@ class SwipeToDismissHandler(
}
return true
}
MotionEvent.ACTION_MOVE -> {
MotionEvent.ACTION_MOVE -> {
if (isTracking) {
val translationY = event.y - startY
swipeView.translationY = translationY
@ -66,7 +66,7 @@ class SwipeToDismissHandler(
}
return true
}
else -> {
else -> {
return false
}
}

View File

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

View File

@ -18,8 +18,10 @@ package org.matrix.android.sdk.common
import org.matrix.android.sdk.api.session.Session
data class CryptoTestData(val roomId: String,
val sessions: List<Session>) {
data class CryptoTestData(
val roomId: String,
val sessions: List<Session>
) {
val firstSession: Session
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
*/
class SimpleRule(match: String,
private val code: Int = HttpsURLConnection.HTTP_OK,
private val body: String = "{}") : Rule(match) {
class SimpleRule(
match: String,
private val code: Int = HttpsURLConnection.HTTP_OK,
private val body: String = "{}"
) : Rule(match) {
override fun process(originalRequest: Request): Response? {
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 <T>
*/
open class TestMatrixCallback<T>(private val countDownLatch: CountDownLatch,
private val onlySuccessful: Boolean = true) : MatrixCallback<T> {
open class TestMatrixCallback<T>(
private val countDownLatch: CountDownLatch,
private val onlySuccessful: Boolean = true
) : MatrixCallback<T> {
@CallSuper
override fun onSuccess(data: T) {

View File

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

View File

@ -83,7 +83,8 @@ class ExportEncryptionTest {
@Test
fun checkExportDecrypt1() {
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"
var decodedString: String? = null
@ -103,7 +104,8 @@ class ExportEncryptionTest {
@Test
fun checkExportDecrypt2() {
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"
var decodedString: String? = null
@ -123,7 +125,8 @@ class ExportEncryptionTest {
@Test
fun checkExportDecrypt3() {
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"
var decodedString: String? = null
@ -202,7 +205,8 @@ class ExportEncryptionTest {
@Test
fun checkExportEncrypt4() {
val password = "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword"
val password =
"passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpasswordpassword"
val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically"
var decodedString: String? = null

View File

@ -442,7 +442,7 @@ class KeyShareTests : InstrumentedTest {
// Should get a reply from bob and not from alice
commonTestHelper.waitWithLatch { latch ->
commonTestHelper.retryPeriodicallyWithLatch(latch) {
// Log.d("#TEST", "outgoing key requests :${aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().joinToString { it.sessionId ?: "?" }}")
// Log.d("#TEST", "outgoing key requests :${aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().joinToString { it.sessionId ?: "?" }}")
val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession }
val bobReply = outgoing?.results?.firstOrNull { it.userId == bobSession.myUserId }
val result = bobReply?.result

View File

@ -33,7 +33,8 @@ import java.util.concurrent.CountDownLatch
internal class KeysBackupTestHelper(
private val testHelper: CommonTestHelper,
private val cryptoTestHelper: CryptoTestHelper) {
private val cryptoTestHelper: CryptoTestHelper
) {
fun waitForKeybackUpBatching() {
Thread.sleep(400)
@ -96,8 +97,10 @@ internal class KeysBackupTestHelper(
)
}
fun prepareAndCreateKeysBackupData(keysBackup: KeysBackupService,
password: String? = null): PrepareKeysBackupDataResult {
fun prepareAndCreateKeysBackupData(
keysBackup: KeysBackupService,
password: String? = null
): PrepareKeysBackupDataResult {
val stateObserver = StateObserver(keysBackup)
val megolmBackupCreationInfo = testHelper.doSync<MegolmBackupCreationInfo> {
@ -169,9 +172,11 @@ internal class KeysBackupTestHelper(
* - The new device must have the same count of megolm keys
* - Alice must have the same keys on both devices
*/
fun checkRestoreSuccess(testData: KeysBackupScenarioData,
total: Int,
imported: Int) {
fun checkRestoreSuccess(
testData: KeysBackupScenarioData,
total: Int,
imported: Int
) {
// - Imported keys number must be correct
Assert.assertEquals(testData.aliceKeys.size, total)
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
data class PrepareKeysBackupDataResult(val megolmBackupCreationInfo: MegolmBackupCreationInfo,
val version: String)
data class PrepareKeysBackupDataResult(
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
* It checks all state transitions and detected forbidden transition
*/
internal class StateObserver(private val keysBackup: KeysBackupService,
private val latch: CountDownLatch? = null,
private val expectedStateChange: Int = -1) : KeysBackupStateListener {
internal class StateObserver(
private val keysBackup: KeysBackupService,
private val latch: CountDownLatch? = null,
private val expectedStateChange: Int = -1
) : KeysBackupStateListener {
private val allowedStateTransitions = listOf(
KeysBackupState.BackingUp to KeysBackupState.ReadyToBackUp,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -41,11 +41,12 @@ object RoomDataHelper {
}
}
private fun createFakeEvent(type: String,
content: Content? = null,
prevContent: Content? = null,
sender: String = FAKE_TEST_SENDER,
stateKey: String? = null
private fun createFakeEvent(
type: String,
content: Content? = null,
prevContent: Content? = null,
sender: String = FAKE_TEST_SENDER,
stateKey: String? = null
): Event {
return Event(
type = type,

View File

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

View File

@ -93,14 +93,18 @@ interface AuthenticationService {
/**
* Create a session after a SSO successful login.
*/
suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig,
credentials: Credentials): Session
suspend fun createSessionFromSso(
homeServerConnectionConfig: HomeServerConnectionConfig,
credentials: Credentials
): Session
/**
* Perform a wellknown request, using the domain from the matrixId.
*/
suspend fun getWellKnownData(matrixId: String,
homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult
suspend fun getWellKnownData(
matrixId: String,
homeServerConnectionConfig: HomeServerConnectionConfig?
): WellknownResult
/**
* Authenticate with a matrixId and a password.
@ -111,9 +115,11 @@ interface AuthenticationService {
* @param initialDeviceName the initial device name
* @param deviceId the device id, optional. If not provided or null, the server will generate one.
*/
suspend fun directAuthentication(homeServerConnectionConfig: HomeServerConnectionConfig,
matrixId: String,
password: String,
initialDeviceName: String,
deviceId: String? = null): Session
suspend fun directAuthentication(
homeServerConnectionConfig: HomeServerConnectionConfig,
matrixId: String,
password: String,
initialDeviceName: String,
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 defaultLanguage the default language to use if the user language is not found for a policy in registrationFlowResponse
*/
fun TermPolicies.toLocalizedLoginTerms(userLanguage: String,
defaultLanguage: String = "en"): List<LocalizedFlowDataLoginTerms> {
fun TermPolicies.toLocalizedLoginTerms(
userLanguage: String,
defaultLanguage: String = "en"
): List<LocalizedFlowDataLoginTerms> {
val result = ArrayList<LocalizedFlowDataLoginTerms>()
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.
* @return a [Session] if the login is successful
*/
suspend fun login(login: String,
password: String,
initialDeviceName: String,
deviceId: String? = null): Session
suspend fun login(
login: String,
password: String,
initialDeviceName: String,
deviceId: String? = null
): Session
/**
* 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 newPassword the desired new password
*/
suspend fun resetPassword(email: String,
newPassword: String)
suspend fun resetPassword(
email: String,
newPassword: String
)
/**
* 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 initialDeviceDisplayName the device display name
*/
suspend fun createAccount(userName: String?,
password: String?,
initialDeviceDisplayName: String?): RegistrationResult
suspend fun createAccount(
userName: String?,
password: String?,
initialDeviceDisplayName: String?
): RegistrationResult
/**
* 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,
* 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,
val identityServerUrl: String?,
val wellKnown: WellKnown) : WellknownResult()
data class Prompt(
val homeServerUrl: String,
val identityServerUrl: String?,
val wellKnown: WellKnown
) : WellknownResult()
/**
* 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 newPassword New password
*/
suspend fun changePassword(password: String,
newPassword: String)
suspend fun changePassword(
password: String,
newPassword: String
)
/**
* Deactivate the account.
@ -46,6 +48,8 @@ interface AccountService {
* an incomplete view of conversations
* @param userInteractiveAuthInterceptor see [UserInteractiveAuthInterceptor]
*/
suspend fun deactivateAccount(eraseAllData: Boolean,
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor)
suspend fun deactivateAccount(
eraseAllData: Boolean,
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor
)
}

View File

@ -91,10 +91,12 @@ interface MxCall : MxCallDetail {
* 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
*/
suspend fun transfer(targetUserId: String,
targetRoomId: String?,
createCallId: String?,
awaitCallId: String?)
suspend fun transfer(
targetUserId: String,
targetRoomId: String?,
createCallId: String?,
awaitCallId: String?
)
fun addListener(listener: StateListener)
fun removeListener(listener: StateListener)

View File

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

View File

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

View File

@ -26,7 +26,7 @@ data class RequestReply(
)
sealed class RequestResult {
data class Success(val chainIndex: Int) : RequestResult()
data class Success(val chainIndex: Int) : RequestResult()
data class Failure(val code: WithHeldCode) : RequestResult()
}

View File

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

View File

@ -36,8 +36,10 @@ interface KeysBackupService {
* @param keysBackupCreationInfo the info object from [prepareKeysBackupVersion].
* @param callback Asynchronous callback
*/
fun createKeysBackupVersion(keysBackupCreationInfo: MegolmBackupCreationInfo,
callback: MatrixCallback<KeysVersion>)
fun createKeysBackupVersion(
keysBackupCreationInfo: MegolmBackupCreationInfo,
callback: MatrixCallback<KeysVersion>
)
/**
* 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 callback the main callback
*/
fun backupAllGroupSessions(progressListener: ProgressListener?,
callback: MatrixCallback<Unit>?)
fun backupAllGroupSessions(
progressListener: ProgressListener?,
callback: MatrixCallback<Unit>?
)
/**
* Check trust on a key backup version.
@ -64,8 +68,10 @@ interface KeysBackupService {
* @param keysBackupVersion the backup version to check.
* @param callback block called when the operations completes.
*/
fun getKeysBackupTrust(keysBackupVersion: KeysVersionResult,
callback: MatrixCallback<KeysBackupVersionTrust>)
fun getKeysBackupTrust(
keysBackupVersion: KeysVersionResult,
callback: MatrixCallback<KeysBackupVersionTrust>
)
/**
* Return the current progress of the backup.
@ -79,8 +85,10 @@ interface KeysBackupService {
* @param version the backup version
* @param callback
*/
fun getVersion(version: String,
callback: MatrixCallback<KeysVersionResult?>)
fun getVersion(
version: String,
callback: MatrixCallback<KeysVersionResult?>
)
/**
* 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 callback Asynchronous callback
*/
fun prepareKeysBackupVersion(password: String?,
progressListener: ProgressListener?,
callback: MatrixCallback<MegolmBackupCreationInfo>)
fun prepareKeysBackupVersion(
password: String?,
progressListener: ProgressListener?,
callback: MatrixCallback<MegolmBackupCreationInfo>
)
/**
* 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 callback Asynchronous callback
*/
fun deleteBackup(version: String,
callback: MatrixCallback<Unit>?)
fun deleteBackup(
version: String,
callback: MatrixCallback<Unit>?
)
/**
* 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 callback block called when the operations completes.
*/
fun trustKeysBackupVersion(keysBackupVersion: KeysVersionResult,
trust: Boolean,
callback: MatrixCallback<Unit>)
fun trustKeysBackupVersion(
keysBackupVersion: KeysVersionResult,
trust: Boolean,
callback: MatrixCallback<Unit>
)
/**
* 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 callback block called when the operations completes.
*/
fun trustKeysBackupVersionWithRecoveryKey(keysBackupVersion: KeysVersionResult,
recoveryKey: String,
callback: MatrixCallback<Unit>)
fun trustKeysBackupVersionWithRecoveryKey(
keysBackupVersion: KeysVersionResult,
recoveryKey: String,
callback: MatrixCallback<Unit>
)
/**
* 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 callback block called when the operations completes.
*/
fun trustKeysBackupVersionWithPassphrase(keysBackupVersion: KeysVersionResult,
password: String,
callback: MatrixCallback<Unit>)
fun trustKeysBackupVersionWithPassphrase(
keysBackupVersion: KeysVersionResult,
password: String,
callback: MatrixCallback<Unit>
)
fun onSecretKeyGossip(secret: String)
@ -180,11 +198,13 @@ interface KeysBackupService {
* @param stepProgressListener the step progress listener
* @param callback Callback. It provides the number of found keys and the number of successfully imported keys.
*/
fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult,
recoveryKey: String, roomId: String?,
sessionId: String?,
stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>)
fun restoreKeysWithRecoveryKey(
keysVersionResult: KeysVersionResult,
recoveryKey: String, roomId: String?,
sessionId: String?,
stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>
)
/**
* 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 callback Callback. It provides the number of found keys and the number of successfully imported keys.
*/
fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult,
password: String,
roomId: String?,
sessionId: String?,
stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>)
fun restoreKeyBackupWithPassword(
keysBackupVersion: KeysVersionResult,
password: String,
roomId: String?,
sessionId: String?,
stepProgressListener: StepProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>
)
val keysBackupVersion: KeysVersionResult?
val currentBackupVersion: String?
@ -215,8 +237,10 @@ interface KeysBackupService {
fun isValidRecoveryKeyForCurrentVersion(recoveryKey: String, callback: MatrixCallback<Boolean>)
fun computePrivateKey(passphrase: String,
privateKeySalt: String,
privateKeyIterations: Int,
progressListener: ProgressListener): ByteArray
fun computePrivateKey(
passphrase: String,
privateKeySalt: String,
privateKeyIterations: Int,
progressListener: ProgressListener
): ByteArray
}

View File

@ -40,7 +40,8 @@ sealed class KeysBackupVersionTrustSignature {
/**
* Flag to indicate the signature from this device is valid.
*/
val valid: Boolean) : KeysBackupVersionTrustSignature()
val valid: Boolean
) : KeysBackupVersionTrustSignature()
data class UserSignature(
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.StringRes
data class EmojiRepresentation(val emoji: String,
@StringRes val nameResId: Int,
@DrawableRes val drawableRes: Int? = null
data class EmojiRepresentation(
val emoji: String,
@StringRes val nameResId: Int,
@DrawableRes val drawableRes: Int? = null
)

View File

@ -46,54 +46,68 @@ interface VerificationService {
fun getExistingVerificationRequestInRoom(roomId: String, tid: String?): PendingVerificationRequest?
fun beginKeyVerification(method: VerificationMethod,
otherUserId: String,
otherDeviceId: String,
transactionId: String?): String?
fun beginKeyVerification(
method: VerificationMethod,
otherUserId: String,
otherDeviceId: String,
transactionId: String?
): String?
/**
* Request key verification with another user via room events (instead of the to-device API).
*/
fun requestKeyVerificationInDMs(methods: List<VerificationMethod>,
otherUserId: String,
roomId: String,
localId: String? = LocalEcho.createLocalEchoId()): PendingVerificationRequest
fun requestKeyVerificationInDMs(
methods: List<VerificationMethod>,
otherUserId: String,
roomId: String,
localId: String? = LocalEcho.createLocalEchoId()
): PendingVerificationRequest
fun cancelVerificationRequest(request: PendingVerificationRequest)
/**
* Request a key verification from another user using toDevice events.
*/
fun requestKeyVerification(methods: List<VerificationMethod>,
otherUserId: String,
otherDevices: List<String>?): PendingVerificationRequest
fun requestKeyVerification(
methods: List<VerificationMethod>,
otherUserId: String,
otherDevices: List<String>?
): PendingVerificationRequest
fun declineVerificationRequestInDMs(otherUserId: String,
transactionId: String,
roomId: String)
fun declineVerificationRequestInDMs(
otherUserId: String,
transactionId: String,
roomId: String
)
// Only SAS method is supported for the moment
// TODO Parameter otherDeviceId should be removed in this case
fun beginKeyVerificationInDMs(method: VerificationMethod,
transactionId: String,
roomId: String,
otherUserId: String,
otherDeviceId: String): String
fun beginKeyVerificationInDMs(
method: VerificationMethod,
transactionId: String,
roomId: String,
otherUserId: String,
otherDeviceId: String
): String
/**
* Returns false if the request is unknown.
*/
fun readyPendingVerificationInDMs(methods: List<VerificationMethod>,
otherUserId: String,
roomId: String,
transactionId: String): Boolean
fun readyPendingVerificationInDMs(
methods: List<VerificationMethod>,
otherUserId: String,
roomId: String,
transactionId: String
): Boolean
/**
* Returns false if the request is unknown.
*/
fun readyPendingVerification(methods: List<VerificationMethod>,
otherUserId: String,
transactionId: String): Boolean
fun readyPendingVerification(
methods: List<VerificationMethod>,
otherUserId: String,
transactionId: String
): Boolean
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
* The result will not be stored into cache
*/
suspend fun getEvent(roomId: String,
eventId: String): Event
suspend fun getEvent(
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.
* 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,
mimeType: String?,
url: String?,
elementToDecrypt: ElementToDecrypt?): File
suspend fun downloadFile(
fileName: String,
mimeType: String?,
url: String?,
elementToDecrypt: ElementToDecrypt?
): File
suspend fun downloadFile(messageContent: MessageWithAttachmentContent): File =
downloadFile(
@ -57,10 +59,11 @@ interface FileService {
elementToDecrypt = messageContent.encryptedFileInfo?.toElementToDecrypt()
)
fun isFileInCache(mxcUrl: String?,
fileName: String,
mimeType: String?,
elementToDecrypt: ElementToDecrypt?
fun isFileInCache(
mxcUrl: String?,
fileName: String,
mimeType: String?,
elementToDecrypt: ElementToDecrypt?
): Boolean
fun isFileInCache(messageContent: MessageWithAttachmentContent) =
@ -75,10 +78,12 @@ interface FileService {
* 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).
*/
fun getTemporarySharableURI(mxcUrl: String?,
fileName: String,
mimeType: String?,
elementToDecrypt: ElementToDecrypt?): Uri?
fun getTemporarySharableURI(
mxcUrl: String?,
fileName: String,
mimeType: String?,
elementToDecrypt: ElementToDecrypt?
): Uri?
fun getTemporarySharableURI(messageContent: MessageWithAttachmentContent): Uri? =
getTemporarySharableURI(
@ -92,10 +97,12 @@ interface FileService {
* Get information on the given file.
* Mimetype should be the same one as passed to downloadFile (limitation for now)
*/
fun fileState(mxcUrl: String?,
fileName: String,
mimeType: String?,
elementToDecrypt: ElementToDecrypt?): FileState
fun fileState(
mxcUrl: String?,
fileName: String,
mimeType: String?,
elementToDecrypt: ElementToDecrypt?
): FileState
fun fileState(messageContent: MessageWithAttachmentContent): 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 callback the callback to use.
*/
class MatrixPermalinkSpan(private val url: String,
private val callback: Callback? = null) : ClickableSpan() {
class MatrixPermalinkSpan(
private val url: String,
private val callback: Callback? = null
) : ClickableSpan() {
interface Callback {
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.
*/
suspend fun finalizeAddingThreePid(threePid: ThreePid,
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor)
suspend fun finalizeAddingThreePid(
threePid: ThreePid,
userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor
)
/**
* 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.
* @throws [InvalidParameterException] if a parameter is not correct
*/
suspend fun addEmailPusher(email: String,
lang: String,
emailBranding: String,
appDisplayName: String,
deviceDisplayName: String,
append: Boolean = true)
suspend fun addEmailPusher(
email: String,
lang: String,
emailBranding: String,
appDisplayName: String,
deviceDisplayName: String,
append: Boolean = true
)
/**
* Directly ask the push gateway to send a push to this device.
@ -75,10 +77,12 @@ interface PushersService {
* @param pushkey the FCM token
* @param eventId the eventId which will be sent in the Push message. Use a fake eventId.
*/
suspend fun testPush(url: String,
appId: String,
pushkey: String,
eventId: String)
suspend fun testPush(
url: String,
appId: String,
pushkey: String,
eventId: String
)
/**
* 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
*/
interface ConditionResolver {
fun resolveEventMatchCondition(event: Event,
condition: EventMatchCondition): Boolean
fun resolveEventMatchCondition(
event: Event,
condition: EventMatchCondition
): Boolean
fun resolveRoomMemberCountCondition(event: Event,
condition: RoomMemberCountCondition): Boolean
fun resolveRoomMemberCountCondition(
event: Event,
condition: RoomMemberCountCondition
): Boolean
fun resolveSenderNotificationPermissionCondition(event: Event,
condition: SenderNotificationPermissionCondition): Boolean
fun resolveSenderNotificationPermissionCondition(
event: Event,
condition: SenderNotificationPermissionCondition
): Boolean
fun resolveContainsDisplayNameCondition(event: Event,
condition: ContainsDisplayNameCondition): Boolean
fun resolveContainsDisplayNameCondition(
event: Event,
condition: ContainsDisplayNameCondition
): Boolean
}

View File

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

View File

@ -28,8 +28,10 @@ interface RoomDirectoryService {
/**
* Get rooms from directory.
*/
suspend fun getPublicRooms(server: String?,
publicRoomsParams: PublicRoomsParams): PublicRoomsResponse
suspend fun getPublicRooms(
server: String?,
publicRoomsParams: PublicRoomsParams
): PublicRoomsResponse
/**
* 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 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,
reason: String? = null,
viaServers: List<String> = emptyList())
suspend fun joinRoom(
roomIdOrAlias: String,
reason: String? = null,
viaServers: List<String> = emptyList()
)
/**
* @param roomId the roomId of the room to join
@ -101,15 +103,19 @@ interface RoomService {
* Get a snapshot list of room summaries.
* @return the immutable list of [RoomSummary]
*/
fun getRoomSummaries(queryParams: RoomSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE): List<RoomSummary>
fun getRoomSummaries(
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.
* @return the [LiveData] of List[RoomSummary]
*/
fun getRoomSummariesLive(queryParams: RoomSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData<List<RoomSummary>>
fun getRoomSummariesLive(
queryParams: RoomSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY
): LiveData<List<RoomSummary>>
/**
* Get a snapshot list of Breadcrumbs.
@ -139,8 +145,10 @@ interface RoomService {
/**
* Resolve a room alias to a room ID.
*/
suspend fun getRoomIdByAlias(roomAlias: String,
searchOnServer: Boolean): Optional<RoomAliasDescription>
suspend fun getRoomIdByAlias(
roomAlias: String,
searchOnServer: Boolean
): Optional<RoomAliasDescription>
/**
* Delete a room alias.
@ -205,16 +213,20 @@ interface RoomService {
/**
* TODO Doc.
*/
fun getPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData<PagedList<RoomSummary>>
fun getPagedRoomSummariesLive(
queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY
): LiveData<PagedList<RoomSummary>>
/**
* TODO Doc.
*/
fun getFilteredPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): UpdatableLivePageResult
fun getFilteredPagedRoomSummariesLive(
queryParams: RoomSummaryQueryParams,
pagedListConfig: PagedList.Config = defaultPagedListConfig,
sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY
): UpdatableLivePageResult
/**
* Return a LiveData on the number of rooms.
@ -240,8 +252,10 @@ interface RoomService {
/**
* Returns all the children of this space, as LiveData.
*/
fun getFlattenRoomSummaryChildrenOfLive(spaceId: String?,
memberships: List<Membership> = Membership.activeMemberships()): LiveData<List<RoomSummary>>
fun getFlattenRoomSummaryChildrenOfLive(
spaceId: String?,
memberships: List<Membership> = Membership.activeMemberships()
): LiveData<List<RoomSummary>>
/**
* Refreshes the RoomSummary LatestPreviewContent for the given @param roomId.

View File

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

View File

@ -58,16 +58,20 @@ interface RelationService {
* @param targetEventId the id of the event being reacted
* @param reaction the reaction (preferably emoji)
*/
fun sendReaction(targetEventId: String,
reaction: String): Cancelable
fun sendReaction(
targetEventId: String,
reaction: String
): Cancelable
/**
* Undo a reaction (emoji) to the targetedEvent.
* @param targetEventId the id of the event being reacted
* @param reaction the reaction (preferably emoji)
*/
suspend fun undoReaction(targetEventId: String,
reaction: String): Cancelable
suspend fun undoReaction(
targetEventId: String,
reaction: String
): Cancelable
/**
* Edit a poll.
@ -76,10 +80,12 @@ interface RelationService {
* @param question The edited question
* @param options The edited options
*/
fun editPoll(targetEvent: TimelineEvent,
pollType: PollType,
question: String,
options: List<String>): Cancelable
fun editPoll(
targetEvent: TimelineEvent,
pollType: PollType,
question: String,
options: List<String>
): Cancelable
/**
* 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 compatibilityBodyText The text that will appear on clients that don't support yet edition
*/
fun editTextMessage(targetEvent: TimelineEvent,
msgType: String,
newBodyText: CharSequence,
newBodyAutoMarkdown: Boolean,
compatibilityBodyText: String = "* $newBodyText"): Cancelable
fun editTextMessage(
targetEvent: TimelineEvent,
msgType: String,
newBodyText: CharSequence,
newBodyAutoMarkdown: Boolean,
compatibilityBodyText: String = "* $newBodyText"
): Cancelable
/**
* 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 compatibilityBodyText The text that will appear on clients that don't support yet edition
*/
fun editReply(replyToEdit: TimelineEvent,
originalTimelineEvent: TimelineEvent,
newBodyText: String,
compatibilityBodyText: String = "* $newBodyText"): Cancelable
fun editReply(
replyToEdit: TimelineEvent,
originalTimelineEvent: TimelineEvent,
newBodyText: String,
compatibilityBodyText: String = "* $newBodyText"
): Cancelable
/**
* Get the edit history of the given event.
@ -127,11 +137,12 @@ interface RelationService {
* @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
*/
fun replyToMessage(eventReplied: TimelineEvent,
replyText: CharSequence,
autoMarkdown: Boolean = false,
showInThread: Boolean = false,
rootThreadEventId: String? = null
fun replyToMessage(
eventReplied: TimelineEvent,
replyText: CharSequence,
autoMarkdown: Boolean = false,
showInThread: Boolean = false,
rootThreadEventId: String? = null
): Cancelable?
/**
@ -159,10 +170,12 @@ interface RelationService {
* @param formattedText The formatted body using MessageType#FORMAT_MATRIX_HTML
* @param eventReplied the event referenced by the reply within a thread
*/
fun replyInThread(rootThreadEventId: String,
replyInThreadText: CharSequence,
msgType: String = MessageType.MSGTYPE_TEXT,
autoMarkdown: Boolean = false,
formattedText: String? = null,
eventReplied: TimelineEvent? = null): Cancelable?
fun replyInThread(
rootThreadEventId: String,
replyInThreadText: CharSequence,
msgType: String = MessageType.MSGTYPE_TEXT,
autoMarkdown: Boolean = false,
formattedText: String? = null,
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
* @return a [Cancelable]
*/
fun sendMedia(attachment: ContentAttachmentData,
compressBeforeSending: Boolean,
roomIds: Set<String>,
rootThreadEventId: String? = null): Cancelable
fun sendMedia(
attachment: ContentAttachmentData,
compressBeforeSending: Boolean,
roomIds: Set<String>,
rootThreadEventId: String? = null
): Cancelable
/**
* 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
* @return a [Cancelable]
*/
fun sendMedias(attachments: List<ContentAttachmentData>,
compressBeforeSending: Boolean,
roomIds: Set<String>,
rootThreadEventId: String? = null): Cancelable
fun sendMedias(
attachments: List<ContentAttachmentData>,
compressBeforeSending: Boolean,
roomIds: Set<String>,
rootThreadEventId: String? = null
): Cancelable
/**
* Send a poll to the room.

View File

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

View File

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

View File

@ -33,12 +33,14 @@ interface SearchService {
* @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.
*/
suspend fun search(searchTerm: String,
roomId: String,
nextBatch: String?,
orderByRecent: Boolean,
limit: Int,
beforeLimit: Int,
afterLimit: Int,
includeProfile: Boolean): SearchResult
suspend fun search(
searchTerm: String,
roomId: String,
nextBatch: String?,
orderByRecent: Boolean,
limit: Int,
beforeLimit: Int,
afterLimit: Int,
includeProfile: Boolean
): SearchResult
}

View File

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

View File

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

View File

@ -37,11 +37,13 @@ interface SpaceService {
/**
* Just a shortcut for space creation for ease of use.
*/
suspend fun createSpace(name: String,
topic: String?,
avatarUri: Uri?,
isPublic: Boolean,
roomAliasLocalPart: String? = null): String
suspend fun createSpace(
name: String,
topic: String?,
avatarUri: Uri?,
isPublic: Boolean,
roomAliasLocalPart: String? = null
): String
/**
* 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.
* @param knownStateList when paginating, pass back the m.space.child state events
*/
suspend fun querySpaceChildren(spaceId: String,
suggestedOnly: Boolean? = null,
limit: Int? = null,
from: String? = null,
knownStateList: List<Event>? = null): SpaceHierarchyData
suspend fun querySpaceChildren(
spaceId: String,
suggestedOnly: Boolean? = null,
limit: Int? = null,
from: String? = null,
knownStateList: List<Event>? = null
): SpaceHierarchyData
/**
* Get a live list of space summaries. This list is refreshed as soon as the data changes.
* @return the [LiveData] of List[SpaceSummary]
*/
fun getSpaceSummariesLive(queryParams: SpaceSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE): LiveData<List<RoomSummary>>
fun getSpaceSummariesLive(
queryParams: SpaceSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE
): LiveData<List<RoomSummary>>
fun getSpaceSummaries(spaceSummaryQueryParams: SpaceSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE): List<RoomSummary>
fun getSpaceSummaries(
spaceSummaryQueryParams: SpaceSummaryQueryParams,
sortOrder: RoomSortOrder = RoomSortOrder.NONE
): List<RoomSummary>
suspend fun joinSpace(spaceIdOrAlias: String,
reason: String? = null,
viaServers: List<String> = emptyList()): JoinSpaceResult
suspend fun joinSpace(
spaceIdOrAlias: String,
reason: String? = null,
viaServers: List<String> = emptyList()
): JoinSpaceResult
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.
*/
data class InitialSyncRequest(val requestDurationMs: Int,
val downloadDurationMs: Int,
val treatmentDurationMs: Int,
val nbOfJoinedRooms: Int) : StatisticEvent
data class InitialSyncRequest(
val requestDurationMs: Int,
val downloadDurationMs: Int,
val treatmentDurationMs: Int,
val nbOfJoinedRooms: Int
) : StatisticEvent
/**
* Incremental sync event.
*/
data class SyncTreatment(val durationMs: Int,
val afterPause: Boolean,
val nbOfJoinedRooms: Int) : StatisticEvent
data class SyncTreatment(
val durationMs: Int,
val afterPause: Boolean,
val nbOfJoinedRooms: Int
) : StatisticEvent
}

View File

@ -38,4 +38,5 @@ data class RoomSyncUnreadNotifications(
/**
* 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
) {
fun getLocalizedTerms(userLanguage: String,
defaultLanguage: String = "en"): List<LocalizedFlowDataLoginTerms> {
fun getLocalizedTerms(
userLanguage: String,
defaultLanguage: String = "en"
): List<LocalizedFlowDataLoginTerms> {
return policies?.map {
val tos = policies[it.key] as? Map<*, *> ?: return@map null
((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 agreeToTerms(serviceType: ServiceType,
baseUrl: String,
agreedUrls: List<String>,
token: String?)
suspend fun agreeToTerms(
serviceType: ServiceType,
baseUrl: String,
agreedUrls: List<String>,
token: String?
)
/**
* Get the homeserver terms, from the register API.

View File

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

View File

@ -27,8 +27,10 @@ import org.matrix.android.sdk.internal.session.SessionComponent
import javax.inject.Inject
@MatrixScope
internal class SessionManager @Inject constructor(private val matrixComponent: MatrixComponent,
private val sessionParamsStore: SessionParamsStore) {
internal class SessionManager @Inject constructor(
private val matrixComponent: MatrixComponent,
private val sessionParamsStore: SessionParamsStore
) {
// SessionId -> 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
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "register/{threePid}/requestToken")
suspend fun add3Pid(@Path("threePid") threePid: String,
@Body params: AddThreePidRegistrationParams): AddThreePidRegistrationResponse
suspend fun add3Pid(
@Path("threePid") threePid: String,
@Body params: AddThreePidRegistrationParams
): AddThreePidRegistrationResponse
/**
* Validate 3pid.
*/
@POST
suspend fun validate3Pid(@Url url: String,
@Body params: ValidationCodeBody): SuccessResult
suspend fun validate3Pid(
@Url url: String,
@Body params: ValidationCodeBody
): SuccessResult
/**
* Get the supported login flow.

View File

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

View File

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

View File

@ -31,7 +31,8 @@ internal data class PasswordLoginParams(
@Json(name = "password") val password: String,
@Json(name = "type") override val type: 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 {
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_PHONE = "phone"
fun userIdentifier(user: String,
password: String,
deviceDisplayName: String?,
deviceId: String?): PasswordLoginParams {
fun userIdentifier(
user: String,
password: String,
deviceDisplayName: String?,
deviceId: String?
): PasswordLoginParams {
return PasswordLoginParams(
identifier = mapOf(
IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_USER,
@ -63,11 +66,13 @@ internal data class PasswordLoginParams(
)
}
fun thirdPartyIdentifier(medium: String,
address: String,
password: String,
deviceDisplayName: String?,
deviceId: String?): PasswordLoginParams {
fun thirdPartyIdentifier(
medium: String,
address: String,
password: String,
deviceDisplayName: String?,
deviceId: String?
): PasswordLoginParams {
return PasswordLoginParams(
identifier = mapOf(
IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_THIRD_PARTY,
@ -81,11 +86,13 @@ internal data class PasswordLoginParams(
)
}
fun phoneIdentifier(country: String,
phone: String,
password: String,
deviceDisplayName: String?,
deviceId: String?): PasswordLoginParams {
fun phoneIdentifier(
country: String,
phone: String,
password: String,
deviceDisplayName: String?,
deviceId: String?
): PasswordLoginParams {
return PasswordLoginParams(
identifier = mapOf(
IDENTIFIER_KEY_TYPE to IDENTIFIER_KEY_TYPE_PHONE,

View File

@ -23,9 +23,10 @@ import org.matrix.android.sdk.internal.database.awaitTransaction
import org.matrix.android.sdk.internal.di.AuthDatabase
import javax.inject.Inject
internal class RealmPendingSessionStore @Inject constructor(private val mapper: PendingSessionMapper,
@AuthDatabase
private val realmConfiguration: RealmConfiguration
internal class RealmPendingSessionStore @Inject constructor(
private val mapper: PendingSessionMapper,
@AuthDatabase
private val realmConfiguration: RealmConfiguration
) : PendingSessionStore {
override suspend fun savePendingSessionData(pendingSessionData: PendingSessionData) {

View File

@ -28,9 +28,10 @@ import org.matrix.android.sdk.internal.di.AuthDatabase
import timber.log.Timber
import javax.inject.Inject
internal class RealmSessionParamsStore @Inject constructor(private val mapper: SessionParamsMapper,
@AuthDatabase
private val realmConfiguration: RealmConfiguration
internal class RealmSessionParamsStore @Inject constructor(
private val mapper: SessionParamsMapper,
@AuthDatabase
private val realmConfiguration: RealmConfiguration
) : SessionParamsStore {
override fun getLast(): SessionParams? {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -592,10 +592,12 @@ internal class DefaultCryptoService @Inject constructor(
* @param membersId list of members to start tracking their devices
* @return true if the operation succeeds.
*/
private suspend fun setEncryptionInRoom(roomId: String,
algorithm: String?,
inhibitDeviceQuery: Boolean,
membersId: List<String>): Boolean {
private suspend fun setEncryptionInRoom(
roomId: String,
algorithm: String?,
inhibitDeviceQuery: Boolean,
membersId: List<String>
): Boolean {
// If we already have encryption in this room, we should ignore this event
// (for now at least. Maybe we should alert the user somehow?)
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 callback the asynchronous callback
*/
override fun encryptEventContent(eventContent: Content,
eventType: String,
roomId: String,
callback: MatrixCallback<MXEncryptEventContentResult>) {
override fun encryptEventContent(
eventContent: Content,
eventType: String,
roomId: String,
callback: MatrixCallback<MXEncryptEventContentResult>
) {
// moved to crypto scope to have uptodate values
cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
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.
*/
private fun handleSDKLevelGossip(secretName: String?,
secretValue: String): Boolean {
private fun handleSDKLevelGossip(
secretName: String?,
secretValue: String
): Boolean {
return when (secretName) {
MASTER_KEY_SSSS_NAME -> {
crossSigningService.onSecretMSKGossip(secretValue)
@ -1022,9 +1028,11 @@ internal class DefaultCryptoService @Inject constructor(
* @param progressListener the progress listener
* @return the result ImportRoomKeysResult
*/
override suspend fun importRoomKeys(roomKeysAsArray: ByteArray,
password: String,
progressListener: ProgressListener?): ImportRoomKeysResult {
override suspend fun importRoomKeys(
roomKeysAsArray: ByteArray,
password: String,
progressListener: ProgressListener?
): ImportRoomKeysResult {
return withContext(coroutineDispatchers.crypto) {
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(
private val store: IMXCryptoStore,
private val cryptoCoroutineScope: CoroutineScope,
private val coroutineDispatchers: MatrixCoroutineDispatchers) {
private val coroutineDispatchers: MatrixCoroutineDispatchers
) {
private data class CacheKey(
val sessionId: String,

View File

@ -369,9 +369,11 @@ internal class IncomingKeyRequestManager @Inject constructor(
shareMegolmKey(validReq, requestingDevice, null)
}
private suspend fun shareMegolmKey(validRequest: ValidMegolmRequestBody,
requestingDevice: CryptoDeviceInfo,
chainIndex: Long?): Boolean {
private suspend fun shareMegolmKey(
validRequest: ValidMegolmRequestBody,
requestingDevice: CryptoDeviceInfo,
chainIndex: Long?
): Boolean {
Timber.tag(loggerTag.value)
.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
* @return true if the operation succeeds.
*/
fun addInboundGroupSession(sessionId: String,
sessionKey: String,
roomId: String,
senderKey: String,
forwardingCurve25519KeyChain: List<String>,
keysClaimed: Map<String, String>,
exportFormat: Boolean): AddSessionResult {
fun addInboundGroupSession(
sessionId: String,
sessionKey: String,
roomId: String,
senderKey: String,
forwardingCurve25519KeyChain: List<String>,
keysClaimed: Map<String, String>,
exportFormat: Boolean
): AddSessionResult {
val candidateSession = OlmInboundGroupSessionWrapper2(sessionKey, exportFormat)
val existingSessionHolder = tryOrNull { getInboundGroupSession(sessionId, senderKey, roomId) }
val existingSession = existingSessionHolder?.wrapper
@ -760,11 +762,13 @@ internal class MXOlmDevice @Inject constructor(
* @return the decrypting result. Nil if the sessionId is unknown.
*/
@Throws(MXCryptoError::class)
suspend fun decryptGroupMessage(body: String,
roomId: String,
timeline: String?,
sessionId: String,
senderKey: String): OlmDecryptionResult {
suspend fun decryptGroupMessage(
body: String,
roomId: String,
timeline: String?,
sessionId: String,
senderKey: String
): OlmDecryptionResult {
val sessionHolder = getInboundGroupSession(sessionId, senderKey, roomId)
val wrapper = sessionHolder.wrapper
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 javax.inject.Inject
internal class ObjectSigner @Inject constructor(private val credentials: Credentials,
private val olmDevice: MXOlmDevice) {
internal class ObjectSigner @Inject constructor(
private val credentials: Credentials,
private val olmDevice: MXOlmDevice
) {
/**
* Sign Object.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -148,7 +148,8 @@ internal class MXMegolmDecryption(
throw MXCryptoError.Base(
MXCryptoError.ErrorType.KEYS_WITHHELD,
withHeldInfo.code?.value ?: "",
withHeldInfo.reason)
withHeldInfo.reason
)
}
if (requestKeysOnFail) {
@ -248,9 +249,9 @@ internal class MXMegolmDecryption(
)
when (addSessionResult) {
is MXOlmDevice.AddSessionResult.Imported -> addSessionResult.ratchetIndex
is MXOlmDevice.AddSessionResult.Imported -> addSessionResult.ratchetIndex
is MXOlmDevice.AddSessionResult.NotImportedHigherIndex -> addSessionResult.newIndex
else -> null
else -> null
}?.let { index ->
if (event.getClearType() == EventType.FORWARDED_ROOM_KEY) {
val fromDevice = (event.content?.get("sender_key") as? String)?.let { senderDeviceIdentityKey ->
@ -267,7 +268,8 @@ internal class MXMegolmDecryption(
senderKey = senderKey,
fromIndex = index,
fromDevice = fromDevice,
event = event)
event = event
)
cryptoStore.saveIncomingForwardKeyAuditTrail(
roomId = roomKeyContent.roomId,
@ -276,7 +278,8 @@ internal class MXMegolmDecryption(
algorithm = roomKeyContent.algorithm ?: "",
userId = event.senderId ?: "",
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
outgoingKeyRequestManager.postCancelRequestForSessionIfNeeded(roomKeyContent.sessionId, roomKeyContent.roomId, senderKey, index)

View File

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

View File

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

View File

@ -38,7 +38,8 @@ internal class MXOlmDecryption(
// The olm device interface
private val olmDevice: MXOlmDevice,
// the matrix userId
private val userId: String) :
private val userId: String
) :
IMXDecrypting {
@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 javax.inject.Inject
internal class MXOlmDecryptionFactory @Inject constructor(private val olmDevice: MXOlmDevice,
@UserId private val userId: String) {
internal class MXOlmDecryptionFactory @Inject constructor(
private val olmDevice: MXOlmDevice,
@UserId private val userId: String
) {
fun create(): MXOlmDecryption {
return MXOlmDecryption(

View File

@ -32,7 +32,8 @@ internal class MXOlmEncryption(
private val cryptoStore: IMXCryptoStore,
private val messageEncrypter: MessageEncrypter,
private val deviceListManager: DeviceListManager,
private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) :
private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction
) :
IMXEncrypting {
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 javax.inject.Inject
internal class MXOlmEncryptionFactory @Inject constructor(private val olmDevice: MXOlmDevice,
private val cryptoStore: IMXCryptoStore,
private val messageEncrypter: MessageEncrypter,
private val deviceListManager: DeviceListManager,
private val coroutineDispatchers: MatrixCoroutineDispatchers,
private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) {
internal class MXOlmEncryptionFactory @Inject constructor(
private val olmDevice: MXOlmDevice,
private val cryptoStore: IMXCryptoStore,
private val messageEncrypter: MessageEncrypter,
private val deviceListManager: DeviceListManager,
private val coroutineDispatchers: MatrixCoroutineDispatchers,
private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction
) {
fun create(roomId: String): MXOlmEncryption {
return MXOlmEncryption(

View File

@ -117,9 +117,11 @@ internal interface CryptoApi {
* @param body the body
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sendToDevice/{eventType}/{txnId}")
suspend fun sendToDevice(@Path("eventType") eventType: String,
@Path("txnId") transactionId: String,
@Body body: SendToDeviceBody)
suspend fun sendToDevice(
@Path("eventType") eventType: String,
@Path("txnId") transactionId: String,
@Body body: SendToDeviceBody
)
/**
* Delete a device.
@ -129,8 +131,10 @@ internal interface CryptoApi {
* @param params the deletion parameters
*/
@HTTP(path = NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}", method = "DELETE", hasBody = true)
suspend fun deleteDevice(@Path("device_id") deviceId: String,
@Body params: DeleteDeviceParams)
suspend fun deleteDevice(
@Path("device_id") deviceId: String,
@Body params: DeleteDeviceParams
)
/**
* Update the device information.
@ -140,8 +144,10 @@ internal interface CryptoApi {
* @param params the params
*/
@PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "devices/{device_id}")
suspend fun updateDeviceInfo(@Path("device_id") deviceId: String,
@Body params: UpdateDeviceInfoBody)
suspend fun updateDeviceInfo(
@Path("device_id") deviceId: String,
@Body params: UpdateDeviceInfoBody
)
/**
* Get the update devices list from two sync token.
@ -151,6 +157,8 @@ internal interface CryptoApi {
* @param newToken the up-to token.
*/
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "keys/changes")
suspend fun getKeyChanges(@Query("from") oldToken: String,
@Query("to") newToken: String): KeyChangesResponse
suspend fun getKeyChanges(
@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 MESSAGE_DIGEST_ALGORITHM = "SHA-256"
fun encrypt(clearStream: InputStream,
outputFile: File,
clock: Clock,
progress: ((current: Int, total: Int) -> Unit)): EncryptedFileInfo {
fun encrypt(
clearStream: InputStream,
outputFile: File,
clock: Clock,
progress: ((current: Int, total: Int) -> Unit)
): EncryptedFileInfo {
val t0 = clock.epochMillis()
val secureRandom = SecureRandom()
val initVectorBytes = ByteArray(16) { 0.toByte() }
@ -236,10 +238,11 @@ internal object MXEncryptedAttachments {
* @param clock a clock to retrieve current time
* @return true in case of success, false in case of error
*/
fun decryptAttachment(attachmentStream: InputStream?,
elementToDecrypt: ElementToDecrypt?,
outputStream: OutputStream,
clock: Clock
fun decryptAttachment(
attachmentStream: InputStream?,
elementToDecrypt: ElementToDecrypt?,
outputStream: OutputStream,
clock: Clock
): Boolean {
// sanity checks
if (null == attachmentStream || elementToDecrypt == null) {

View File

@ -261,9 +261,10 @@ internal class DefaultCrossSigningService @Inject constructor(
}
}
override fun checkTrustFromPrivateKeys(masterKeyPrivateKey: String?,
uskKeyPrivateKey: String?,
sskPrivateKey: String?
override fun checkTrustFromPrivateKeys(
masterKeyPrivateKey: String?,
uskKeyPrivateKey: String?,
sskPrivateKey: String?
): UserTrustResult {
val mxCrossSigningInfo = getMyCrossSigningKeys() ?: return UserTrustResult.CrossSigningNotConfigured(userId)

View File

@ -276,10 +276,12 @@ internal class UpdateTrustWorker(context: Context, params: WorkerParameters, ses
}
}
private fun computeRoomShield(myCrossSigningInfo: MXCrossSigningInfo?,
cryptoRealm: Realm,
activeMemberUserIds: List<String>,
roomSummaryEntity: RoomSummaryEntity): RoomEncryptionTrustLevel {
private fun computeRoomShield(
myCrossSigningInfo: MXCrossSigningInfo?,
cryptoRealm: Realm,
activeMemberUserIds: List<String>,
roomSummaryEntity: RoomSummaryEntity
): RoomEncryptionTrustLevel {
Timber.v("## CrossSigning - computeRoomShield ${roomSummaryEntity.roomId} -> ${activeMemberUserIds.logLimit()}")
// 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

View File

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

View File

@ -49,8 +49,9 @@ internal data class GeneratePrivateKeyResult(
* @return a {privateKey, salt, iterations} tuple.
*/
@WorkerThread
internal fun generatePrivateKeyWithPassword(password: String,
progressListener: ProgressListener?
internal fun generatePrivateKeyWithPassword(
password: String,
progressListener: ProgressListener?
): GeneratePrivateKeyResult {
val salt = generateSalt()
val iterations = DEFAULT_ITERATION
@ -70,10 +71,12 @@ internal fun generatePrivateKeyWithPassword(password: String,
* @return a private key.
*/
@WorkerThread
internal fun retrievePrivateKeyWithPassword(password: String,
salt: String,
iterations: Int,
progressListener: ProgressListener? = null): ByteArray {
internal fun retrievePrivateKeyWithPassword(
password: String,
salt: String,
iterations: Int,
progressListener: ProgressListener? = null
): ByteArray {
return deriveKey(password, salt, iterations, progressListener)
}
@ -88,10 +91,12 @@ internal fun retrievePrivateKeyWithPassword(password: String,
* @return a private key.
*/
@WorkerThread
internal fun deriveKey(password: String,
salt: String,
iterations: Int,
progressListener: ProgressListener?): ByteArray {
internal fun deriveKey(
password: String,
salt: String,
iterations: Int,
progressListener: ProgressListener?
): ByteArray {
// Note: copied and adapted from MXMegolmExportEncryption
// 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.

View File

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

View File

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

View File

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

View File

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

View File

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

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