Merge branch 'develop' into feature/aris/threads_post_release_ui_improvements

# Conflicts:
#	vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt
This commit is contained in:
ariskotsomitopoulos 2022-05-17 11:55:07 +03:00
commit 324856d700
811 changed files with 2991 additions and 2192 deletions

View file

@ -67,4 +67,4 @@ jobs:
path: | path: |
vector/build/outputs/apk/*/release/*.apk vector/build/outputs/apk/*/release/*.apk
# TODO: add exodus checks # TODO add exodus checks

View file

@ -325,5 +325,5 @@ jobs:
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
hookshot_url: ${{ secrets.ELEMENT_ANDROID_HOOKSHOT_URL }} hookshot_url: ${{ secrets.ELEMENT_ANDROID_HOOKSHOT_URL }}
text_template: "Post-merge validation of ${{ github.head_ref }} into ${{ github.base_ref }} by ${{ github.event.merged_by }} failed: {{#each job_statuses }}{{#with this }}{{#if completed }} {{name}} {{conclusion}} at {{completed_at}}, {{/if}}{{/with}}{{/each}}" text_template: "Post-merge validation of ${{ github.head_ref }} into ${{ github.base_ref }} by ${{ github.event.pull_request.merged_by }} failed: {{#each job_statuses }}{{#with this }}{{#if completed }} {{name}} {{conclusion}} at {{completed_at}}, {{/if}}{{/with}}{{/each}}"
html_template: "Post-merge validation of ${{ github.head_ref }} into ${{ github.base_ref }} by ${{ github.event.merged_by }} failed: {{#each job_statuses }}{{#with this }}{{#if completed }}<br />{{icon conclusion}} {{name}} <font color='{{color conclusion}}'>{{conclusion}} at {{completed_at}} <a href=\"{{html_url}}\">[details]</a></font>{{/if}}{{/with}}{{/each}}" html_template: "Post-merge validation of ${{ github.head_ref }} into ${{ github.base_ref }} by ${{ github.event.pull_request.merged_by }} failed: {{#each job_statuses }}{{#with this }}{{#if completed }}<br />{{icon conclusion}} {{name}} <font color='{{color conclusion}}'>{{conclusion}} at {{completed_at}} <a href=\"{{html_url}}\">[details]</a></font>{{/if}}{{/with}}{{/each}}"

View file

@ -14,6 +14,16 @@ jobs:
- name: Run code quality check suite - name: Run code quality check suite
run: ./tools/check/check_code_quality.sh run: ./tools/check/check_code_quality.sh
# Knit for all the modules (https://github.com/Kotlin/kotlinx-knit)
knit:
name: Knit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run knit
run: |
./gradlew knit
# ktlint for all the modules # ktlint for all the modules
ktlint: ktlint:
name: Kotlin Linter name: Kotlin Linter
@ -147,3 +157,23 @@ jobs:
name: release-lint-report-${{ matrix.target }} name: release-lint-report-${{ matrix.target }}
path: | path: |
vector/build/reports/*.* vector/build/reports/*.*
detekt:
name: Detekt Analysis
runs-on: ubuntu-latest
# Allow all jobs on main and develop. Just one per PR.
concurrency:
group: ${{ github.ref == 'refs/heads/main' && format('detekt-main-{0}', github.sha) || github.ref == 'refs/heads/develop' && format('detekt-develop-{0}', github.sha) || format('detekt-{0}', github.ref) }}
cancel-in-progress: true
steps:
- uses: actions/checkout@v3
- name: Run detekt
run: |
./gradlew detekt
- name: Upload reports
if: always()
uses: actions/upload-artifact@v3
with:
name: detekt-report
path: |
*/build/reports/detekt/detekt.html

View file

@ -30,14 +30,17 @@ buildscript {
classpath "com.likethesalad.android:stem-plugin:2.0.0" classpath "com.likethesalad.android:stem-plugin:2.0.0"
classpath 'org.owasp:dependency-check-gradle:7.1.0.1' classpath 'org.owasp:dependency-check-gradle:7.1.0.1'
classpath "org.jetbrains.dokka:dokka-gradle-plugin:1.6.21" classpath "org.jetbrains.dokka:dokka-gradle-plugin:1.6.21"
classpath "org.jetbrains.kotlinx:kotlinx-knit:0.4.0"
// NOTE: Do not place your application dependencies here; they belong // NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files // in the individual module build.gradle files
} }
} }
// ktlint Plugin
plugins { plugins {
// ktlint Plugin
id "org.jlleitschuh.gradle.ktlint" version "10.3.0" id "org.jlleitschuh.gradle.ktlint" version "10.3.0"
// Detekt
id "io.gitlab.arturbosch.detekt" version "1.20.0"
} }
// https://github.com/jeremylong/DependencyCheck // https://github.com/jeremylong/DependencyCheck
@ -52,6 +55,7 @@ dependencyCheck {
allprojects { allprojects {
apply plugin: "org.jlleitschuh.gradle.ktlint" apply plugin: "org.jlleitschuh.gradle.ktlint"
apply plugin: "io.gitlab.arturbosch.detekt"
repositories { repositories {
// Do not use `mavenCentral()`, it prevents Dependabot from working properly // Do not use `mavenCentral()`, it prevents Dependabot from working properly
@ -119,7 +123,7 @@ allprojects {
// display the corresponding rule // display the corresponding rule
verbose = true verbose = true
disabledRules = [ disabledRules = [
// TODO: Re-enable these 4 rules after reformatting project // TODO Re-enable these 4 rules after reformatting project
"indent", "indent",
"experimental:argument-list-wrapping", "experimental:argument-list-wrapping",
"max-line-length", "max-line-length",
@ -140,6 +144,15 @@ allprojects {
"experimental:kdoc-wrapping", "experimental:kdoc-wrapping",
] ]
} }
detekt {
// preconfigure defaults
buildUponDefaultConfig = true
// activate all available (even unstable) rules.
allRules = true
// point to your custom config defining rules to run, overwriting default behavior
config = files("$rootDir/tools/detekt/detekt.yml")
}
} }
task clean(type: Delete) { task clean(type: Delete) {

1
changelog.d/5887.sdk Normal file
View file

@ -0,0 +1 @@
Small change in the Matrix class: deprecated methods have been removed and the constructor is now public. Also the fun `workerFactory()` has been renamed to `getWorkerFactory()`

1
changelog.d/5906.bugfix Normal file
View file

@ -0,0 +1 @@
Desynchronized 4S | Megolm backup causing Unusable backup

1
changelog.d/5932.feature Normal file
View file

@ -0,0 +1 @@
Allow using the latest user Avatar and name for all messages in the timeline

1
changelog.d/5973.doc Normal file
View file

@ -0,0 +1 @@
Note public_baseurl requirement in integration tests documentation.

1
changelog.d/6038.misc Normal file
View file

@ -0,0 +1 @@
Setup detekt

1
changelog.d/6047.feature Normal file
View file

@ -0,0 +1 @@
Add presence indicator busy and away.

View file

@ -10,7 +10,7 @@ ext.versions = [
def gradle = "7.2.0" def gradle = "7.2.0"
// Ref: https://kotlinlang.org/releases.html // Ref: https://kotlinlang.org/releases.html
def kotlin = "1.6.21" def kotlin = "1.6.21"
def kotlinCoroutines = "1.6.0" def kotlinCoroutines = "1.6.1"
def dagger = "2.42" def dagger = "2.42"
def retrofit = "2.9.0" def retrofit = "2.9.0"
def arrow = "0.8.2" def arrow = "0.8.2"

View file

@ -123,6 +123,7 @@ ext.groups = [
'io.github.detekt.sarif4k', 'io.github.detekt.sarif4k',
'io.github.microutils', 'io.github.microutils',
'io.github.reactivecircus.flowbinding', 'io.github.reactivecircus.flowbinding',
'io.gitlab.arturbosch.detekt',
'io.grpc', 'io.grpc',
'io.jsonwebtoken', 'io.jsonwebtoken',
'io.kindedj', 'io.kindedj',
@ -195,6 +196,7 @@ ext.groups = [
'org.testng', 'org.testng',
'org.threeten', 'org.threeten',
'org.webjars', 'org.webjars',
'org.yaml',
'ru.noties', 'ru.noties',
'xerces', 'xerces',
'xml-apis', 'xml-apis',

View file

@ -37,9 +37,9 @@ Wording: "We've sent you an email to verify your address. Please follow the inst
} }
``` ```
## User receive an e-mail ## User receives an e-mail
> [homeserver.org] Validate your email > `homeserver.org` Validate your email
> >
> A request to add an email address to your Matrix account has been received. If this was you, please click the link below to confirm adding this email: > A request to add an email address to your Matrix account has been received. If this was you, please click the link below to confirm adding this email:
https://homeserver.org/_matrix/client/unstable/add_threepid/email/submit_token?token=WUnEhQAmJrXupdEbXgdWvnVIKaGYZFsU&client_secret=TixzvOnw7nLEUdiQEmkHzkXKrY4HhiGh&sid=bxyDHuJKsdkjMlTJ https://homeserver.org/_matrix/client/unstable/add_threepid/email/submit_token?token=WUnEhQAmJrXupdEbXgdWvnVIKaGYZFsU&client_secret=TixzvOnw7nLEUdiQEmkHzkXKrY4HhiGh&sid=bxyDHuJKsdkjMlTJ

View file

@ -43,14 +43,17 @@ virtualenv -p python3 env
source env/bin/activate source env/bin/activate
pip install -e . pip install -e .
demo/start.sh --no-rate-limit demo/start.sh --no-rate-limit
``` ```
Alternatively, to install the latest Synapse release package (and not a cloned branch) you can run the following instead of `pip install -e .`: Alternatively, to install the latest Synapse release package (and not a cloned branch) you can run the following instead of `git clone` and `pip install -e .`:
```bash ```bash
pip install matrix-synapse pip install matrix-synapse
``` ```
On your first run, you will want to stop the demo and edit the config to correct the `public_baseurl` to http://10.0.2.2:8080 and restart the server.
You should now have 3 running federated Synapse instances 🎉, at http://127.0.0.1:8080/, http://127.0.0.1:8081/ and http://127.0.0.1:8082/, which should display a "It Works! Synapse is running" message. You should now have 3 running federated Synapse instances 🎉, at http://127.0.0.1:8080/, http://127.0.0.1:8081/ and http://127.0.0.1:8082/, which should display a "It Works! Synapse is running" message.
## Run the test ## Run the test
@ -87,6 +90,18 @@ You'll need python3 to be able to run synapse
Try on the Emulator browser to open "http://10.0.2.2:8080". You should see the "Synapse is running" message. Try on the Emulator browser to open "http://10.0.2.2:8080". You should see the "Synapse is running" message.
### Tests partially run but some fail with "Unable to contact localhost:8080"
This is because the `public_baseurl` of synapse is not consistent with the endpoint that the tests are connecting to.
Ensure you have the following configuration in `demo/etc/8080.config`.
```
public_baseurl: http://10.0.2.2:8080/
```
After changing this you will need to restart synapse using `demo/stop.sh` and `demo/start.sh` to load the new configuration.
### virtualenv command fails ### virtualenv command fails
You can try using You can try using

View file

@ -30,6 +30,19 @@ In any case, it is better to explicitly declare in the description why the PR is
Also, draft PR should not stay indefinitely in this state. It may be removed if it is the case and the submitter does not update it after a few days. Also, draft PR should not stay indefinitely in this state. It may be removed if it is the case and the submitter does not update it after a few days.
##### Base branch
The `develop` branch is generally the base branch for every PRs.
Exceptions can occur:
- if a feature implementation is split into multiple PRs. We can have a chain of PRs in this case. PR can be merged one by one on develop, and GitHub change the target branch to `develop` for the next PR automatically.
- we want to merge a PR from the community, but there is still work to do, and the PR is not updated by the submitter. First, we can kindly ask the submitter if they will update their PR, by commenting it. If there is no answer after a few days (including a week-end), we can create a new branch, push it, and change the target branch of the PR to this new branch. The PR can then be merged, and we can add more commits to fix the issues. After that a new PR can be created with `develop` as a target branch.
**Important notice 1:** Releases are created from the `develop` branch. So `develop` branch should always contain a "releasable" source code. So when a feature is being implemented with several PRs, it has to be disabled by default (using a feature flag for instance), until the feature is fully implemented. A last PR to enable the feature can then be created.
**Important notice 2:** Database migration: some developers and some people from the community are using the nightly build from `develop`. Multiple database migrations should be properly handled for them. This is OK to have multiple migrations between 2 releases, this is not OK to add steps to the pending database migration on `develop`. So for instance `develop` users will migrate from version 11 to version 12, then 13, then 14, and `main` users will do all those steps after they get the app upgrade.
##### PR Review Assignment ##### PR Review Assignment
We use automatic assignment for PR reviews. A PR is automatically routed by GitHub to 2 team members using the round robin algorithm. The process is the following: We use automatic assignment for PR reviews. A PR is automatically routed by GitHub to 2 team members using the round robin algorithm. The process is the following:
@ -103,7 +116,7 @@ Review such PR is the same recipe than for PR from Dependabot
##### Sync analytics plan ##### Sync analytics plan
This tools imports any update in the analytics plan. See instruction in the PR itself to handle it. This tools imports any update in the analytics plan. See instruction in the PR itself to handle it.
More info can be found in the file [analytics.md] More info can be found in the file [analytics.md](./analytics.md)
## Reviewing PR ## Reviewing PR

View file

@ -17,7 +17,7 @@
package im.vector.lib.core.utils.epoxy.charsequence package im.vector.lib.core.utils.epoxy.charsequence
/** /**
* Wrapper for a CharSequence, which support mutation of the CharSequence, which can happen during rendering * Wrapper for a CharSequence, which support mutation of the CharSequence, which can happen during rendering.
*/ */
class EpoxyCharSequence(val charSequence: CharSequence) { class EpoxyCharSequence(val charSequence: CharSequence) {
private val hash = charSequence.toString().hashCode() private val hash = charSequence.toString().hashCode()

View file

@ -17,6 +17,6 @@
package im.vector.lib.core.utils.epoxy.charsequence package im.vector.lib.core.utils.epoxy.charsequence
/** /**
* Extensions to wrap CharSequence to EpoxyCharSequence * Extensions to wrap CharSequence to EpoxyCharSequence.
*/ */
fun CharSequence.toEpoxyCharSequence() = EpoxyCharSequence(this) fun CharSequence.toEpoxyCharSequence() = EpoxyCharSequence(this)

View file

@ -22,7 +22,7 @@ import im.vector.lib.multipicker.entity.MultiPickerAudioType
import im.vector.lib.multipicker.utils.toMultiPickerAudioType import im.vector.lib.multipicker.utils.toMultiPickerAudioType
/** /**
* Audio file picker implementation * Audio file picker implementation.
*/ */
class AudioPicker : Picker<MultiPickerAudioType>() { class AudioPicker : Picker<MultiPickerAudioType>() {

View file

@ -28,12 +28,12 @@ import im.vector.lib.multipicker.utils.createTemporaryMediaFile
import im.vector.lib.multipicker.utils.toMultiPickerImageType import im.vector.lib.multipicker.utils.toMultiPickerImageType
/** /**
* Implementation of taking a photo with Camera * Implementation of taking a photo with Camera.
*/ */
class CameraPicker { class CameraPicker {
/** /**
* Start camera by using a ActivityResultLauncher * Start camera by using a ActivityResultLauncher.
* @return Uri of taken photo or null if the operation is cancelled. * @return Uri of taken photo or null if the operation is cancelled.
*/ */
fun startWithExpectingFile(context: Context, activityResultLauncher: ActivityResultLauncher<Intent>): Uri { fun startWithExpectingFile(context: Context, activityResultLauncher: ActivityResultLauncher<Intent>): Uri {

View file

@ -28,12 +28,12 @@ import im.vector.lib.multipicker.utils.createTemporaryMediaFile
import im.vector.lib.multipicker.utils.toMultiPickerVideoType import im.vector.lib.multipicker.utils.toMultiPickerVideoType
/** /**
* Implementation of taking a video with Camera * Implementation of taking a video with Camera.
*/ */
class CameraVideoPicker { class CameraVideoPicker {
/** /**
* Start camera by using a ActivityResultLauncher * Start camera by using a ActivityResultLauncher.
* @return Uri of taken photo or null if the operation is cancelled. * @return Uri of taken photo or null if the operation is cancelled.
*/ */
fun startWithExpectingFile(context: Context, activityResultLauncher: ActivityResultLauncher<Intent>): Uri { fun startWithExpectingFile(context: Context, activityResultLauncher: ActivityResultLauncher<Intent>): Uri {

View file

@ -26,7 +26,7 @@ import im.vector.lib.multipicker.entity.MultiPickerContactType
import im.vector.lib.multipicker.utils.getColumnIndexOrNull import im.vector.lib.multipicker.utils.getColumnIndexOrNull
/** /**
* Contact Picker implementation * Contact Picker implementation.
*/ */
class ContactPicker : Picker<MultiPickerContactType>() { class ContactPicker : Picker<MultiPickerContactType>() {

View file

@ -32,7 +32,7 @@ import im.vector.lib.multipicker.utils.toMultiPickerImageType
import im.vector.lib.multipicker.utils.toMultiPickerVideoType import im.vector.lib.multipicker.utils.toMultiPickerVideoType
/** /**
* Implementation of selecting any type of files * Implementation of selecting any type of files.
*/ */
class FilePicker : Picker<MultiPickerBaseType>() { class FilePicker : Picker<MultiPickerBaseType>() {

View file

@ -22,7 +22,7 @@ import im.vector.lib.multipicker.entity.MultiPickerImageType
import im.vector.lib.multipicker.utils.toMultiPickerImageType import im.vector.lib.multipicker.utils.toMultiPickerImageType
/** /**
* Image Picker implementation * Image Picker implementation.
*/ */
class ImagePicker : Picker<MultiPickerImageType>() { class ImagePicker : Picker<MultiPickerImageType>() {

View file

@ -24,7 +24,7 @@ import im.vector.lib.multipicker.utils.toMultiPickerImageType
import im.vector.lib.multipicker.utils.toMultiPickerVideoType import im.vector.lib.multipicker.utils.toMultiPickerVideoType
/** /**
* Image/Video Picker implementation * Image/Video Picker implementation.
*/ */
class MediaPicker : Picker<MultiPickerBaseMediaType>() { class MediaPicker : Picker<MultiPickerBaseMediaType>() {

View file

@ -16,7 +16,7 @@
package im.vector.lib.multipicker package im.vector.lib.multipicker
class MultiPicker<T> { class MultiPicker<T> private constructor() {
companion object Type { companion object Type {
val IMAGE by lazy { MultiPicker<ImagePicker>() } val IMAGE by lazy { MultiPicker<ImagePicker>() }

View file

@ -24,7 +24,7 @@ import android.net.Uri
import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.ActivityResultLauncher
/** /**
* Abstract class to provide all types of Pickers * Abstract class to provide all types of Pickers.
*/ */
abstract class Picker<T> { abstract class Picker<T> {

View file

@ -22,7 +22,7 @@ import im.vector.lib.multipicker.entity.MultiPickerVideoType
import im.vector.lib.multipicker.utils.toMultiPickerVideoType import im.vector.lib.multipicker.utils.toMultiPickerVideoType
/** /**
* Video Picker implementation * Video Picker implementation.
*/ */
class VideoPicker : Picker<MultiPickerVideoType>() { class VideoPicker : Picker<MultiPickerVideoType>() {

View file

@ -126,6 +126,14 @@
<color name="vctr_presence_indicator_online_light">@color/palette_element_green</color> <color name="vctr_presence_indicator_online_light">@color/palette_element_green</color>
<color name="vctr_presence_indicator_online_dark">@color/palette_element_green</color> <color name="vctr_presence_indicator_online_dark">@color/palette_element_green</color>
<attr name="vctr_presence_indicator_busy" format="color" />
<color name="vctr_presence_indicator_busy_light">@color/element_alert_light</color>
<color name="vctr_presence_indicator_busy_dark">@color/element_alert_dark</color>
<attr name="vctr_presence_indicator_away" format="color" />
<color name="vctr_presence_indicator_away_light">@color/palette_element_orange</color>
<color name="vctr_presence_indicator_away_dark">@color/palette_element_orange</color>
<!-- Location sharing colors --> <!-- Location sharing colors -->
<attr name="vctr_live_location" format="color" /> <attr name="vctr_live_location" format="color" />
<color name="vctr_live_location_light">@color/palette_prune</color> <color name="vctr_live_location_light">@color/palette_prune</color>

View file

@ -17,6 +17,7 @@
<color name="palette_melon">#FF812D</color> <color name="palette_melon">#FF812D</color>
<color name="palette_element_green">#0DBD8B</color> <color name="palette_element_green">#0DBD8B</color>
<color name="palette_element_orange">#D9B072</color>
<color name="palette_white">#FFFFFF</color> <color name="palette_white">#FFFFFF</color>
<color name="palette_vermilion">#FF5B55</color> <color name="palette_vermilion">#FF5B55</color>
<!-- (unused) --> <!-- (unused) -->

View file

@ -45,6 +45,8 @@
<!-- Presence Indicator colors --> <!-- Presence Indicator colors -->
<item name="vctr_presence_indicator_offline">@color/vctr_presence_indicator_offline_dark</item> <item name="vctr_presence_indicator_offline">@color/vctr_presence_indicator_offline_dark</item>
<item name="vctr_presence_indicator_online">@color/vctr_presence_indicator_online_dark</item> <item name="vctr_presence_indicator_online">@color/vctr_presence_indicator_online_dark</item>
<item name="vctr_presence_indicator_busy">@color/vctr_presence_indicator_busy_dark</item>
<item name="vctr_presence_indicator_away">@color/vctr_presence_indicator_away_dark</item>
<!-- Some aliases --> <!-- Some aliases -->
<item name="vctr_header_background">?vctr_system</item> <item name="vctr_header_background">?vctr_system</item>

View file

@ -45,6 +45,8 @@
<!-- Presence Indicator colors --> <!-- Presence Indicator colors -->
<item name="vctr_presence_indicator_offline">@color/vctr_presence_indicator_offline_light</item> <item name="vctr_presence_indicator_offline">@color/vctr_presence_indicator_offline_light</item>
<item name="vctr_presence_indicator_online">@color/vctr_presence_indicator_online_light</item> <item name="vctr_presence_indicator_online">@color/vctr_presence_indicator_online_light</item>
<item name="vctr_presence_indicator_busy">@color/vctr_presence_indicator_busy_light</item>
<item name="vctr_presence_indicator_away">@color/vctr_presence_indicator_away_light</item>
<!-- Some aliases --> <!-- Some aliases -->
<item name="vctr_header_background">?vctr_system</item> <item name="vctr_header_background">?vctr_system</item>

View file

@ -21,7 +21,7 @@ dokkaHtml {
dokkaSourceSets { dokkaSourceSets {
configureEach { configureEach {
// Emit warnings about not documented members. // Emit warnings about not documented members.
reportUndocumented.set(true) // reportUndocumented.set(true)
// Suppress legacy Riot's packages. // Suppress legacy Riot's packages.
perPackageOption { perPackageOption {
matchingRegex.set("org.matrix.android.sdk.internal.legacy.riot") matchingRegex.set("org.matrix.android.sdk.internal.legacy.riot")

View file

@ -11,11 +11,11 @@ This pages list the complete API that this SDK is exposing to a client applicati
A few entry points: A few entry points:
- **Matrix**: The app will have to create and manage a Matrix object. - **[Matrix](org.matrix.android.sdk.api.Matrix)**: The app will have to create and manage a **[Matrix](org.matrix.android.sdk.api.Matrix)** object.
- From this **Matrix** object, you will be able to get various services, including the **AuthenticationService**. - From this **[Matrix](org.matrix.android.sdk.api.Matrix)** object, you will be able to get various services, including the **[AuthenticationService](org.matrix.android.sdk.api.auth.AuthenticationService)**.
- With this **AuthenticationService** you will be able to get an existing **Session**, or create one using a **LoginWizard** or a **RegistrationWizard**, which will finally give you a **Session**. - With this **[AuthenticationService](org.matrix.android.sdk.api.auth.AuthenticationService)** you will be able to get an existing **[Session](org.matrix.android.sdk.api.session.Session)**, or create one using a **[LoginWizard](org.matrix.android.sdk.api.auth.login.LoginWizard)** or a **[RegistrationWizard](org.matrix.android.sdk.api.auth.registration.RegistrationWizard)**, which will finally give you a **[Session](org.matrix.android.sdk.api.session.Session)**.
- From the **Session**, you will be able to retrieve many Services, including the **RoomService**. - From the **[Session](org.matrix.android.sdk.api.session.Session)**, you will be able to retrieve many Services, including the **[RoomService](org.matrix.android.sdk.api.session.room.RoomService)**.
- From the **RoomService**, you will be able to list the rooms, create a **Room**, and get a specific **Room**. - From the **[RoomService](org.matrix.android.sdk.api.session.room.RoomService)**, you will be able to list the rooms, create a **[Room](org.matrix.android.sdk.api.session.room.Room)**, and get a specific **[Room](org.matrix.android.sdk.api.session.room.Room)**.
- And from a **Room**, you will be able to do many things, including get a **Timeline**, send messages, etc. - And from a **[Room](org.matrix.android.sdk.api.session.room.Room)**, you will be able to do many things, including get a **[Timeline](org.matrix.android.sdk.api.session.room.timeline.Timeline)**, send messages, etc.
Please read the whole documentation to learn more! Please read the whole documentation to learn more!

View file

@ -63,8 +63,9 @@ class CommonTestHelper(context: Context) {
fun getTestInterceptor(session: Session): MockOkHttpInterceptor? = TestModule.interceptorForSession(session.sessionId) as? MockOkHttpInterceptor fun getTestInterceptor(session: Session): MockOkHttpInterceptor? = TestModule.interceptorForSession(session.sessionId) as? MockOkHttpInterceptor
init { init {
var _matrix: TestMatrix? = null
UiThreadStatement.runOnUiThread { UiThreadStatement.runOnUiThread {
TestMatrix.initialize( _matrix = TestMatrix(
context, context,
MatrixConfiguration( MatrixConfiguration(
applicationFlavor = "TestFlavor", applicationFlavor = "TestFlavor",
@ -72,7 +73,7 @@ class CommonTestHelper(context: Context) {
) )
) )
} }
matrix = TestMatrix.getInstance() matrix = _matrix!!
} }
fun createAccount(userNamePrefix: String, testParams: SessionTestParams): Session { fun createAccount(userNamePrefix: String, testParams: SessionTestParams): Session {

View file

@ -203,17 +203,49 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!!
// Alice sends a message // Alice sends a message
testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[0], 1) testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[0], 1).first().eventId.let { sentEventId ->
// ensure bob got it
ensureEventReceived(aliceRoomId, sentEventId, bobSession, true)
}
// Bob send 3 messages // Bob send 3 messages
testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[0], 1) testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId ->
testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[1], 1) // ensure alice got it
testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[2], 1) ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true)
}
testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[1], 1).first().eventId.let { sentEventId ->
// ensure alice got it
ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true)
}
testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[2], 1).first().eventId.let { sentEventId ->
// ensure alice got it
ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true)
}
// Alice sends a message // Alice sends a message
testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[1], 1) testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[1], 1).first().eventId.let { sentEventId ->
// ensure bob got it
ensureEventReceived(aliceRoomId, sentEventId, bobSession, true)
}
return cryptoTestData return cryptoTestData
} }
private fun ensureEventReceived(roomId: String, eventId: String, session: Session, andCanDecrypt: Boolean) {
testHelper.waitWithLatch { latch ->
testHelper.retryPeriodicallyWithLatch(latch) {
val timeLineEvent = session.getRoom(roomId)?.timelineService()?.getTimelineEvent(eventId)
if (andCanDecrypt) {
timeLineEvent != null &&
timeLineEvent.isEncrypted() &&
timeLineEvent.root.getClearType() == EventType.MESSAGE
} else {
timeLineEvent != null
}
}
}
}
fun checkEncryptedEvent(event: Event, roomId: String, clearMessage: String, senderSession: Session) { fun checkEncryptedEvent(event: Event, roomId: String, clearMessage: String, senderSession: Session) {
assertEquals(EventType.ENCRYPTED, event.type) assertEquals(EventType.ENCRYPTED, event.type)
assertNotNull(event.content) assertNotNull(event.content)
@ -381,9 +413,9 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
testHelper.waitWithLatch { testHelper.waitWithLatch {
testHelper.retryPeriodicallyWithLatch(it) { testHelper.retryPeriodicallyWithLatch(it) {
bobVerificationService.getExistingVerificationRequests(alice.myUserId).firstOrNull { bobVerificationService.getExistingVerificationRequests(alice.myUserId).firstOrNull {
it.requestInfo?.fromDevice == alice.sessionParams.deviceId it.requestInfo?.fromDevice == alice.sessionParams.deviceId
} != null } != null
} }
} }
val incomingRequest = bobVerificationService.getExistingVerificationRequests(alice.myUserId).first { val incomingRequest = bobVerificationService.getExistingVerificationRequests(alice.myUserId).first {
@ -411,7 +443,8 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) {
requestID!!, requestID!!,
roomId, roomId,
bob.myUserId, bob.myUserId,
bob.sessionParams.credentials.deviceId!!) bob.sessionParams.credentials.deviceId!!
)
// we should reach SHOW SAS on both // we should reach SHOW SAS on both
var alicePovTx: OutgoingSasVerificationTransaction? = null var alicePovTx: OutgoingSasVerificationTransaction? = null

View file

@ -38,13 +38,12 @@ import org.matrix.android.sdk.internal.util.BackgroundDetectionObserver
import org.matrix.android.sdk.internal.worker.MatrixWorkerFactory import org.matrix.android.sdk.internal.worker.MatrixWorkerFactory
import org.matrix.olm.OlmManager import org.matrix.olm.OlmManager
import java.util.concurrent.Executors import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject import javax.inject.Inject
/** /**
* This mimics the Matrix class but using TestMatrixComponent internally instead of regular MatrixComponent. * This mimics the Matrix class but using TestMatrixComponent internally instead of regular MatrixComponent.
*/ */
internal class TestMatrix constructor(context: Context, matrixConfiguration: MatrixConfiguration) { internal class TestMatrix(context: Context, matrixConfiguration: MatrixConfiguration) {
@Inject internal lateinit var legacySessionImporter: LegacySessionImporter @Inject internal lateinit var legacySessionImporter: LegacySessionImporter
@Inject internal lateinit var authenticationService: AuthenticationService @Inject internal lateinit var authenticationService: AuthenticationService
@ -60,13 +59,14 @@ internal class TestMatrix constructor(context: Context, matrixConfiguration: Mat
private val uiHandler = Handler(Looper.getMainLooper()) private val uiHandler = Handler(Looper.getMainLooper())
init { init {
Monarchy.init(context) val appContext = context.applicationContext
DaggerTestMatrixComponent.factory().create(context, matrixConfiguration).inject(this) Monarchy.init(appContext)
DaggerTestMatrixComponent.factory().create(appContext, matrixConfiguration).inject(this)
val configuration = Configuration.Builder() val configuration = Configuration.Builder()
.setExecutor(Executors.newCachedThreadPool()) .setExecutor(Executors.newCachedThreadPool())
.setWorkerFactory(matrixWorkerFactory) .setWorkerFactory(matrixWorkerFactory)
.build() .build()
WorkManager.initialize(context, configuration) WorkManager.initialize(appContext, configuration)
uiHandler.post { uiHandler.post {
ProcessLifecycleOwner.get().lifecycle.addObserver(backgroundDetectionObserver) ProcessLifecycleOwner.get().lifecycle.addObserver(backgroundDetectionObserver)
} }
@ -95,23 +95,6 @@ internal class TestMatrix constructor(context: Context, matrixConfiguration: Mat
} }
companion object { companion object {
private lateinit var instance: TestMatrix
private val isInit = AtomicBoolean(false)
fun initialize(context: Context, matrixConfiguration: MatrixConfiguration) {
if (isInit.compareAndSet(false, true)) {
instance = TestMatrix(context.applicationContext, matrixConfiguration)
}
}
fun getInstance(): TestMatrix {
if (isInit.compareAndSet(false, false)) {
throw IllegalStateException("Matrix is not initialized properly. You should call TestMatrix.initialize first")
}
return instance
}
fun getSdkVersion(): String { fun getSdkVersion(): String {
return BuildConfig.SDK_VERSION + " (" + BuildConfig.GIT_SDK_REVISION + ")" return BuildConfig.SDK_VERSION + " (" + BuildConfig.GIT_SDK_REVISION + ")"
} }

View file

@ -24,7 +24,6 @@ import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
import org.junit.FixMethodOrder import org.junit.FixMethodOrder
import org.junit.Ignore
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.junit.runners.MethodSorters import org.junit.runners.MethodSorters
@ -37,7 +36,9 @@ import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupLastVersio
import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupState import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupState
import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupStateListener import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupStateListener
import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupVersionTrust import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupVersionTrust
import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupVersionTrustSignature
import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersion import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersion
import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersionResult
import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo
import org.matrix.android.sdk.api.session.crypto.keysbackup.toKeysVersionResult import org.matrix.android.sdk.api.session.crypto.keysbackup.toKeysVersionResult
import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult
@ -54,18 +55,16 @@ import java.util.concurrent.CountDownLatch
@LargeTest @LargeTest
class KeysBackupTest : InstrumentedTest { class KeysBackupTest : InstrumentedTest {
private val testHelper = CommonTestHelper(context())
private val cryptoTestHelper = CryptoTestHelper(testHelper)
private val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
/** /**
* - From doE2ETestWithAliceAndBobInARoomWithEncryptedMessages, we should have no backed up keys * - From doE2ETestWithAliceAndBobInARoomWithEncryptedMessages, we should have no backed up keys
* - Check backup keys after having marked one as backed up * - Check backup keys after having marked one as backed up
* - Reset keys backup markers * - Reset keys backup markers
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun roomKeysTest_testBackupStore_ok() { fun roomKeysTest_testBackupStore_ok() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
// From doE2ETestWithAliceAndBobInARoomWithEncryptedMessages, we should have no backed up keys // From doE2ETestWithAliceAndBobInARoomWithEncryptedMessages, we should have no backed up keys
@ -104,6 +103,8 @@ class KeysBackupTest : InstrumentedTest {
*/ */
@Test @Test
fun prepareKeysBackupVersionTest() { fun prepareKeysBackupVersionTest() {
val testHelper = CommonTestHelper(context())
val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams)
assertNotNull(bobSession.cryptoService().keysBackupService()) assertNotNull(bobSession.cryptoService().keysBackupService())
@ -132,7 +133,11 @@ class KeysBackupTest : InstrumentedTest {
*/ */
@Test @Test
fun createKeysBackupVersionTest() { fun createKeysBackupVersionTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams)
cryptoTestHelper.initializeCrossSigning(bobSession)
val keysBackup = bobSession.cryptoService().keysBackupService() val keysBackup = bobSession.cryptoService().keysBackupService()
@ -147,13 +152,46 @@ class KeysBackupTest : InstrumentedTest {
assertFalse(keysBackup.isEnabled) assertFalse(keysBackup.isEnabled)
// Create the version // Create the version
testHelper.doSync<KeysVersion> { val version = testHelper.doSync<KeysVersion> {
keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it)
} }
// Backup must be enable now // Backup must be enable now
assertTrue(keysBackup.isEnabled) assertTrue(keysBackup.isEnabled)
// Check that it's signed with MSK
val versionResult = testHelper.doSync<KeysVersionResult?> {
keysBackup.getVersion(version.version, it)
}
val trust = testHelper.doSync<KeysBackupVersionTrust> {
keysBackup.getKeysBackupTrust(versionResult!!, it)
}
assertEquals("Should have 2 signatures", 2, trust.signatures.size)
trust.signatures
.firstOrNull { it is KeysBackupVersionTrustSignature.DeviceSignature }
.let {
assertNotNull("Should be signed by a device", it)
it as KeysBackupVersionTrustSignature.DeviceSignature
}.let {
assertEquals("Should be signed by current device", bobSession.sessionParams.deviceId, it.deviceId)
assertTrue("Signature should be valid", it.valid)
}
trust.signatures
.firstOrNull { it is KeysBackupVersionTrustSignature.UserSignature }
.let {
assertNotNull("Should be signed by a user", it)
it as KeysBackupVersionTrustSignature.UserSignature
}.let {
val msk = bobSession.cryptoService().crossSigningService()
.getMyCrossSigningKeys()?.masterKey()?.unpaddedBase64PublicKey
assertEquals("Should be signed by my msk 1", msk, it.keyId)
assertEquals("Should be signed by my msk 2", msk, it.cryptoCrossSigningKey?.unpaddedBase64PublicKey)
assertTrue("Signature should be valid", it.valid)
}
stateObserver.stopAndCheckStates(null) stateObserver.stopAndCheckStates(null)
testHelper.signOutAndClose(bobSession) testHelper.signOutAndClose(bobSession)
} }
@ -163,8 +201,11 @@ class KeysBackupTest : InstrumentedTest {
* - Check the backup completes * - Check the backup completes
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun backupAfterCreateKeysBackupVersionTest() { fun backupAfterCreateKeysBackupVersionTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
keysBackupTestHelper.waitForKeybackUpBatching() keysBackupTestHelper.waitForKeybackUpBatching()
@ -204,8 +245,11 @@ class KeysBackupTest : InstrumentedTest {
* Check that backupAllGroupSessions() returns valid data * Check that backupAllGroupSessions() returns valid data
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun backupAllGroupSessionsTest() { fun backupAllGroupSessionsTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService()
@ -249,8 +293,11 @@ class KeysBackupTest : InstrumentedTest {
* - Compare the decrypted megolm key with the original one * - Compare the decrypted megolm key with the original one
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun testEncryptAndDecryptKeysBackupData() { fun testEncryptAndDecryptKeysBackupData() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService
@ -293,8 +340,11 @@ class KeysBackupTest : InstrumentedTest {
* - Restore must be successful * - Restore must be successful
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun restoreKeysBackupTest() { fun restoreKeysBackupTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null)
// - Restore the e2e backup from the homeserver // - Restore the e2e backup from the homeserver
@ -378,8 +428,11 @@ class KeysBackupTest : InstrumentedTest {
* - It must be trusted and must have with 2 signatures now * - It must be trusted and must have with 2 signatures now
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun trustKeyBackupVersionTest() { fun trustKeyBackupVersionTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
// - Do an e2e backup to the homeserver with a recovery key // - Do an e2e backup to the homeserver with a recovery key
// - And log Alice on a new device // - And log Alice on a new device
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null)
@ -438,8 +491,11 @@ class KeysBackupTest : InstrumentedTest {
* - It must be trusted and must have with 2 signatures now * - It must be trusted and must have with 2 signatures now
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun trustKeyBackupVersionWithRecoveryKeyTest() { fun trustKeyBackupVersionWithRecoveryKeyTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
// - Do an e2e backup to the homeserver with a recovery key // - Do an e2e backup to the homeserver with a recovery key
// - And log Alice on a new device // - And log Alice on a new device
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null)
@ -496,8 +552,11 @@ class KeysBackupTest : InstrumentedTest {
* - The backup must still be untrusted and disabled * - The backup must still be untrusted and disabled
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun trustKeyBackupVersionWithWrongRecoveryKeyTest() { fun trustKeyBackupVersionWithWrongRecoveryKeyTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
// - Do an e2e backup to the homeserver with a recovery key // - Do an e2e backup to the homeserver with a recovery key
// - And log Alice on a new device // - And log Alice on a new device
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null)
@ -538,8 +597,11 @@ class KeysBackupTest : InstrumentedTest {
* - It must be trusted and must have with 2 signatures now * - It must be trusted and must have with 2 signatures now
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun trustKeyBackupVersionWithPasswordTest() { fun trustKeyBackupVersionWithPasswordTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val password = "Password" val password = "Password"
// - Do an e2e backup to the homeserver with a password // - Do an e2e backup to the homeserver with a password
@ -598,8 +660,11 @@ class KeysBackupTest : InstrumentedTest {
* - The backup must still be untrusted and disabled * - The backup must still be untrusted and disabled
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun trustKeyBackupVersionWithWrongPasswordTest() { fun trustKeyBackupVersionWithWrongPasswordTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val password = "Password" val password = "Password"
val badPassword = "Bad Password" val badPassword = "Bad Password"
@ -639,8 +704,11 @@ class KeysBackupTest : InstrumentedTest {
* - It must fail * - It must fail
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun restoreKeysBackupWithAWrongRecoveryKeyTest() { fun restoreKeysBackupWithAWrongRecoveryKeyTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null)
// - Try to restore the e2e backup with a wrong recovery key // - Try to restore the e2e backup with a wrong recovery key
@ -673,8 +741,11 @@ class KeysBackupTest : InstrumentedTest {
* - Restore must be successful * - Restore must be successful
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun testBackupWithPassword() { fun testBackupWithPassword() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val password = "password" val password = "password"
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password)
@ -730,8 +801,11 @@ class KeysBackupTest : InstrumentedTest {
* - It must fail * - It must fail
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun restoreKeysBackupWithAWrongPasswordTest() { fun restoreKeysBackupWithAWrongPasswordTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val password = "password" val password = "password"
val wrongPassword = "passw0rd" val wrongPassword = "passw0rd"
@ -767,8 +841,11 @@ class KeysBackupTest : InstrumentedTest {
* - Restore must be successful * - Restore must be successful
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() { fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val password = "password" val password = "password"
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password)
@ -797,8 +874,11 @@ class KeysBackupTest : InstrumentedTest {
* - It must fail * - It must fail
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() { fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null)
// - Try to restore the e2e backup with a password // - Try to restore the e2e backup with a password
@ -829,8 +909,11 @@ class KeysBackupTest : InstrumentedTest {
* - Check the returned KeysVersionResult is trusted * - Check the returned KeysVersionResult is trusted
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun testIsKeysBackupTrusted() { fun testIsKeysBackupTrusted() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
// - Create a backup version // - Create a backup version
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
@ -855,7 +938,7 @@ class KeysBackupTest : InstrumentedTest {
assertTrue(keysBackupVersionTrust.usable) assertTrue(keysBackupVersionTrust.usable)
assertEquals(1, keysBackupVersionTrust.signatures.size) assertEquals(1, keysBackupVersionTrust.signatures.size)
val signature = keysBackupVersionTrust.signatures[0] val signature = keysBackupVersionTrust.signatures[0] as KeysBackupVersionTrustSignature.DeviceSignature
assertTrue(signature.valid) assertTrue(signature.valid)
assertNotNull(signature.device) assertNotNull(signature.device)
assertEquals(cryptoTestData.firstSession.cryptoService().getMyDevice().deviceId, signature.deviceId) assertEquals(cryptoTestData.firstSession.cryptoService().getMyDevice().deviceId, signature.deviceId)
@ -865,66 +948,6 @@ class KeysBackupTest : InstrumentedTest {
cryptoTestData.cleanUp(testHelper) cryptoTestData.cleanUp(testHelper)
} }
/**
* Check backup starts automatically if there is an existing and compatible backup
* version on the homeserver.
* - Create a backup version
* - Restart alice session
* -> The new alice session must back up to the same version
*/
@Test
@Ignore("This test will be ignored until it is fixed")
fun testCheckAndStartKeysBackupWhenRestartingAMatrixSession() {
// - Create a backup version
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService()
val stateObserver = StateObserver(keysBackup)
assertFalse(keysBackup.isEnabled)
val keyBackupCreationInfo = keysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup)
assertTrue(keysBackup.isEnabled)
// - Restart alice session
// - Log Alice on a new device
val aliceSession2 = testHelper.logIntoAccount(cryptoTestData.firstSession.myUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync)
cryptoTestData.cleanUp(testHelper)
val keysBackup2 = aliceSession2.cryptoService().keysBackupService()
val stateObserver2 = StateObserver(keysBackup2)
// -> The new alice session must back up to the same version
val latch = CountDownLatch(1)
var count = 0
keysBackup2.addListener(object : KeysBackupStateListener {
override fun onStateChange(newState: KeysBackupState) {
// Check the backup completes
if (newState == KeysBackupState.ReadyToBackUp) {
count++
if (count == 2) {
// Remove itself from the list of listeners
keysBackup2.removeListener(this)
latch.countDown()
}
}
}
})
testHelper.await(latch)
assertEquals(keyBackupCreationInfo.version, keysBackup2.currentBackupVersion)
stateObserver.stopAndCheckStates(null)
stateObserver2.stopAndCheckStates(null)
testHelper.signOutAndClose(aliceSession2)
}
/** /**
* Check WrongBackUpVersion state * Check WrongBackUpVersion state
* *
@ -935,6 +958,10 @@ class KeysBackupTest : InstrumentedTest {
*/ */
@Test @Test
fun testBackupWhenAnotherBackupWasCreated() { fun testBackupWhenAnotherBackupWasCreated() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
// - Create a backup version // - Create a backup version
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
@ -1005,8 +1032,11 @@ class KeysBackupTest : InstrumentedTest {
* -> It must success * -> It must success
*/ */
@Test @Test
@Ignore("This test will be ignored until it is fixed")
fun testBackupAfterVerifyingADevice() { fun testBackupAfterVerifyingADevice() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
// - Create a backup version // - Create a backup version
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()
@ -1039,6 +1069,8 @@ class KeysBackupTest : InstrumentedTest {
// - Try to backup all in aliceSession2, it must fail // - Try to backup all in aliceSession2, it must fail
val keysBackup2 = aliceSession2.cryptoService().keysBackupService() val keysBackup2 = aliceSession2.cryptoService().keysBackupService()
assertFalse("Backup should not be enabled", keysBackup2.isEnabled)
val stateObserver2 = StateObserver(keysBackup2) val stateObserver2 = StateObserver(keysBackup2)
var isSuccessful = false var isSuccessful = false
@ -1056,8 +1088,8 @@ class KeysBackupTest : InstrumentedTest {
assertFalse(isSuccessful) assertFalse(isSuccessful)
// Backup state must be NotTrusted // Backup state must be NotTrusted
assertEquals(KeysBackupState.NotTrusted, keysBackup2.state) assertEquals("Backup state must be NotTrusted", KeysBackupState.NotTrusted, keysBackup2.state)
assertFalse(keysBackup2.isEnabled) assertFalse("Backup should not be enabled", keysBackup2.isEnabled)
// - Validate the old device from the new one // - Validate the old device from the new one
aliceSession2.cryptoService().setDeviceVerification( aliceSession2.cryptoService().setDeviceVerification(
@ -1103,6 +1135,10 @@ class KeysBackupTest : InstrumentedTest {
*/ */
@Test @Test
fun deleteKeysBackupTest() { fun deleteKeysBackupTest() {
val testHelper = CommonTestHelper(context())
val cryptoTestHelper = CryptoTestHelper(testHelper)
val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper)
// - Create a backup version // - Create a backup version
val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages()

View file

@ -106,14 +106,14 @@ internal class KeysBackupTestHelper(
Assert.assertNotNull(megolmBackupCreationInfo) Assert.assertNotNull(megolmBackupCreationInfo)
Assert.assertFalse(keysBackup.isEnabled) Assert.assertFalse("Key backup should not be enabled before creation", keysBackup.isEnabled)
// Create the version // Create the version
val keysVersion = testHelper.doSync<KeysVersion> { val keysVersion = testHelper.doSync<KeysVersion> {
keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it)
} }
Assert.assertNotNull(keysVersion.version) Assert.assertNotNull("Key backup version should not be null", keysVersion.version)
// Backup must be enable now // Backup must be enable now
Assert.assertTrue(keysBackup.isEnabled) Assert.assertTrue(keysBackup.isEnabled)

View file

@ -38,15 +38,18 @@ import org.matrix.android.sdk.internal.util.BackgroundDetectionObserver
import org.matrix.android.sdk.internal.worker.MatrixWorkerFactory import org.matrix.android.sdk.internal.worker.MatrixWorkerFactory
import org.matrix.olm.OlmManager import org.matrix.olm.OlmManager
import java.util.concurrent.Executors import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject import javax.inject.Inject
/** /**
* This is the main entry point to the matrix sdk. * This is the main entry point to the matrix sdk.
* <br/> * <br/>
* See [Companion.createInstance] to create an instance. The app should create and manage the instance itself. *
* The constructor creates a new instance of Matrix, it's recommended to manage this instance as a singleton.
*
* @param context the application context
* @param matrixConfiguration global configuration that will be used for every [org.matrix.android.sdk.api.session.Session]
*/ */
class Matrix private constructor(context: Context, matrixConfiguration: MatrixConfiguration) { class Matrix(context: Context, matrixConfiguration: MatrixConfiguration) {
@Inject internal lateinit var legacySessionImporter: LegacySessionImporter @Inject internal lateinit var legacySessionImporter: LegacySessionImporter
@Inject internal lateinit var authenticationService: AuthenticationService @Inject internal lateinit var authenticationService: AuthenticationService
@ -61,89 +64,72 @@ class Matrix private constructor(context: Context, matrixConfiguration: MatrixCo
@Inject internal lateinit var lightweightSettingsStorage: LightweightSettingsStorage @Inject internal lateinit var lightweightSettingsStorage: LightweightSettingsStorage
init { init {
Monarchy.init(context) val appContext = context.applicationContext
DaggerMatrixComponent.factory().create(context, matrixConfiguration).inject(this) Monarchy.init(appContext)
if (context.applicationContext !is Configuration.Provider) { DaggerMatrixComponent.factory().create(appContext, matrixConfiguration).inject(this)
if (appContext !is Configuration.Provider) {
val configuration = Configuration.Builder() val configuration = Configuration.Builder()
.setExecutor(Executors.newCachedThreadPool()) .setExecutor(Executors.newCachedThreadPool())
.setWorkerFactory(matrixWorkerFactory) .setWorkerFactory(matrixWorkerFactory)
.build() .build()
WorkManager.initialize(context, configuration) WorkManager.initialize(appContext, configuration)
} }
ProcessLifecycleOwner.get().lifecycle.addObserver(backgroundDetectionObserver) ProcessLifecycleOwner.get().lifecycle.addObserver(backgroundDetectionObserver)
} }
/**
* Return the User Agent used for any request that the SDK is making to the homeserver.
* There is no way to change the user agent at the moment.
*/
fun getUserAgent() = userAgentHolder.userAgent fun getUserAgent() = userAgentHolder.userAgent
/**
* Return the AuthenticationService.
*/
fun authenticationService() = authenticationService fun authenticationService() = authenticationService
/**
* Return the RawService.
*/
fun rawService() = rawService fun rawService() = rawService
/**
* Return the LightweightSettingsStorage.
*/
fun lightweightSettingsStorage() = lightweightSettingsStorage fun lightweightSettingsStorage() = lightweightSettingsStorage
/**
* Return the HomeServerHistoryService.
*/
fun homeServerHistoryService() = homeServerHistoryService fun homeServerHistoryService() = homeServerHistoryService
/**
* Return the legacy session importer, useful if you want to migrate an app, which was using the legacy Matrix Android Sdk.
*/
fun legacySessionImporter() = legacySessionImporter fun legacySessionImporter() = legacySessionImporter
fun workerFactory(): WorkerFactory = matrixWorkerFactory /**
* Get the worker factory. The returned value has to be provided to `WorkConfiguration.Builder()`.
*/
fun getWorkerFactory(): WorkerFactory = matrixWorkerFactory
/**
* Register an API interceptor, to be able to be notified when the specified API got a response.
*/
fun registerApiInterceptorListener(path: ApiPath, listener: ApiInterceptorListener) { fun registerApiInterceptorListener(path: ApiPath, listener: ApiInterceptorListener) {
apiInterceptor.addListener(path, listener) apiInterceptor.addListener(path, listener)
} }
/**
* Un-register an API interceptor.
*/
fun unregisterApiInterceptorListener(path: ApiPath, listener: ApiInterceptorListener) { fun unregisterApiInterceptorListener(path: ApiPath, listener: ApiInterceptorListener) {
apiInterceptor.removeListener(path, listener) apiInterceptor.removeListener(path, listener)
} }
companion object { companion object {
private lateinit var instance: Matrix
private val isInit = AtomicBoolean(false)
/** /**
* Creates a new instance of Matrix, it's recommended to manage this instance as a singleton. * @return a String with details about the Matrix SDK version.
* To make use of the built in singleton use Matrix.initialize() and/or Matrix.getInstance(context) instead
**/
fun createInstance(context: Context, matrixConfiguration: MatrixConfiguration): Matrix {
return Matrix(context.applicationContext, matrixConfiguration)
}
/**
* Initializes a singleton instance of Matrix for the given MatrixConfiguration
* This instance will be returned by Matrix.getInstance(context)
*/
@Deprecated("Use Matrix.createInstance and manage the instance manually")
fun initialize(context: Context, matrixConfiguration: MatrixConfiguration) {
if (isInit.compareAndSet(false, true)) {
instance = Matrix(context.applicationContext, matrixConfiguration)
}
}
/**
* Either provides an already initialized singleton Matrix instance or queries the application context for a MatrixConfiguration.Provider
* to lazily create and store the instance.
*/
@Suppress("deprecation") // suppressing warning as this method is unused but is still provided for SDK clients
@Deprecated("Use Matrix.createInstance and manage the instance manually")
fun getInstance(context: Context): Matrix {
if (isInit.compareAndSet(false, true)) {
val appContext = context.applicationContext
if (appContext is MatrixConfiguration.Provider) {
val matrixConfiguration = (appContext as MatrixConfiguration.Provider).providesMatrixConfiguration()
instance = Matrix(appContext, matrixConfiguration)
} else {
throw IllegalStateException(
"Matrix is not initialized properly." +
" If you want to manage your own Matrix instance use Matrix.createInstance" +
" otherwise you should call Matrix.initialize or let your application implement MatrixConfiguration.Provider."
)
}
}
return instance
}
/**
* @return a String with details about the Matrix SDK version
*/ */
fun getSdkVersion(): String { fun getSdkVersion(): String {
return BuildConfig.SDK_VERSION + " (" + BuildConfig.GIT_SDK_REVISION + ")" return BuildConfig.SDK_VERSION + " (" + BuildConfig.GIT_SDK_REVISION + ")"

View file

@ -23,7 +23,7 @@ package org.matrix.android.sdk.api
interface MatrixCallback<in T> { interface MatrixCallback<in T> {
/** /**
* On success method, default to no-op * On success method, default to no-op.
* @param data the data successfully returned from the async function * @param data the data successfully returned from the async function
*/ */
fun onSuccess(data: T) { fun onSuccess(data: T) {
@ -31,7 +31,7 @@ interface MatrixCallback<in T> {
} }
/** /**
* On failure method, default to no-op * On failure method, default to no-op.
* @param failure the failure data returned from the async function * @param failure the failure data returned from the async function
*/ */
fun onFailure(failure: Throwable) { fun onFailure(failure: Throwable) {
@ -40,6 +40,6 @@ interface MatrixCallback<in T> {
} }
/** /**
* Basic no op implementation * Basic no op implementation.
*/ */
class NoOpMatrixCallback<T> : MatrixCallback<T> class NoOpMatrixCallback<T> : MatrixCallback<T>

View file

@ -46,7 +46,7 @@ data class MatrixConfiguration(
*/ */
val proxy: Proxy? = null, val proxy: Proxy? = null,
/** /**
* TLS versions and cipher suites limitation for unauthenticated requests * TLS versions and cipher suites limitation for unauthenticated requests.
*/ */
val connectionSpec: ConnectionSpec = ConnectionSpec.RESTRICTED_TLS, val connectionSpec: ConnectionSpec = ConnectionSpec.RESTRICTED_TLS,
/** /**
@ -62,16 +62,7 @@ data class MatrixConfiguration(
*/ */
val roomDisplayNameFallbackProvider: RoomDisplayNameFallbackProvider, val roomDisplayNameFallbackProvider: RoomDisplayNameFallbackProvider,
/** /**
* Thread messages default enable/disabled value * Thread messages default enable/disabled value.
*/ */
val threadMessagesEnabledDefault: Boolean = false, val threadMessagesEnabledDefault: Boolean = false,
) { )
/**
* Can be implemented by your Application class.
*/
@Deprecated("Use Matrix.createInstance and manage the instance manually instead of Matrix.getInstance")
interface Provider {
fun providesMatrixConfiguration(): MatrixConfiguration
}
}

View file

@ -17,7 +17,7 @@
package org.matrix.android.sdk.api package org.matrix.android.sdk.api
/** /**
* This object define some global constants regarding the Matrix specification * This object define some global constants regarding the Matrix specification.
*/ */
object MatrixConstants { object MatrixConstants {
/** /**

View file

@ -147,7 +147,7 @@ object MatrixPatterns {
} }
/** /**
* Extract server name from a matrix id * Extract server name from a matrix id.
* *
* @param matrixId * @param matrixId
* @return null if not found or if matrixId is null * @return null if not found or if matrixId is null
@ -172,7 +172,7 @@ object MatrixPatterns {
} }
/** /**
* Return the domain form a userId * Return the domain form a userId.
* Examples: * Examples:
* - "@alice:domain.org".getDomain() will return "domain.org" * - "@alice:domain.org".getDomain() will return "domain.org"
* - "@bob:domain.org:3455".getDomain() will return "domain.org:3455" * - "@bob:domain.org:3455".getDomain() will return "domain.org:3455"

View file

@ -17,21 +17,21 @@
package org.matrix.android.sdk.api package org.matrix.android.sdk.api
/** /**
* This class contains pattern to match Matrix Url, aka mxc urls * This class contains pattern to match Matrix Url, aka mxc urls.
*/ */
object MatrixUrls { object MatrixUrls {
/** /**
* "mxc" scheme, including "://". So "mxc://" * "mxc" scheme, including "://". So "mxc://".
*/ */
const val MATRIX_CONTENT_URI_SCHEME = "mxc://" const val MATRIX_CONTENT_URI_SCHEME = "mxc://"
/** /**
* Return true if the String starts with "mxc://" * Return true if the String starts with "mxc://".
*/ */
fun String.isMxcUrl() = startsWith(MATRIX_CONTENT_URI_SCHEME) fun String.isMxcUrl() = startsWith(MATRIX_CONTENT_URI_SCHEME)
/** /**
* Remove the "mxc://" prefix. No op if the String is not a Mxc URL * Remove the "mxc://" prefix. No op if the String is not a Mxc URL.
*/ */
fun String.removeMxcPrefix() = removePrefix(MATRIX_CONTENT_URI_SCHEME) fun String.removeMxcPrefix() = removePrefix(MATRIX_CONTENT_URI_SCHEME)
} }

View file

@ -40,12 +40,12 @@ interface AuthenticationService {
suspend fun getLoginFlowOfSession(sessionId: String): LoginFlowResult suspend fun getLoginFlowOfSession(sessionId: String): LoginFlowResult
/** /**
* Get a SSO url * Get a SSO url.
*/ */
fun getSsoUrl(redirectUrl: String, deviceId: String?, providerId: String?): String? fun getSsoUrl(redirectUrl: String, deviceId: String?, providerId: String?): String?
/** /**
* Get the sign in or sign up fallback URL * Get the sign in or sign up fallback URL.
*/ */
fun getFallbackUrl(forSignIn: Boolean, deviceId: String?): String? fun getFallbackUrl(forSignIn: Boolean, deviceId: String?): String?
@ -64,17 +64,17 @@ interface AuthenticationService {
fun getRegistrationWizard(): RegistrationWizard fun getRegistrationWizard(): RegistrationWizard
/** /**
* True when login and password has been sent with success to the homeserver * True when login and password has been sent with success to the homeserver.
*/ */
val isRegistrationStarted: Boolean val isRegistrationStarted: Boolean
/** /**
* Cancel pending login or pending registration * Cancel pending login or pending registration.
*/ */
suspend fun cancelPendingLoginOrRegistration() suspend fun cancelPendingLoginOrRegistration()
/** /**
* Reset all pending settings, including current HomeServerConnectionConfig * Reset all pending settings, including current HomeServerConnectionConfig.
*/ */
suspend fun reset() suspend fun reset()
@ -91,20 +91,20 @@ interface AuthenticationService {
fun getLastAuthenticatedSession(): Session? fun getLastAuthenticatedSession(): Session?
/** /**
* Create a session after a SSO successful login * Create a session after a SSO successful login.
*/ */
suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig, suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig,
credentials: Credentials): Session credentials: Credentials): Session
/** /**
* Perform a wellknown request, using the domain from the matrixId * Perform a wellknown request, using the domain from the matrixId.
*/ */
suspend fun getWellKnownData(matrixId: String, suspend fun getWellKnownData(matrixId: String,
homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult
/** /**
* Authenticate with a matrixId and a password * Authenticate with a matrixId and a password.
* Usually call this after a successful call to getWellKnownData() * Usually call this after a successful call to getWellKnownData().
* @param homeServerConnectionConfig the information about the homeserver and other configuration * @param homeServerConnectionConfig the information about the homeserver and other configuration
* @param matrixId the matrixId of the user * @param matrixId the matrixId of the user
* @param password the password of the account * @param password the password of the account

View file

@ -20,7 +20,7 @@ import com.squareup.moshi.JsonClass
import org.matrix.android.sdk.api.auth.data.LoginFlowTypes import org.matrix.android.sdk.api.auth.data.LoginFlowTypes
/** /**
* This class provides the authentication data by using user and password * This class provides the authentication data by using user and password.
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class TokenBasedAuth( data class TokenBasedAuth(

View file

@ -20,7 +20,7 @@ import com.squareup.moshi.JsonClass
import org.matrix.android.sdk.api.auth.data.LoginFlowTypes import org.matrix.android.sdk.api.auth.data.LoginFlowTypes
/** /**
* This class provides the authentication data by using user and password * This class provides the authentication data by using user and password.
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class UserPasswordAuth( data class UserPasswordAuth(

View file

@ -37,7 +37,7 @@ data class Credentials(
*/ */
@Json(name = "access_token") val accessToken: String, @Json(name = "access_token") val accessToken: String,
/** /**
* Not documented * Not documented.
*/ */
@Json(name = "refresh_token") val refreshToken: String?, @Json(name = "refresh_token") val refreshToken: String?,
/** /**

View file

@ -22,12 +22,12 @@ package org.matrix.android.sdk.api.auth.data
*/ */
data class SessionParams( data class SessionParams(
/** /**
* Please consider using shortcuts instead * Please consider using shortcuts instead.
*/ */
val credentials: Credentials, val credentials: Credentials,
/** /**
* Please consider using shortcuts instead * Please consider using shortcuts instead.
*/ */
val homeServerConnectionConfig: HomeServerConnectionConfig, val homeServerConnectionConfig: HomeServerConnectionConfig,
@ -41,12 +41,12 @@ data class SessionParams(
*/ */
/** /**
* The userId of the session (Ex: "@user:domain.org") * The userId of the session (Ex: "@user:domain.org").
*/ */
val userId = credentials.userId val userId = credentials.userId
/** /**
* The deviceId of the session (Ex: "ABCDEFGH") * The deviceId of the session (Ex: "ABCDEFGH").
*/ */
val deviceId = credentials.deviceId val deviceId = credentials.deviceId
@ -62,12 +62,12 @@ data class SessionParams(
val homeServerUrlBase = homeServerConnectionConfig.homeServerUriBase.toString() val homeServerUrlBase = homeServerConnectionConfig.homeServerUriBase.toString()
/** /**
* The current homeserver host, using what has been entered by the user during login phase * The current homeserver host, using what has been entered by the user during login phase.
*/ */
val homeServerHost = homeServerConnectionConfig.homeServerUri.host val homeServerHost = homeServerConnectionConfig.homeServerUri.host
/** /**
* The default identity server url if any, returned by the homeserver during login phase * The default identity server url if any, returned by the homeserver during login phase.
*/ */
val defaultIdentityServerUrl = homeServerConnectionConfig.identityServerUri?.toString() val defaultIdentityServerUrl = homeServerConnectionConfig.identityServerUri?.toString()
} }

View file

@ -43,6 +43,7 @@ import org.matrix.android.sdk.api.util.JsonDict
* } * }
* } * }
* </pre> * </pre>
* .
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class WellKnown( data class WellKnown(

View file

@ -26,6 +26,7 @@ import com.squareup.moshi.JsonClass
* "base_url": "https://vector.im" * "base_url": "https://vector.im"
* } * }
* </pre> * </pre>
* .
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class WellKnownBaseConfig( data class WellKnownBaseConfig(

View file

@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.util.JsonDict
*/ */
interface LoginWizard { interface LoginWizard {
/** /**
* Get some information about a matrixId: displayName and avatar url * Get some information about a matrixId: displayName and avatar url.
*/ */
suspend fun getProfileInfo(matrixId: String): LoginProfileInfo suspend fun getProfileInfo(matrixId: String): LoginProfileInfo

View file

@ -73,7 +73,7 @@ data class RegistrationFlowResponse(
) )
/** /**
* Convert to something easier to handle on client side * Convert to something easier to handle on client side.
*/ */
fun RegistrationFlowResponse.toFlowResult(): FlowResult { fun RegistrationFlowResponse.toFlowResult(): FlowResult {
// Get all the returned stages // Get all the returned stages

View file

@ -32,7 +32,7 @@ const val MXCRYPTO_ALGORITHM_MEGOLM = "m.megolm.v1.aes-sha2"
const val MXCRYPTO_ALGORITHM_MEGOLM_BACKUP = "m.megolm_backup.v1.curve25519-aes-sha2" const val MXCRYPTO_ALGORITHM_MEGOLM_BACKUP = "m.megolm_backup.v1.curve25519-aes-sha2"
/** /**
* Secured Shared Storage algorithm constant * Secured Shared Storage algorithm constant.
*/ */
const val SSSS_ALGORITHM_CURVE25519_AES_SHA2 = "m.secret_storage.v1.curve25519-aes-sha2" const val SSSS_ALGORITHM_CURVE25519_AES_SHA2 = "m.secret_storage.v1.curve25519-aes-sha2"

View file

@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.EmojiRepresentatio
import org.matrix.android.sdk.internal.crypto.verification.getEmojiForCode import org.matrix.android.sdk.internal.crypto.verification.getEmojiForCode
/** /**
* Provide all the emojis used for SAS verification (for debug purpose) * Provide all the emojis used for SAS verification (for debug purpose).
*/ */
fun getAllVerificationEmojis(): List<EmojiRepresentation> { fun getAllVerificationEmojis(): List<EmojiRepresentation> {
return (0..63).map { getEmojiForCode(it) } return (0..63).map { getEmojiForCode(it) }

View file

@ -24,6 +24,6 @@ fun CharSequence.ensurePrefix(prefix: CharSequence): CharSequence {
} }
/** /**
* Append a new line and then the provided string * Append a new line and then the provided string.
*/ */
fun StringBuilder.appendNl(str: String) = append("\n").append(str) fun StringBuilder.appendNl(str: String) = append("\n").append(str)

View file

@ -47,7 +47,7 @@ fun Throwable.shouldBeRetried() = this is Failure.NetworkConnection ||
isLimitExceededError() isLimitExceededError()
/** /**
* Get the retry delay in case of rate limit exceeded error, adding 100 ms, of defaultValue otherwise * Get the retry delay in case of rate limit exceeded error, adding 100 ms, of defaultValue otherwise.
*/ */
fun Throwable.getRetryDelay(defaultValue: Long): Long { fun Throwable.getRetryDelay(defaultValue: Long): Long {
return (this as? Failure.ServerError) return (this as? Failure.ServerError)

View file

@ -17,11 +17,11 @@
package org.matrix.android.sdk.api.failure package org.matrix.android.sdk.api.failure
/** /**
* This enum provide the reason why the SDK request an initial sync to the application * This enum provide the reason why the SDK request an initial sync to the application.
*/ */
enum class InitialSyncRequestReason { enum class InitialSyncRequestReason {
/** /**
* The list of ignored users has changed, and at least one user who was ignored is not ignored anymore * The list of ignored users has changed, and at least one user who was ignored is not ignored anymore.
*/ */
IGNORED_USERS_LIST_CHANGE, IGNORED_USERS_LIST_CHANGE,
} }

View file

@ -28,9 +28,9 @@ import org.matrix.android.sdk.api.util.JsonDict
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class MatrixError( data class MatrixError(
/** unique string which can be used to handle an error message */ /** unique string which can be used to handle an error message. */
@Json(name = "errcode") val code: String, @Json(name = "errcode") val code: String,
/** human-readable error message */ /** human-readable error message. */
@Json(name = "error") val message: String, @Json(name = "error") val message: String,
// For M_CONSENT_NOT_GIVEN // For M_CONSENT_NOT_GIVEN
@ -92,19 +92,19 @@ data class MatrixError(
/** Sent when the room alias given to the createRoom API is already in use. */ /** Sent when the room alias given to the createRoom API is already in use. */
const val M_ROOM_IN_USE = "M_ROOM_IN_USE" const val M_ROOM_IN_USE = "M_ROOM_IN_USE"
/** (Not documented yet) */ /** (Not documented yet). */
const val M_BAD_PAGINATION = "M_BAD_PAGINATION" const val M_BAD_PAGINATION = "M_BAD_PAGINATION"
/** The request was not correctly authorized. Usually due to login failures. */ /** The request was not correctly authorized. Usually due to login failures. */
const val M_UNAUTHORIZED = "M_UNAUTHORIZED" const val M_UNAUTHORIZED = "M_UNAUTHORIZED"
/** (Not documented yet) */ /** (Not documented yet). */
const val M_OLD_VERSION = "M_OLD_VERSION" const val M_OLD_VERSION = "M_OLD_VERSION"
/** The server did not understand the request. */ /** The server did not understand the request. */
const val M_UNRECOGNIZED = "M_UNRECOGNIZED" const val M_UNRECOGNIZED = "M_UNRECOGNIZED"
/** (Not documented yet) */ /** (Not documented yet). */
const val M_LOGIN_EMAIL_URL_NOT_YET = "M_LOGIN_EMAIL_URL_NOT_YET" const val M_LOGIN_EMAIL_URL_NOT_YET = "M_LOGIN_EMAIL_URL_NOT_YET"
/** Authentication could not be performed on the third party identifier. */ /** Authentication could not be performed on the third party identifier. */
@ -122,7 +122,7 @@ data class MatrixError(
/** The request or entity was too large. */ /** The request or entity was too large. */
const val M_TOO_LARGE = "M_TOO_LARGE" const val M_TOO_LARGE = "M_TOO_LARGE"
/** (Not documented yet) */ /** (Not documented yet). */
const val M_CONSENT_NOT_GIVEN = "M_CONSENT_NOT_GIVEN" const val M_CONSENT_NOT_GIVEN = "M_CONSENT_NOT_GIVEN"
/** The request cannot be completed because the homeserver has reached a resource limit imposed on it. For example, /** The request cannot be completed because the homeserver has reached a resource limit imposed on it. For example,
@ -176,10 +176,10 @@ data class MatrixError(
/** The user is unable to reject an invite to join the server notices room. See the Server Notices module for more information. */ /** The user is unable to reject an invite to join the server notices room. See the Server Notices module for more information. */
const val M_CANNOT_LEAVE_SERVER_NOTICE_ROOM = "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM" const val M_CANNOT_LEAVE_SERVER_NOTICE_ROOM = "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM"
/** (Not documented yet) */ /** (Not documented yet). */
const val M_WRONG_ROOM_KEYS_VERSION = "M_WRONG_ROOM_KEYS_VERSION" const val M_WRONG_ROOM_KEYS_VERSION = "M_WRONG_ROOM_KEYS_VERSION"
/** (Not documented yet) */ /** (Not documented yet). */
const val M_WEAK_PASSWORD = "M_WEAK_PASSWORD" const val M_WEAK_PASSWORD = "M_WEAK_PASSWORD"
/** The provided password's length is shorter than the minimum length required by the server. */ /** The provided password's length is shorter than the minimum length required by the server. */

View file

@ -18,7 +18,7 @@ package org.matrix.android.sdk.api.federation
interface FederationService { interface FederationService {
/** /**
* Get information about the homeserver * Get information about the homeserver.
*/ */
suspend fun getFederationVersion(): FederationVersion suspend fun getFederationVersion(): FederationVersion
} }

View file

@ -17,7 +17,7 @@
package org.matrix.android.sdk.api.listeners package org.matrix.android.sdk.api.listeners
/** /**
* Interface to send a progress info * Interface to send a progress info.
*/ */
interface ProgressListener { interface ProgressListener {
/** /**

View file

@ -17,7 +17,7 @@
package org.matrix.android.sdk.api.listeners package org.matrix.android.sdk.api.listeners
/** /**
* Interface to send a progress info * Interface to send a progress info.
*/ */
interface StepProgressListener { interface StepProgressListener {

View file

@ -22,15 +22,15 @@ package org.matrix.android.sdk.api.logger
* val loggerTag = LoggerTag("MyTag", LoggerTag.VOIP) * val loggerTag = LoggerTag("MyTag", LoggerTag.VOIP)
* Timber.tag(loggerTag.value).v("My log message") * Timber.tag(loggerTag.value).v("My log message")
*/ */
open class LoggerTag(_value: String, parentTag: LoggerTag? = null) { open class LoggerTag(name: String, parentTag: LoggerTag? = null) {
object SYNC : LoggerTag("SYNC") object SYNC : LoggerTag("SYNC")
object VOIP : LoggerTag("VOIP") object VOIP : LoggerTag("VOIP")
object CRYPTO : LoggerTag("CRYPTO") object CRYPTO : LoggerTag("CRYPTO")
val value: String = if (parentTag == null) { val value: String = if (parentTag == null) {
_value name
} else { } else {
"${parentTag.value}/$_value" "${parentTag.value}/$name"
} }
} }

View file

@ -36,19 +36,19 @@ sealed interface QueryStringValue {
enum class Case { enum class Case {
/** /**
* Match query sensitive to case * Match query sensitive to case.
*/ */
SENSITIVE, SENSITIVE,
/** /**
* Match query insensitive to case, this only works for Latin-1 character sets * Match query insensitive to case, this only works for Latin-1 character sets.
*/ */
INSENSITIVE, INSENSITIVE,
/** /**
* Match query with input normalized (case insensitive) * Match query with input normalized (case insensitive).
* Works around Realms inability to sort or filter by case for non Latin-1 character sets * Works around Realms inability to sort or filter by case for non Latin-1 character sets.
* Expects the target field to contain normalized data * Expects the target field to contain normalized data.
* *
* @see org.matrix.android.sdk.internal.util.Normalizer.normalize * @see org.matrix.android.sdk.internal.util.Normalizer.normalize
*/ */

View file

@ -23,19 +23,19 @@ import org.matrix.android.sdk.api.cache.CacheStrategy
*/ */
interface RawService { interface RawService {
/** /**
* Get a URL, either from cache or from the remote server, depending on the cache strategy * Get a URL, either from cache or from the remote server, depending on the cache strategy.
*/ */
suspend fun getUrl(url: String, cacheStrategy: CacheStrategy): String suspend fun getUrl(url: String, cacheStrategy: CacheStrategy): String
/** /**
* Specific case for the well-known file. Cache validity is 8 hours * Specific case for the well-known file. Cache validity is 8 hours.
* @param domain the domain to get the .well-known file, for instance "matrix.org". * @param domain the domain to get the .well-known file, for instance "matrix.org".
* The URL will be "https://{domain}/.well-known/matrix/client" * The URL will be "https://{domain}/.well-known/matrix/client"
*/ */
suspend fun getWellknown(domain: String): String suspend fun getWellknown(domain: String): String
/** /**
* Clear all the cache data * Clear all the cache data.
*/ */
suspend fun clearCache() suspend fun clearCache()
} }

View file

@ -72,23 +72,23 @@ interface Session {
val coroutineDispatchers: MatrixCoroutineDispatchers val coroutineDispatchers: MatrixCoroutineDispatchers
/** /**
* The params associated to the session * The params associated to the session.
*/ */
val sessionParams: SessionParams val sessionParams: SessionParams
/** /**
* The session is valid, i.e. it has a valid token so far * The session is valid, i.e. it has a valid token so far.
*/ */
val isOpenable: Boolean val isOpenable: Boolean
/** /**
* Useful shortcut to get access to the userId * Useful shortcut to get access to the userId.
*/ */
val myUserId: String val myUserId: String
get() = sessionParams.userId get() = sessionParams.userId
/** /**
* The sessionId * The sessionId.
*/ */
val sessionId: String val sessionId: String
@ -99,16 +99,16 @@ interface Session {
fun open() fun open()
/** /**
* Requires a one time background sync * Requires a one time background sync.
*/ */
fun requireBackgroundSync() fun requireBackgroundSync()
/** /**
* Launches infinite self rescheduling background syncs via the WorkManager * Launches infinite self rescheduling background syncs via the WorkManager.
* *
* While dozing, syncs will only occur during maintenance windows * While dozing, syncs will only occur during maintenance windows.
* For reliability it's recommended to also start a long running foreground service * For reliability it's recommended to also start a long running foreground service
* along with disabling battery optimizations * along with disabling battery optimizations.
*/ */
fun startAutomaticBackgroundSync(timeOutInSeconds: Long, repeatDelayInSeconds: Long) fun startAutomaticBackgroundSync(timeOutInSeconds: Long, repeatDelayInSeconds: Long)
@ -125,7 +125,7 @@ interface Session {
fun stopSync() fun stopSync()
/** /**
* Clear cache of the session * Clear cache of the session.
*/ */
suspend fun clearCache() suspend fun clearCache()
@ -147,7 +147,7 @@ interface Session {
fun syncFlow(): SharedFlow<SyncResponse> fun syncFlow(): SharedFlow<SyncResponse>
/** /**
* This methods return true if an initial sync has been processed * This methods return true if an initial sync has been processed.
*/ */
fun hasAlreadySynced(): Boolean fun hasAlreadySynced(): Boolean
@ -162,187 +162,187 @@ interface Session {
fun contentUrlResolver(): ContentUrlResolver fun contentUrlResolver(): ContentUrlResolver
/** /**
* Returns the ContentUploadProgressTracker associated with the session * Returns the ContentUploadProgressTracker associated with the session.
*/ */
fun contentUploadProgressTracker(): ContentUploadStateTracker fun contentUploadProgressTracker(): ContentUploadStateTracker
/** /**
* Returns the TypingUsersTracker associated with the session * Returns the TypingUsersTracker associated with the session.
*/ */
fun typingUsersTracker(): TypingUsersTracker fun typingUsersTracker(): TypingUsersTracker
/** /**
* Returns the ContentDownloadStateTracker associated with the session * Returns the ContentDownloadStateTracker associated with the session.
*/ */
fun contentDownloadProgressTracker(): ContentDownloadStateTracker fun contentDownloadProgressTracker(): ContentDownloadStateTracker
/** /**
* Returns the cryptoService associated with the session * Returns the cryptoService associated with the session.
*/ */
fun cryptoService(): CryptoService fun cryptoService(): CryptoService
/** /**
* Returns the ContentScannerService associated with the session * Returns the ContentScannerService associated with the session.
*/ */
fun contentScannerService(): ContentScannerService fun contentScannerService(): ContentScannerService
/** /**
* Returns the identity service associated with the session * Returns the identity service associated with the session.
*/ */
fun identityService(): IdentityService fun identityService(): IdentityService
/** /**
* Returns the HomeServerCapabilities service associated with the session * Returns the HomeServerCapabilities service associated with the session.
*/ */
fun homeServerCapabilitiesService(): HomeServerCapabilitiesService fun homeServerCapabilitiesService(): HomeServerCapabilitiesService
/** /**
* Returns the RoomService associated with the session * Returns the RoomService associated with the session.
*/ */
fun roomService(): RoomService fun roomService(): RoomService
/** /**
* Returns the RoomDirectoryService associated with the session * Returns the RoomDirectoryService associated with the session.
*/ */
fun roomDirectoryService(): RoomDirectoryService fun roomDirectoryService(): RoomDirectoryService
/** /**
* Returns the GroupService associated with the session * Returns the GroupService associated with the session.
*/ */
fun groupService(): GroupService fun groupService(): GroupService
/** /**
* Returns the UserService associated with the session * Returns the UserService associated with the session.
*/ */
fun userService(): UserService fun userService(): UserService
/** /**
* Returns the SignOutService associated with the session * Returns the SignOutService associated with the session.
*/ */
fun signOutService(): SignOutService fun signOutService(): SignOutService
/** /**
* Returns the FilterService associated with the session * Returns the FilterService associated with the session.
*/ */
fun filterService(): FilterService fun filterService(): FilterService
/** /**
* Returns the PushRuleService associated with the session * Returns the PushRuleService associated with the session.
*/ */
fun pushRuleService(): PushRuleService fun pushRuleService(): PushRuleService
/** /**
* Returns the PushersService associated with the session * Returns the PushersService associated with the session.
*/ */
fun pushersService(): PushersService fun pushersService(): PushersService
/** /**
* Returns the EventService associated with the session * Returns the EventService associated with the session.
*/ */
fun eventService(): EventService fun eventService(): EventService
/** /**
* Returns the TermsService associated with the session * Returns the TermsService associated with the session.
*/ */
fun termsService(): TermsService fun termsService(): TermsService
/** /**
* Returns the SyncStatusService associated with the session * Returns the SyncStatusService associated with the session.
*/ */
fun syncStatusService(): SyncStatusService fun syncStatusService(): SyncStatusService
/** /**
* Returns the SecureStorageService associated with the session * Returns the SecureStorageService associated with the session.
*/ */
fun secureStorageService(): SecureStorageService fun secureStorageService(): SecureStorageService
/** /**
* Returns the ProfileService associated with the session * Returns the ProfileService associated with the session.
*/ */
fun profileService(): ProfileService fun profileService(): ProfileService
/** /**
* Returns the PresenceService associated with the session * Returns the PresenceService associated with the session.
*/ */
fun presenceService(): PresenceService fun presenceService(): PresenceService
/** /**
* Returns the AccountService associated with the session * Returns the AccountService associated with the session.
*/ */
fun accountService(): AccountService fun accountService(): AccountService
/** /**
* Returns the ToDeviceService associated with the session * Returns the ToDeviceService associated with the session.
*/ */
fun toDeviceService(): ToDeviceService fun toDeviceService(): ToDeviceService
/** /**
* Returns the EventStreamService associated with the session * Returns the EventStreamService associated with the session.
*/ */
fun eventStreamService(): EventStreamService fun eventStreamService(): EventStreamService
/** /**
* Returns the widget service associated with the session * Returns the widget service associated with the session.
*/ */
fun widgetService(): WidgetService fun widgetService(): WidgetService
/** /**
* Returns the media service associated with the session * Returns the media service associated with the session.
*/ */
fun mediaService(): MediaService fun mediaService(): MediaService
/** /**
* Returns the integration manager service associated with the session * Returns the integration manager service associated with the session.
*/ */
fun integrationManagerService(): IntegrationManagerService fun integrationManagerService(): IntegrationManagerService
/** /**
* Returns the call signaling service associated with the session * Returns the call signaling service associated with the session.
*/ */
fun callSignalingService(): CallSignalingService fun callSignalingService(): CallSignalingService
/** /**
* Returns the file download service associated with the session * Returns the file download service associated with the session.
*/ */
fun fileService(): FileService fun fileService(): FileService
/** /**
* Returns the permalink service associated with the session * Returns the permalink service associated with the session.
*/ */
fun permalinkService(): PermalinkService fun permalinkService(): PermalinkService
/** /**
* Returns the search service associated with the session * Returns the search service associated with the session.
*/ */
fun searchService(): SearchService fun searchService(): SearchService
/** /**
* Returns the federation service associated with the session * Returns the federation service associated with the session.
*/ */
fun federationService(): FederationService fun federationService(): FederationService
/** /**
* Returns the third party service associated with the session * Returns the third party service associated with the session.
*/ */
fun thirdPartyService(): ThirdPartyService fun thirdPartyService(): ThirdPartyService
/** /**
* Returns the space service associated with the session * Returns the space service associated with the session.
*/ */
fun spaceService(): SpaceService fun spaceService(): SpaceService
/** /**
* Returns the open id service associated with the session * Returns the open id service associated with the session.
*/ */
fun openIdService(): OpenIdService fun openIdService(): OpenIdService
/** /**
* Returns the account data service associated with the session * Returns the account data service associated with the session.
*/ */
fun accountDataService(): SessionAccountDataService fun accountDataService(): SessionAccountDataService
/** /**
* Returns the SharedSecretStorageService associated with the session * Returns the SharedSecretStorageService associated with the session.
*/ */
fun sharedSecretStorageService(): SharedSecretStorageService fun sharedSecretStorageService(): SharedSecretStorageService
@ -377,8 +377,8 @@ interface Session {
/** /**
* Possible cases: * Possible cases:
* - The access token is not valid anymore, * - The access token is not valid anymore,
* - a M_CONSENT_NOT_GIVEN error has been received from the homeserver * - a M_CONSENT_NOT_GIVEN error has been received from the homeserver;
* See [GlobalError] for all the possible cases * See [GlobalError] for all the possible cases.
*/ */
fun onGlobalError(session: Session, globalError: GlobalError) = Unit fun onGlobalError(session: Session, globalError: GlobalError) = Unit
} }
@ -386,7 +386,7 @@ interface Session {
fun getUiaSsoFallbackUrl(authenticationSessionId: String): String fun getUiaSsoFallbackUrl(authenticationSessionId: String): String
/** /**
* Maintenance API, allows to print outs info on DB size to logcat * Maintenance API, allows to print outs info on DB size to logcat.
*/ */
fun logDbUsageInfo() fun logDbUsageInfo()
} }

View file

@ -21,16 +21,16 @@ import org.matrix.android.sdk.api.session.room.model.RoomSummary
import org.matrix.android.sdk.api.session.user.model.User import org.matrix.android.sdk.api.session.user.model.User
/** /**
* Get a room using the RoomService of a Session * Get a room using the RoomService of a Session.
*/ */
fun Session.getRoom(roomId: String): Room? = roomService().getRoom(roomId) fun Session.getRoom(roomId: String): Room? = roomService().getRoom(roomId)
/** /**
* Get a room summary using the RoomService of a Session * Get a room summary using the RoomService of a Session.
*/ */
fun Session.getRoomSummary(roomIdOrAlias: String): RoomSummary? = roomService().getRoomSummary(roomIdOrAlias) fun Session.getRoomSummary(roomIdOrAlias: String): RoomSummary? = roomService().getRoomSummary(roomIdOrAlias)
/** /**
* Get a user using the UserService of a Session * Get a user using the UserService of a Session.
*/ */
fun Session.getUser(userId: String): User? = userService().getUser(userId) fun Session.getUser(userId: String): User? = userService().getUser(userId)

View file

@ -21,9 +21,8 @@ import org.matrix.android.sdk.api.session.events.model.Content
import java.util.UUID import java.util.UUID
interface ToDeviceService { interface ToDeviceService {
/** /**
* Send an event to a specific list of devices * Send an event to a specific list of devices.
*/ */
suspend fun sendToDevice(eventType: String, contentMap: MXUsersDevicesMap<Any>, txnId: String? = UUID.randomUUID().toString()) suspend fun sendToDevice(eventType: String, contentMap: MXUsersDevicesMap<Any>, txnId: String? = UUID.randomUUID().toString())

View file

@ -26,12 +26,12 @@ import org.matrix.android.sdk.api.util.Optional
*/ */
interface SessionAccountDataService { interface SessionAccountDataService {
/** /**
* Retrieve the account data with the provided type or null if not found * Retrieve the account data with the provided type or null if not found.
*/ */
fun getUserAccountDataEvent(type: String): UserAccountDataEvent? fun getUserAccountDataEvent(type: String): UserAccountDataEvent?
/** /**
* Observe the account data with the provided type * Observe the account data with the provided type.
*/ */
fun getLiveUserAccountDataEvent(type: String): LiveData<Optional<UserAccountDataEvent>> fun getLiveUserAccountDataEvent(type: String): LiveData<Optional<UserAccountDataEvent>>
@ -60,7 +60,7 @@ interface SessionAccountDataService {
fun getLiveRoomAccountDataEvents(types: Set<String>): LiveData<List<RoomAccountDataEvent>> fun getLiveRoomAccountDataEvents(types: Set<String>): LiveData<List<RoomAccountDataEvent>>
/** /**
* Update the account data with the provided type and the provided account data content * Update the account data with the provided type and the provided account data content.
*/ */
suspend fun updateUserAccountData(type: String, content: Content) suspend fun updateUserAccountData(type: String, content: Content)
} }

View file

@ -39,32 +39,32 @@ interface CallListener {
fun onCallAnswerReceived(callAnswerContent: CallAnswerContent) fun onCallAnswerReceived(callAnswerContent: CallAnswerContent)
/** /**
* Called when a called has been hung up * Called when a called has been hung up.
*/ */
fun onCallHangupReceived(callHangupContent: CallHangupContent) fun onCallHangupReceived(callHangupContent: CallHangupContent)
/** /**
* Called when a called has been rejected * Called when a called has been rejected.
*/ */
fun onCallRejectReceived(callRejectContent: CallRejectContent) fun onCallRejectReceived(callRejectContent: CallRejectContent)
/** /**
* Called when an answer has been selected * Called when an answer has been selected.
*/ */
fun onCallSelectAnswerReceived(callSelectAnswerContent: CallSelectAnswerContent) fun onCallSelectAnswerReceived(callSelectAnswerContent: CallSelectAnswerContent)
/** /**
* Called when a negotiation is sent * Called when a negotiation is sent.
*/ */
fun onCallNegotiateReceived(callNegotiateContent: CallNegotiateContent) fun onCallNegotiateReceived(callNegotiateContent: CallNegotiateContent)
/** /**
* Called when the call has been managed by an other session * Called when the call has been managed by an other session.
*/ */
fun onCallManagedByOtherSession(callId: String) fun onCallManagedByOtherSession(callId: String)
/** /**
* Called when an asserted identity event is received * Called when an asserted identity event is received.
*/ */
fun onCallAssertedIdentityReceived(callAssertedIdentityContent: CallAssertedIdentityContent) fun onCallAssertedIdentityReceived(callAssertedIdentityContent: CallAssertedIdentityContent)
} }

View file

@ -21,7 +21,7 @@ interface CallSignalingService {
suspend fun getTurnServer(): TurnServerResponse suspend fun getTurnServer(): TurnServerResponse
/** /**
* Create an outgoing call * Create an outgoing call.
*/ */
fun createOutgoingCall(roomId: String, otherUserId: String, isVideoCall: Boolean): MxCall fun createOutgoingCall(roomId: String, otherUserId: String, isVideoCall: Boolean): MxCall

View file

@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.room.model.call.EndCallReason
sealed class CallState { sealed class CallState {
/** Idle, setting up objects */ /** Idle, setting up objects. */
object Idle : CallState() object Idle : CallState()
/** /**

View file

@ -35,7 +35,7 @@ interface MxCallDetail {
} }
/** /**
* Define both an incoming call and on outgoing call * Define both an incoming call and on outgoing call.
*/ */
interface MxCall : MxCallDetail { interface MxCall : MxCallDetail {
@ -46,13 +46,13 @@ interface MxCall : MxCallDetail {
var state: CallState var state: CallState
/** /**
* Pick Up the incoming call * Pick Up the incoming call.
* It has no effect on outgoing call * It has no effect on outgoing call.
*/ */
fun accept(sdpString: String) fun accept(sdpString: String)
/** /**
* SDP negotiation for media pause, hold/resume, ICE restarts and voice/video call up/downgrading * SDP negotiation for media pause, hold/resume, ICE restarts and voice/video call up/downgrading.
*/ */
fun negotiate(sdpString: String, type: SdpType) fun negotiate(sdpString: String, type: SdpType)
@ -62,17 +62,17 @@ interface MxCall : MxCallDetail {
fun selectAnswer() fun selectAnswer()
/** /**
* Reject an incoming call * Reject an incoming call.
*/ */
fun reject() fun reject()
/** /**
* End the call * End the call.
*/ */
fun hangUp(reason: EndCallReason? = null) fun hangUp(reason: EndCallReason? = null)
/** /**
* Start a call * Start a call.
* Send offer SDP to the other participant. * Send offer SDP to the other participant.
*/ */
fun offerSdp(sdpString: String) fun offerSdp(sdpString: String)

View file

@ -29,7 +29,7 @@ interface ContentUrlResolver {
} }
/** /**
* URL to use to upload content * URL to use to upload content.
*/ */
val uploadUrl: String val uploadUrl: String
@ -42,7 +42,7 @@ interface ContentUrlResolver {
fun resolveFullSize(contentUrl: String?): String? fun resolveFullSize(contentUrl: String?): String?
/** /**
* Get the ResolvedMethod to download a URL * Get the ResolvedMethod to download a URL.
* *
* @param contentUrl the Matrix media content URI (in the form of "mxc://..."). * @param contentUrl the Matrix media content URI (in the form of "mxc://...").
* @param elementToDecrypt Encryption data may be required if you use a content scanner * @param elementToDecrypt Encryption data may be required if you use a content scanner

View file

@ -155,8 +155,8 @@ interface CryptoService {
fun getIncomingRoomKeyRequestsPaged(): LiveData<PagedList<IncomingRoomKeyRequest>> fun getIncomingRoomKeyRequestsPaged(): LiveData<PagedList<IncomingRoomKeyRequest>>
/** /**
* Can be called by the app layer to accept a request manually * Can be called by the app layer to accept a request manually.
* Use carefully as it is prone to social attacks * Use carefully as it is prone to social attacks.
*/ */
suspend fun manuallyAcceptRoomKeyRequest(request: IncomingRoomKeyRequest) suspend fun manuallyAcceptRoomKeyRequest(request: IncomingRoomKeyRequest)

View file

@ -28,7 +28,7 @@ sealed class MXCryptoError : Throwable() {
data class Base(val errorType: ErrorType, data class Base(val errorType: ErrorType,
val technicalMessage: String, val technicalMessage: String,
/** /**
* Describe the error with more details * Describe the error with more details.
*/ */
val detailedErrorDescription: String? = null) : MXCryptoError() val detailedErrorDescription: String? = null) : MXCryptoError()
@ -63,7 +63,7 @@ sealed class MXCryptoError : Throwable() {
companion object { companion object {
/** /**
* Resource for technicalMessage * Resource for technicalMessage.
*/ */
const val UNABLE_TO_ENCRYPT_REASON = "Unable to encrypt %s" const val UNABLE_TO_ENCRYPT_REASON = "Unable to encrypt %s"
const val UNABLE_TO_DECRYPT_REASON = "Unable to decrypt %1\$s. Algorithm: %2\$s" const val UNABLE_TO_DECRYPT_REASON = "Unable to decrypt %1\$s. Algorithm: %2\$s"

View file

@ -17,7 +17,7 @@
package org.matrix.android.sdk.api.session.crypto package org.matrix.android.sdk.api.session.crypto
/** /**
* This listener notifies on new Megolm sessions being created * This listener notifies on new Megolm sessions being created.
*/ */
interface NewSessionListener { interface NewSessionListener {

View file

@ -35,7 +35,7 @@ fun EncryptedFileInfo.toElementToDecrypt(): ElementToDecrypt? {
} }
/** /**
* Represent data to decode an attachment * Represent data to decode an attachment.
*/ */
@Parcelize @Parcelize
data class ElementToDecrypt( data class ElementToDecrypt(

View file

@ -66,7 +66,7 @@ interface CrossSigningService {
fun markMyMasterKeyAsTrusted() fun markMyMasterKeyAsTrusted()
/** /**
* Sign one of your devices and upload the signature * Sign one of your devices and upload the signature.
*/ */
fun trustDevice(deviceId: String, fun trustDevice(deviceId: String,
callback: MatrixCallback<Unit>) callback: MatrixCallback<Unit>)

View file

@ -23,7 +23,7 @@ import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult
interface KeysBackupService { interface KeysBackupService {
/** /**
* Retrieve the current version of the backup from the homeserver * Retrieve the current version of the backup from the homeserver.
* *
* It can be different than keysBackupVersion. * It can be different than keysBackupVersion.
* @param callback Asynchronous callback * @param callback Asynchronous callback
@ -40,12 +40,12 @@ interface KeysBackupService {
callback: MatrixCallback<KeysVersion>) callback: MatrixCallback<KeysVersion>)
/** /**
* Facility method to get the total number of locally stored keys * Facility method to get the total number of locally stored keys.
*/ */
fun getTotalNumbersOfKeys(): Int fun getTotalNumbersOfKeys(): Int
/** /**
* Facility method to get the number of backed up keys * Facility method to get the number of backed up keys.
*/ */
fun getTotalNumbersOfBackedUpKeys(): Int fun getTotalNumbersOfBackedUpKeys(): Int
@ -68,7 +68,7 @@ interface KeysBackupService {
callback: MatrixCallback<KeysBackupVersionTrust>) callback: MatrixCallback<KeysBackupVersionTrust>)
/** /**
* Return the current progress of the backup * Return the current progress of the backup.
*/ */
fun getBackupProgress(progressListener: ProgressListener) fun getBackupProgress(progressListener: ProgressListener)

View file

@ -19,7 +19,7 @@ package org.matrix.android.sdk.api.session.crypto.keysbackup
interface KeysBackupStateListener { interface KeysBackupStateListener {
/** /**
* The keys backup state has changed * The keys backup state has changed.
* @param newState the new state * @param newState the new state
*/ */
fun onStateChange(newState: KeysBackupState) fun onStateChange(newState: KeysBackupState)

View file

@ -16,25 +16,35 @@
package org.matrix.android.sdk.api.session.crypto.keysbackup package org.matrix.android.sdk.api.session.crypto.keysbackup
import org.matrix.android.sdk.api.session.crypto.crosssigning.CryptoCrossSigningKey
import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
/** /**
* A signature in a `KeysBackupVersionTrust` object. * A signature in a `KeysBackupVersionTrust` object.
*/ */
data class KeysBackupVersionTrustSignature(
/**
* The id of the device that signed the backup version.
*/
val deviceId: String?,
/** sealed class KeysBackupVersionTrustSignature {
* The device that signed the backup version.
* Can be null if the device is not known.
*/
val device: CryptoDeviceInfo?,
/** data class DeviceSignature(
* Flag to indicate the signature from this device is valid. /**
*/ * The id of the device that signed the backup version.
val valid: Boolean, */
) val deviceId: String?,
/**
* The device that signed the backup version.
* Can be null if the device is not known.
*/
val device: CryptoDeviceInfo?,
/**
* Flag to indicate the signature from this device is valid.
*/
val valid: Boolean) : KeysBackupVersionTrustSignature()
data class UserSignature(
val keyId: String?,
val cryptoCrossSigningKey: CryptoCrossSigningKey?,
val valid: Boolean
) : KeysBackupVersionTrustSignature()
}

View file

@ -30,8 +30,8 @@ data class KeysVersionResult(
override val algorithm: String, override val algorithm: String,
/** /**
* algorithm-dependent data, for "m.megolm_backup.v1.curve25519-aes-sha2" * algorithm-dependent data, for "m.megolm_backup.v1.curve25519-aes-sha2".
* see [org.matrix.android.sdk.internal.crypto.keysbackup.MegolmBackupAuthData] * @see [org.matrix.android.sdk.internal.crypto.keysbackup.MegolmBackupAuthData]
*/ */
@Json(name = "auth_data") @Json(name = "auth_data")
override val authData: JsonDict, override val authData: JsonDict,

View file

@ -30,7 +30,7 @@ private const val CHAR_1 = 0x01.toByte()
private const val RECOVERY_KEY_LENGTH = 2 + 32 + 1 private const val RECOVERY_KEY_LENGTH = 2 + 32 + 1
/** /**
* Tell if the format of the recovery key is correct * Tell if the format of the recovery key is correct.
* *
* @param recoveryKey * @param recoveryKey
* @return true if the format of the recovery key is correct * @return true if the format of the recovery key is correct
@ -40,7 +40,7 @@ fun isValidRecoveryKey(recoveryKey: String?): Boolean {
} }
/** /**
* Compute recovery key from curve25519 key * Compute recovery key from curve25519 key.
* *
* @param curve25519Key * @param curve25519Key
* @return the recovery key * @return the recovery key
@ -69,7 +69,7 @@ fun computeRecoveryKey(curve25519Key: ByteArray): String {
} }
/** /**
* Please call [.isValidRecoveryKey] and ensure it returns true before calling this method * Please call [.isValidRecoveryKey] and ensure it returns true before calling this method.
* *
* @param recoveryKey the recovery key * @param recoveryKey the recovery key
* @return curveKey, or null in case of error * @return curveKey, or null in case of error

View file

@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest
/** /**
* Room keys events listener * Room keys events listener.
*/ */
interface GossipingRequestListener { interface GossipingRequestListener {
/** /**
@ -31,7 +31,7 @@ interface GossipingRequestListener {
fun onRoomKeyRequest(request: IncomingRoomKeyRequest) fun onRoomKeyRequest(request: IncomingRoomKeyRequest)
/** /**
* Returns the secret value to be shared * Returns the secret value to be shared.
* @return true if is handled * @return true if is handled
*/ */
fun onSecretShareRequest(request: SecretShareRequest): Boolean fun onSecretShareRequest(request: SecretShareRequest): Boolean

View file

@ -20,24 +20,24 @@ import com.squareup.moshi.JsonClass
import org.matrix.android.sdk.api.interfaces.DatedObject import org.matrix.android.sdk.api.interfaces.DatedObject
/** /**
* This class describes the device information * This class describes the device information.
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class DeviceInfo( data class DeviceInfo(
/** /**
* The owner user id (not documented and useless but the homeserver sent it. You should not need it) * The owner user id (not documented and useless but the homeserver sent it. You should not need it).
*/ */
@Json(name = "user_id") @Json(name = "user_id")
val userId: String? = null, val userId: String? = null,
/** /**
* The device id * The device id.
*/ */
@Json(name = "device_id") @Json(name = "device_id")
val deviceId: String? = null, val deviceId: String? = null,
/** /**
* The device display name * The device display name.
*/ */
@Json(name = "display_name") @Json(name = "display_name")
val displayName: String? = null, val displayName: String? = null,
@ -49,7 +49,7 @@ data class DeviceInfo(
val lastSeenTs: Long? = null, val lastSeenTs: Long? = null,
/** /**
* The last ip address * The last ip address.
*/ */
@Json(name = "last_seen_ip") @Json(name = "last_seen_ip")
val lastSeenIp: String? = null val lastSeenIp: String? = null

View file

@ -20,7 +20,7 @@ import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonClass
/** /**
* In Matrix specs: EncryptedFile * In Matrix specs: EncryptedFile.
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class EncryptedFileInfo( data class EncryptedFileInfo(
@ -56,7 +56,7 @@ data class EncryptedFileInfo(
val v: String? = null val v: String? = null
) { ) {
/** /**
* Check what the spec tells us * Check what the spec tells us.
*/ */
fun isValid(): Boolean { fun isValid(): Boolean {
if (url.isNullOrBlank()) { if (url.isNullOrBlank()) {

View file

@ -52,7 +52,7 @@ data class EncryptedFileKey(
val k: String? = null val k: String? = null
) { ) {
/** /**
* Check what the spec tells us * Check what the spec tells us.
*/ */
fun isValid(): Boolean { fun isValid(): Boolean {
if (alg != "A256CTR") { if (alg != "A256CTR") {

View file

@ -17,7 +17,7 @@
package org.matrix.android.sdk.api.session.crypto.model package org.matrix.android.sdk.api.session.crypto.model
/** /**
* Interface representing an room key action request * Interface representing an room key action request.
* Note: this class cannot be abstract because of [org.matrix.androidsdk.core.JsonUtils.toRoomKeyShare] * Note: this class cannot be abstract because of [org.matrix.androidsdk.core.JsonUtils.toRoomKeyShare]
*/ */
interface GossipingToDeviceObject : SendToDeviceObject { interface GossipingToDeviceObject : SendToDeviceObject {

View file

@ -23,22 +23,22 @@ import org.matrix.android.sdk.internal.util.time.Clock
*/ */
data class IncomingRoomKeyRequest( data class IncomingRoomKeyRequest(
/** /**
* The user id * The user id.
*/ */
val userId: String? = null, val userId: String? = null,
/** /**
* The device id * The device id.
*/ */
val deviceId: String? = null, val deviceId: String? = null,
/** /**
* The request id * The request id.
*/ */
val requestId: String? = null, val requestId: String? = null,
/** /**
* The request body * The request body.
*/ */
val requestBody: RoomKeyRequestBody? = null, val requestBody: RoomKeyRequestBody? = null,
@ -46,7 +46,7 @@ data class IncomingRoomKeyRequest(
) { ) {
companion object { companion object {
/** /**
* Factory * Factory.
* *
* @param event the event * @param event the event
* @param currentTimeMillis the current time in milliseconds * @param currentTimeMillis the current time in milliseconds

View file

@ -30,7 +30,7 @@ data class MXDeviceInfo(
val deviceId: String, val deviceId: String,
/** /**
* the user id * the user id.
*/ */
@Json(name = "user_id") @Json(name = "user_id")
val userId: String, val userId: String,
@ -66,7 +66,7 @@ data class MXDeviceInfo(
val verified: Int = DEVICE_VERIFICATION_UNKNOWN val verified: Int = DEVICE_VERIFICATION_UNKNOWN
) : Serializable { ) : Serializable {
/** /**
* Tells if the device is unknown * Tells if the device is unknown.
* *
* @return true if the device is unknown * @return true if the device is unknown
*/ */

View file

@ -20,11 +20,11 @@ import org.matrix.android.sdk.api.session.events.model.Content
data class MXEncryptEventContentResult( data class MXEncryptEventContentResult(
/** /**
* The encrypted event content * The encrypted event content.
*/ */
val eventContent: Content, val eventContent: Content,
/** /**
* the event type * The event type.
*/ */
val eventType: String val eventType: String
) )

View file

@ -31,7 +31,7 @@ class MXUsersDevicesMap<E> {
get() = map.isEmpty() get() = map.isEmpty()
/** /**
* Provides the device ids list for a user id * Provides the device ids list for a user id.
* FIXME Should maybe return emptyList and not null, to avoid many !! in the code * FIXME Should maybe return emptyList and not null, to avoid many !! in the code
* *
* @param userId the user id * @param userId the user id
@ -44,7 +44,7 @@ class MXUsersDevicesMap<E> {
} }
/** /**
* Provides the object for a device id and a user Id * Provides the object for a device id and a user Id.
* *
* @param deviceId the device id * @param deviceId the device id
* @param userId the object id * @param userId the object id
@ -57,7 +57,7 @@ class MXUsersDevicesMap<E> {
} }
/** /**
* Set an object for a dedicated user Id and device Id * Set an object for a dedicated user Id and device Id.
* *
* @param userId the user Id * @param userId the user Id
* @param deviceId the device id * @param deviceId the device id
@ -71,7 +71,7 @@ class MXUsersDevicesMap<E> {
} }
/** /**
* Defines the objects map for a user Id * Defines the objects map for a user Id.
* *
* @param objectsPerDevices the objects maps * @param objectsPerDevices the objects maps
* @param userId the user id * @param userId the user id
@ -87,7 +87,7 @@ class MXUsersDevicesMap<E> {
} }
/** /**
* Removes objects for a dedicated user * Removes objects for a dedicated user.
* *
* @param userId the user id. * @param userId the user id.
*/ */
@ -98,14 +98,14 @@ class MXUsersDevicesMap<E> {
} }
/** /**
* Clear the internal dictionary * Clear the internal dictionary.
*/ */
fun removeAllObjects() { fun removeAllObjects() {
map.clear() map.clear()
} }
/** /**
* Add entries from another MXUsersDevicesMap * Add entries from another MXUsersDevicesMap.
* *
* @param other the other one * @param other the other one
*/ */

View file

@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.util.JsonDict
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class OlmDecryptionResult( data class OlmDecryptionResult(
/** /**
* The decrypted payload (with properties 'type', 'content') * The decrypted payload (with properties 'type', 'content').
*/ */
@Json(name = "payload") val payload: JsonDict? = null, @Json(name = "payload") val payload: JsonDict? = null,

View file

@ -21,7 +21,7 @@ import com.squareup.moshi.JsonClass
import org.matrix.android.sdk.internal.di.MoshiProvider import org.matrix.android.sdk.internal.di.MoshiProvider
/** /**
* Class representing an room key request body content * Class representing an room key request body content.
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class RoomKeyRequestBody( data class RoomKeyRequestBody(

View file

@ -20,7 +20,7 @@ import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonClass
/** /**
* Class representing a room key request content * Class representing a room key request content.
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class RoomKeyShareRequest( data class RoomKeyShareRequest(

View file

@ -20,7 +20,7 @@ import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonClass
/** /**
* Class representing a room key request content * Class representing a room key request content.
*/ */
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class SecretShareRequest( data class SecretShareRequest(

View file

@ -22,7 +22,7 @@ import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_SAS
import java.util.UUID import java.util.UUID
/** /**
* Stores current pending verification requests * Stores current pending verification requests.
*/ */
data class PendingVerificationRequest( data class PendingVerificationRequest(
val ageLocalTs: Long, val ageLocalTs: Long,
@ -45,7 +45,7 @@ data class PendingVerificationRequest(
val isFinished: Boolean = isSuccessful || cancelConclusion != null val isFinished: Boolean = isSuccessful || cancelConclusion != null
/** /**
* SAS is supported if I support it and the other party support it * SAS is supported if I support it and the other party support it.
*/ */
fun isSasSupported(): Boolean { fun isSasSupported(): Boolean {
return requestInfo?.methods?.contains(VERIFICATION_METHOD_SAS).orFalse() && return requestInfo?.methods?.contains(VERIFICATION_METHOD_SAS).orFalse() &&
@ -53,7 +53,7 @@ data class PendingVerificationRequest(
} }
/** /**
* Other can show QR code if I can scan QR code and other can show QR code * Other can show QR code if I can scan QR code and other can show QR code.
*/ */
fun otherCanShowQrCode(): Boolean { fun otherCanShowQrCode(): Boolean {
return if (isIncoming) { return if (isIncoming) {
@ -66,7 +66,7 @@ data class PendingVerificationRequest(
} }
/** /**
* Other can scan QR code if I can show QR code and other can scan QR code * Other can scan QR code if I can show QR code and other can scan QR code.
*/ */
fun otherCanScanQrCode(): Boolean { fun otherCanScanQrCode(): Boolean {
return if (isIncoming) { return if (isIncoming) {

View file

@ -19,22 +19,22 @@ package org.matrix.android.sdk.api.session.crypto.verification
interface QrCodeVerificationTransaction : VerificationTransaction { interface QrCodeVerificationTransaction : VerificationTransaction {
/** /**
* To use to display a qr code, for the other user to scan it * To use to display a qr code, for the other user to scan it.
*/ */
val qrCodeText: String? val qrCodeText: String?
/** /**
* Call when you have scan the other user QR code * Call when you have scan the other user QR code.
*/ */
fun userHasScannedOtherQrCode(otherQrCodeText: String) fun userHasScannedOtherQrCode(otherQrCodeText: String)
/** /**
* Call when you confirm that other user has scanned your QR code * Call when you confirm that other user has scanned your QR code.
*/ */
fun otherUserScannedMyQrCode() fun otherUserScannedMyQrCode()
/** /**
* Call when you do not confirm that other user has scanned your QR code * Call when you do not confirm that other user has scanned your QR code.
*/ */
fun otherUserDidNotScannedMyQrCode() fun otherUserDidNotScannedMyQrCode()
} }

View file

@ -28,7 +28,7 @@ interface SasVerificationTransaction : VerificationTransaction {
/** /**
* To be called by the client when the user has verified that * To be called by the client when the user has verified that
* both short codes do match * both short codes do match.
*/ */
fun userHasVerifiedShortCode() fun userHasVerifiedShortCode()

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