diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 22b3a1727d..9517a4f3a7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -67,4 +67,4 @@ jobs: path: | vector/build/outputs/apk/*/release/*.apk -# TODO: add exodus checks +# TODO add exodus checks diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000000..b6333c5940 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,22 @@ +name: Documentation + +on: + push: + branches: [ develop ] + +jobs: + docs: + name: Generate and publish Android Matrix SDK documentation + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Build docs + run: ./gradlew dokkaHtml + + - name: Deploy docs + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./matrix-sdk-android/build/dokka/html diff --git a/.github/workflows/post-pr.yml b/.github/workflows/post-pr.yml index 553146acc1..8fe51eb8d5 100644 --- a/.github/workflows/post-pr.yml +++ b/.github/workflows/post-pr.yml @@ -285,7 +285,7 @@ jobs: codecov-units: name: Unit tests with code coverage needs: should-i-run - runs-on: macos-latest + runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 @@ -318,12 +318,12 @@ jobs: - integration-tests - ui-tests - codecov-units - if: always() && (needs.should-i-run.status == 'success' ) && ((needs.codecov-units.status != 'success' ) || (needs.ui-tests.status != 'success') || (needs.integration-tests.status != 'success')) + if: always() && (needs.should-i-run.result == 'success' ) && ((needs.codecov-units.result != 'success' ) || (needs.ui-tests.result != 'success') || (needs.integration-tests.result != 'success')) # No concurrency required, runs every time on a schedule. steps: - uses: michaelkaye/matrix-hookshot-action@v1.0.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} 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}}" - 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 }}
{{icon conclusion}} {{name}} {{conclusion}} at {{completed_at}} [details]{{/if}}{{/with}}{{/each}}" + text_template: "Post-merge validation of ${{ github.head_ref }} into ${{ github.base_ref }} by ${{ github.event.pull_request.merged_by.login }} 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.pull_request.merged_by.login }} failed: {{#each job_statuses }}{{#with this }}{{#if completed }}
{{icon conclusion}} {{name}} {{conclusion}} at {{completed_at}} [details]{{/if}}{{/with}}{{/each}}" diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index dee596980f..a97d532644 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -14,6 +14,16 @@ jobs: - name: Run code quality check suite 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: name: Kotlin Linter @@ -147,3 +157,23 @@ jobs: name: release-lint-report-${{ matrix.target }} path: | 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 diff --git a/.github/workflows/sonarqube.yml b/.github/workflows/sonarqube.yml index ea4c3d594b..6809751d91 100644 --- a/.github/workflows/sonarqube.yml +++ b/.github/workflows/sonarqube.yml @@ -71,7 +71,7 @@ jobs: needs: - sonarqube - codecov-units - if: always() && (needs.sonarqube.result != "success" || needs.codecov-units.result != "success") + if: always() && (needs.sonarqube.result != 'success' || needs.codecov-units.result != 'success') steps: - uses: michaelkaye/matrix-hookshot-action@v1.0.0 with: diff --git a/CHANGES.md b/CHANGES.md index 8e42149545..c8677b1ae4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,44 @@ +Changes in Element v1.4.16 (2022-05-17) +======================================= + +Features ✨ +---------- + - Use key backup before requesting keys + refactor & improvement of key request/forward ([#5494](https://github.com/vector-im/element-android/issues/5494)) + - Screen sharing over WebRTC ([#5911](https://github.com/vector-im/element-android/issues/5911)) + - Allow using the latest user Avatar and name for all messages in the timeline ([#5932](https://github.com/vector-im/element-android/issues/5932)) + - Added themed launch icons for Android 13 ([#5936](https://github.com/vector-im/element-android/issues/5936)) + - Add presence indicator busy and away. ([#6047](https://github.com/vector-im/element-android/issues/6047)) + +Bugfixes 🐛 +---------- + - Changed copy and list order in member profile screen. ([#5825](https://github.com/vector-im/element-android/issues/5825)) + - Fix for audio only being received in one direction after an un-hold during a sip call. ([#5865](https://github.com/vector-im/element-android/issues/5865)) + - Desynchronized 4S | Megolm backup causing Unusable backup ([#5906](https://github.com/vector-im/element-android/issues/5906)) + - If animations are disable on the System, chat effects and confetti will be disabled too ([#5941](https://github.com/vector-im/element-android/issues/5941)) + - Multiple threads improvement (mainly UI) ([#5959](https://github.com/vector-im/element-android/issues/5959)) + +Improved Documentation 📚 +------------------------ + - Note public_baseurl requirement in integration tests documentation. ([#5973](https://github.com/vector-im/element-android/issues/5973)) + +SDK API changes ⚠️ +------------------ + - - New API to enable/disable key forwarding CryptoService#enableKeyGossiping() + - New API to limit room key request only to own devices MXCryptoConfig#limitRoomKeyRequestsToMyDevices + - Event Trail API has changed, now using AuditTrail events + - New API to manually accept an incoming key request CryptoService#manuallyAcceptRoomKeyRequest() ([#5559](https://github.com/vector-im/element-android/issues/5559)) + - 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()` ([#5887](https://github.com/vector-im/element-android/issues/5887)) + - Including SSL/TLS error handing when doing WellKnown lookups without a custom HomeServerConnectionConfig ([#5965](https://github.com/vector-im/element-android/issues/5965)) + +Other changes +------------- + - Improve threads rendering in the main timeline ([#5151](https://github.com/vector-im/element-android/issues/5151)) + - Reformatted project code ([#5953](https://github.com/vector-im/element-android/issues/5953)) + - Update check for server-side threads support to match spec. ([#5997](https://github.com/vector-im/element-android/issues/5997)) + - Setup detekt ([#6038](https://github.com/vector-im/element-android/issues/6038)) + - Notify the user for each new message ([#46312](https://github.com/vector-im/element-android/issues/46312)) + + Changes in Element v1.4.14 (2022-05-05) ======================================= diff --git a/build.gradle b/build.gradle index fa26638015..8553428b49 100644 --- a/build.gradle +++ b/build.gradle @@ -30,14 +30,17 @@ buildscript { classpath "com.likethesalad.android:stem-plugin:2.0.0" classpath 'org.owasp:dependency-check-gradle:7.1.0.1' 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 // in the individual module build.gradle files } } -// ktlint Plugin plugins { + // ktlint Plugin id "org.jlleitschuh.gradle.ktlint" version "10.3.0" + // Detekt + id "io.gitlab.arturbosch.detekt" version "1.20.0" } // https://github.com/jeremylong/DependencyCheck @@ -52,6 +55,7 @@ dependencyCheck { allprojects { apply plugin: "org.jlleitschuh.gradle.ktlint" + apply plugin: "io.gitlab.arturbosch.detekt" repositories { // Do not use `mavenCentral()`, it prevents Dependabot from working properly @@ -119,7 +123,7 @@ allprojects { // display the corresponding rule verbose = true disabledRules = [ - // TODO: Re-enable these 4 rules after reformatting project + // TODO Re-enable these 4 rules after reformatting project "indent", "experimental:argument-list-wrapping", "max-line-length", @@ -140,6 +144,15 @@ allprojects { "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) { diff --git a/changelog.d/46312.misc b/changelog.d/46312.misc deleted file mode 100644 index 5e0112372f..0000000000 --- a/changelog.d/46312.misc +++ /dev/null @@ -1 +0,0 @@ -Notify the user for each new message diff --git a/changelog.d/5151.misc b/changelog.d/5151.misc deleted file mode 100644 index b785c4229c..0000000000 --- a/changelog.d/5151.misc +++ /dev/null @@ -1 +0,0 @@ -Improve threads rendering in the main timeline diff --git a/changelog.d/5658.feature b/changelog.d/5658.feature new file mode 100644 index 0000000000..ba41a03207 --- /dev/null +++ b/changelog.d/5658.feature @@ -0,0 +1 @@ +Space explore screen changes: removed space card, added rooms filtering diff --git a/changelog.d/5689.wip b/changelog.d/5689.wip new file mode 100644 index 0000000000..ccea1ec541 --- /dev/null +++ b/changelog.d/5689.wip @@ -0,0 +1 @@ +[Live location sharing] Update message in timeline during the live diff --git a/changelog.d/5724.sdk b/changelog.d/5724.sdk new file mode 100644 index 0000000000..5a0a37fe31 --- /dev/null +++ b/changelog.d/5724.sdk @@ -0,0 +1 @@ +- Notifies other devices when a verification request sent from an Android device is accepted.` diff --git a/changelog.d/5728.misc b/changelog.d/5728.misc new file mode 100644 index 0000000000..6e463fa76f --- /dev/null +++ b/changelog.d/5728.misc @@ -0,0 +1 @@ +leaving space experience changed to be aligned with iOS diff --git a/changelog.d/5911.feature b/changelog.d/5911.feature deleted file mode 100644 index 368a3b4056..0000000000 --- a/changelog.d/5911.feature +++ /dev/null @@ -1 +0,0 @@ -Screen sharing over WebRTC diff --git a/changelog.d/5941.bugfix b/changelog.d/5941.bugfix deleted file mode 100644 index 0ea17668c6..0000000000 --- a/changelog.d/5941.bugfix +++ /dev/null @@ -1 +0,0 @@ -If animations are disable on the System, chat effects and confetti will be disabled too diff --git a/changelog.d/5953.misc b/changelog.d/5953.misc deleted file mode 100644 index a3ad5dae93..0000000000 --- a/changelog.d/5953.misc +++ /dev/null @@ -1 +0,0 @@ -Reformatted project code diff --git a/changelog.d/5965.sdk b/changelog.d/5965.sdk deleted file mode 100644 index 5bb6c3aac4..0000000000 --- a/changelog.d/5965.sdk +++ /dev/null @@ -1 +0,0 @@ -Including SSL/TLS error handing when doing WellKnown lookups without a custom HomeServerConnectionConfig diff --git a/changelog.d/6025.misc b/changelog.d/6025.misc new file mode 100644 index 0000000000..2900796792 --- /dev/null +++ b/changelog.d/6025.misc @@ -0,0 +1 @@ +@Ignore a number of tests that are currently failing in CI. diff --git a/changelog.d/6041.misc b/changelog.d/6041.misc new file mode 100644 index 0000000000..50378ea3fd --- /dev/null +++ b/changelog.d/6041.misc @@ -0,0 +1 @@ +Remove ShortcutBadger lib and usage (it was dead code) diff --git a/changelog.d/6095.bugfix b/changelog.d/6095.bugfix new file mode 100644 index 0000000000..11110bfa08 --- /dev/null +++ b/changelog.d/6095.bugfix @@ -0,0 +1 @@ +Correct .well-known/matrix/client handling for server_names which include ports. diff --git a/dependencies.gradle b/dependencies.gradle index 2f5a3fd01a..10f9539e5a 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -9,8 +9,8 @@ ext.versions = [ def gradle = "7.2.0" // Ref: https://kotlinlang.org/releases.html -def kotlin = "1.6.0" -def kotlinCoroutines = "1.6.0" +def kotlin = "1.6.21" +def kotlinCoroutines = "1.6.1" def dagger = "2.42" def retrofit = "2.9.0" def arrow = "0.8.2" @@ -26,7 +26,7 @@ def jjwt = "0.11.5" def vanniktechEmoji = "0.9.0" // Testing -def mockk = "1.12.3" +def mockk = "1.12.4" def espresso = "3.4.0" def androidxTest = "1.4.0" def androidxOrchestrator = "1.4.1" @@ -53,7 +53,7 @@ ext.libs = [ 'constraintLayout' : "androidx.constraintlayout:constraintlayout:2.1.3", 'work' : "androidx.work:work-runtime-ktx:2.7.1", 'autoFill' : "androidx.autofill:autofill:1.1.0", - 'preferenceKtx' : "androidx.preference:preference-ktx:1.1.1", + 'preferenceKtx' : "androidx.preference:preference-ktx:1.2.0", 'junit' : "androidx.test.ext:junit:1.1.3", 'lifecycleCommon' : "androidx.lifecycle:lifecycle-common:$lifecycle", 'lifecycleLivedata' : "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle", diff --git a/dependencies_groups.gradle b/dependencies_groups.gradle index 8422e05930..59cefe7e89 100644 --- a/dependencies_groups.gradle +++ b/dependencies_groups.gradle @@ -123,6 +123,7 @@ ext.groups = [ 'io.github.detekt.sarif4k', 'io.github.microutils', 'io.github.reactivecircus.flowbinding', + 'io.gitlab.arturbosch.detekt', 'io.grpc', 'io.jsonwebtoken', 'io.kindedj', @@ -140,7 +141,6 @@ ext.groups = [ 'jline', 'jp.wasabeef', 'junit', - 'me.leolin', 'me.saket', 'net.bytebuddy', 'net.java', @@ -195,6 +195,7 @@ ext.groups = [ 'org.testng', 'org.threeten', 'org.webjars', + 'org.yaml', 'ru.noties', 'xerces', 'xml-apis', diff --git a/docs/add_threePids.md b/docs/add_threePids.md index 89fc92f329..6fb0aff426 100644 --- a/docs/add_threePids.md +++ b/docs/add_threePids.md @@ -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: https://homeserver.org/_matrix/client/unstable/add_threepid/email/submit_token?token=WUnEhQAmJrXupdEbXgdWvnVIKaGYZFsU&client_secret=TixzvOnw7nLEUdiQEmkHzkXKrY4HhiGh&sid=bxyDHuJKsdkjMlTJ diff --git a/docs/integration_tests.md b/docs/integration_tests.md index 0fa1998499..e79f966d1f 100644 --- a/docs/integration_tests.md +++ b/docs/integration_tests.md @@ -43,14 +43,17 @@ virtualenv -p python3 env source env/bin/activate pip install -e . 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 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. ## 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. +### 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 You can try using diff --git a/docs/pull_request.md b/docs/pull_request.md index 4775f292ee..94f8f3b6d8 100644 --- a/docs/pull_request.md +++ b/docs/pull_request.md @@ -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. +##### 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 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 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 @@ -234,4 +247,4 @@ Also "Resolve conversation" should probably be hit by the creator of the convers PR submitter is responsible of the incoming change. PR reviewers who approved the PR take a part of responsibility on the code which will land to develop, and then be used by our users, and the user of our forks. -That said, bug may still be merged on `develop`, this is still acceptable of course. In this case, please make sure an issue is created and correctly labelled. Ideally, such issues should be fixed before the next release candidate, i.e. with a higher priority. But as we release the application every 10 working days, it can be hard to fix every bugs. That's why PR should be fully tested and reviewed before being merge and we should never comment code review remark with "will be handled later", or similar comments. \ No newline at end of file +That said, bug may still be merged on `develop`, this is still acceptable of course. In this case, please make sure an issue is created and correctly labelled. Ideally, such issues should be fixed before the next release candidate, i.e. with a higher priority. But as we release the application every 10 working days, it can be hard to fix every bugs. That's why PR should be fully tested and reviewed before being merge and we should never comment code review remark with "will be handled later", or similar comments. diff --git a/fastlane/metadata/android/cs-CZ/changelogs/40104120.txt b/fastlane/metadata/android/cs-CZ/changelogs/40104120.txt new file mode 100644 index 0000000000..7867646fe5 --- /dev/null +++ b/fastlane/metadata/android/cs-CZ/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Hlavní změny v této verzi: Umožňuje uživatelům zobrazovat se offline a přidává zvukový přehrávač pro zvukové přílohy +Úplný seznam změn: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/cs-CZ/changelogs/40104130.txt b/fastlane/metadata/android/cs-CZ/changelogs/40104130.txt new file mode 100644 index 0000000000..7867646fe5 --- /dev/null +++ b/fastlane/metadata/android/cs-CZ/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Hlavní změny v této verzi: Umožňuje uživatelům zobrazovat se offline a přidává zvukový přehrávač pro zvukové přílohy +Úplný seznam změn: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/de-DE/changelogs/40104060.txt b/fastlane/metadata/android/de-DE/changelogs/40104060.txt new file mode 100644 index 0000000000..17cfdd26cc --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/40104060.txt @@ -0,0 +1,2 @@ +Hauptänderungen: Threads sind jetzt schneller, Fehlerbehebungen. +Alle Änderungen: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/de-DE/changelogs/40104070.txt b/fastlane/metadata/android/de-DE/changelogs/40104070.txt new file mode 100644 index 0000000000..30da225add --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/40104070.txt @@ -0,0 +1,2 @@ +Änderungen: Fehlerbehebungen +Alle Änderungen: https://github.com/vector-im/element-android/releases/tag/v1.4.7 diff --git a/fastlane/metadata/android/de-DE/changelogs/40104080.txt b/fastlane/metadata/android/de-DE/changelogs/40104080.txt new file mode 100644 index 0000000000..902e1d27f7 --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/40104080.txt @@ -0,0 +1,2 @@ +Hauptänderungen: Schnellere Threads, Fehlerbehebungen. +Alle Änderungen: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/de-DE/changelogs/40104100.txt b/fastlane/metadata/android/de-DE/changelogs/40104100.txt new file mode 100644 index 0000000000..2de5ec1d6a --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/40104100.txt @@ -0,0 +1,2 @@ +Hauptänderungen: Scrollen in Sprachnachrichten, Fehlerbehebungen. +Alle Änderungen: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/de-DE/changelogs/40104110.txt b/fastlane/metadata/android/de-DE/changelogs/40104110.txt new file mode 100644 index 0000000000..bde9f04e11 --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/40104110.txt @@ -0,0 +1,2 @@ +Änderungen: Fehlerbehebungen und Stabilitätsverbesserungen +Alle Änderungen: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/de-DE/changelogs/40104120.txt b/fastlane/metadata/android/de-DE/changelogs/40104120.txt new file mode 100644 index 0000000000..e0ce944874 --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Hauptänderungen: Nutzer können ihren Status auf „Offline“ setzen, Gesendete Audiodateien können nun in der App abgespielt werden +Alle Änderungen: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/de-DE/changelogs/40104130.txt b/fastlane/metadata/android/de-DE/changelogs/40104130.txt new file mode 100644 index 0000000000..e0ce944874 --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Hauptänderungen: Nutzer können ihren Status auf „Offline“ setzen, Gesendete Audiodateien können nun in der App abgespielt werden +Alle Änderungen: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/en-US/changelogs/40104160.txt b/fastlane/metadata/android/en-US/changelogs/40104160.txt new file mode 100644 index 0000000000..6e37a4ae7f --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/40104160.txt @@ -0,0 +1,2 @@ +Main changes in this version: Better management of encrypted messages. Various bug fixes and stability improvements. +Full changelog: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/et/changelogs/40104120.txt b/fastlane/metadata/android/et/changelogs/40104120.txt new file mode 100644 index 0000000000..1a7d3ae979 --- /dev/null +++ b/fastlane/metadata/android/et/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Põhilised muutused selles versioonis: kasutajate võrguolekud ning helisõnumite esitaja. +Kogu ingliskeelne muudatuste logi: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/et/changelogs/40104130.txt b/fastlane/metadata/android/et/changelogs/40104130.txt new file mode 100644 index 0000000000..1a7d3ae979 --- /dev/null +++ b/fastlane/metadata/android/et/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Põhilised muutused selles versioonis: kasutajate võrguolekud ning helisõnumite esitaja. +Kogu ingliskeelne muudatuste logi: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/fa/changelogs/40104120.txt b/fastlane/metadata/android/fa/changelogs/40104120.txt new file mode 100644 index 0000000000..4f730e52dc --- /dev/null +++ b/fastlane/metadata/android/fa/changelogs/40104120.txt @@ -0,0 +1,2 @@ +تغییرات عمده در این نگارش: اجازه به کاربران برای برون‌خط ظاهر شدن و افزودن یک پخش‌کنندهٔ صدا برای پیوست‌های صوتی +گزارش دگرگونی کامل: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/fa/changelogs/40104130.txt b/fastlane/metadata/android/fa/changelogs/40104130.txt new file mode 100644 index 0000000000..4f730e52dc --- /dev/null +++ b/fastlane/metadata/android/fa/changelogs/40104130.txt @@ -0,0 +1,2 @@ +تغییرات عمده در این نگارش: اجازه به کاربران برای برون‌خط ظاهر شدن و افزودن یک پخش‌کنندهٔ صدا برای پیوست‌های صوتی +گزارش دگرگونی کامل: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/id/changelogs/40104120.txt b/fastlane/metadata/android/id/changelogs/40104120.txt new file mode 100644 index 0000000000..ce1a4a4d84 --- /dev/null +++ b/fastlane/metadata/android/id/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Perubahan utama dalam versi ini: Diperbolehkan pengguna untuk terlihat luring dan ditambahkan sebuah pemain audio untuk lampiran audio +Catatan perubahan lanjutan: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/id/changelogs/40104130.txt b/fastlane/metadata/android/id/changelogs/40104130.txt new file mode 100644 index 0000000000..ce1a4a4d84 --- /dev/null +++ b/fastlane/metadata/android/id/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Perubahan utama dalam versi ini: Diperbolehkan pengguna untuk terlihat luring dan ditambahkan sebuah pemain audio untuk lampiran audio +Catatan perubahan lanjutan: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/it-IT/changelogs/40104120.txt b/fastlane/metadata/android/it-IT/changelogs/40104120.txt new file mode 100644 index 0000000000..fa015ae564 --- /dev/null +++ b/fastlane/metadata/android/it-IT/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Modifiche principali in questa versione: consente agli utenti di apparire offline e aggiunge un player audio per gli allegati audio +Cronologia completa: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/it-IT/changelogs/40104130.txt b/fastlane/metadata/android/it-IT/changelogs/40104130.txt new file mode 100644 index 0000000000..fa015ae564 --- /dev/null +++ b/fastlane/metadata/android/it-IT/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Modifiche principali in questa versione: consente agli utenti di apparire offline e aggiunge un player audio per gli allegati audio +Cronologia completa: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/lo/changelogs/40100100.txt b/fastlane/metadata/android/lo-LA/changelogs/40100100.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100100.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100100.txt diff --git a/fastlane/metadata/android/lo/changelogs/40100110.txt b/fastlane/metadata/android/lo-LA/changelogs/40100110.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100110.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100110.txt diff --git a/fastlane/metadata/android/lo/changelogs/40100120.txt b/fastlane/metadata/android/lo-LA/changelogs/40100120.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100120.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100120.txt diff --git a/fastlane/metadata/android/lo/changelogs/40100130.txt b/fastlane/metadata/android/lo-LA/changelogs/40100130.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100130.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100130.txt diff --git a/fastlane/metadata/android/lo/changelogs/40100140.txt b/fastlane/metadata/android/lo-LA/changelogs/40100140.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100140.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100140.txt diff --git a/fastlane/metadata/android/lo/changelogs/40100150.txt b/fastlane/metadata/android/lo-LA/changelogs/40100150.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100150.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100150.txt diff --git a/fastlane/metadata/android/lo/changelogs/40100160.txt b/fastlane/metadata/android/lo-LA/changelogs/40100160.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100160.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100160.txt diff --git a/fastlane/metadata/android/lo/changelogs/40100170.txt b/fastlane/metadata/android/lo-LA/changelogs/40100170.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40100170.txt rename to fastlane/metadata/android/lo-LA/changelogs/40100170.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101000.txt b/fastlane/metadata/android/lo-LA/changelogs/40101000.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101000.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101000.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101010.txt b/fastlane/metadata/android/lo-LA/changelogs/40101010.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101010.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101010.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101020.txt b/fastlane/metadata/android/lo-LA/changelogs/40101020.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101020.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101020.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101030.txt b/fastlane/metadata/android/lo-LA/changelogs/40101030.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101030.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101030.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101040.txt b/fastlane/metadata/android/lo-LA/changelogs/40101040.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101040.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101040.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101050.txt b/fastlane/metadata/android/lo-LA/changelogs/40101050.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101050.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101050.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101060.txt b/fastlane/metadata/android/lo-LA/changelogs/40101060.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101060.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101060.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101070.txt b/fastlane/metadata/android/lo-LA/changelogs/40101070.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101070.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101070.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101080.txt b/fastlane/metadata/android/lo-LA/changelogs/40101080.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101080.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101080.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101090.txt b/fastlane/metadata/android/lo-LA/changelogs/40101090.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101090.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101090.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101100.txt b/fastlane/metadata/android/lo-LA/changelogs/40101100.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101100.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101100.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101110.txt b/fastlane/metadata/android/lo-LA/changelogs/40101110.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101110.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101110.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101120.txt b/fastlane/metadata/android/lo-LA/changelogs/40101120.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101120.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101120.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101130.txt b/fastlane/metadata/android/lo-LA/changelogs/40101130.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101130.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101130.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101140.txt b/fastlane/metadata/android/lo-LA/changelogs/40101140.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101140.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101140.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101150.txt b/fastlane/metadata/android/lo-LA/changelogs/40101150.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101150.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101150.txt diff --git a/fastlane/metadata/android/lo/changelogs/40101160.txt b/fastlane/metadata/android/lo-LA/changelogs/40101160.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40101160.txt rename to fastlane/metadata/android/lo-LA/changelogs/40101160.txt diff --git a/fastlane/metadata/android/lo/changelogs/40102000.txt b/fastlane/metadata/android/lo-LA/changelogs/40102000.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40102000.txt rename to fastlane/metadata/android/lo-LA/changelogs/40102000.txt diff --git a/fastlane/metadata/android/lo/changelogs/40102010.txt b/fastlane/metadata/android/lo-LA/changelogs/40102010.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40102010.txt rename to fastlane/metadata/android/lo-LA/changelogs/40102010.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103000.txt b/fastlane/metadata/android/lo-LA/changelogs/40103000.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103000.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103000.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103010.txt b/fastlane/metadata/android/lo-LA/changelogs/40103010.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103010.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103010.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103020.txt b/fastlane/metadata/android/lo-LA/changelogs/40103020.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103020.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103020.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103030.txt b/fastlane/metadata/android/lo-LA/changelogs/40103030.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103030.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103030.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103040.txt b/fastlane/metadata/android/lo-LA/changelogs/40103040.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103040.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103040.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103050.txt b/fastlane/metadata/android/lo-LA/changelogs/40103050.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103050.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103050.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103060.txt b/fastlane/metadata/android/lo-LA/changelogs/40103060.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103060.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103060.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103070.txt b/fastlane/metadata/android/lo-LA/changelogs/40103070.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103070.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103070.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103080.txt b/fastlane/metadata/android/lo-LA/changelogs/40103080.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103080.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103080.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103090.txt b/fastlane/metadata/android/lo-LA/changelogs/40103090.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103090.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103090.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103100.txt b/fastlane/metadata/android/lo-LA/changelogs/40103100.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103100.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103100.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103110.txt b/fastlane/metadata/android/lo-LA/changelogs/40103110.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103110.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103110.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103120.txt b/fastlane/metadata/android/lo-LA/changelogs/40103120.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103120.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103120.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103130.txt b/fastlane/metadata/android/lo-LA/changelogs/40103130.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103130.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103130.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103140.txt b/fastlane/metadata/android/lo-LA/changelogs/40103140.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103140.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103140.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103150.txt b/fastlane/metadata/android/lo-LA/changelogs/40103150.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103150.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103150.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103160.txt b/fastlane/metadata/android/lo-LA/changelogs/40103160.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103160.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103160.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103170.txt b/fastlane/metadata/android/lo-LA/changelogs/40103170.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103170.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103170.txt diff --git a/fastlane/metadata/android/lo/changelogs/40103180.txt b/fastlane/metadata/android/lo-LA/changelogs/40103180.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40103180.txt rename to fastlane/metadata/android/lo-LA/changelogs/40103180.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104000.txt b/fastlane/metadata/android/lo-LA/changelogs/40104000.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104000.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104000.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104020.txt b/fastlane/metadata/android/lo-LA/changelogs/40104020.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104020.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104020.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104040.txt b/fastlane/metadata/android/lo-LA/changelogs/40104040.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104040.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104040.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104060.txt b/fastlane/metadata/android/lo-LA/changelogs/40104060.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104060.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104060.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104070.txt b/fastlane/metadata/android/lo-LA/changelogs/40104070.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104070.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104070.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104080.txt b/fastlane/metadata/android/lo-LA/changelogs/40104080.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104080.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104080.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104100.txt b/fastlane/metadata/android/lo-LA/changelogs/40104100.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104100.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104100.txt diff --git a/fastlane/metadata/android/lo/changelogs/40104110.txt b/fastlane/metadata/android/lo-LA/changelogs/40104110.txt similarity index 100% rename from fastlane/metadata/android/lo/changelogs/40104110.txt rename to fastlane/metadata/android/lo-LA/changelogs/40104110.txt diff --git a/fastlane/metadata/android/lo-LA/changelogs/40104120.txt b/fastlane/metadata/android/lo-LA/changelogs/40104120.txt new file mode 100644 index 0000000000..36c6d678f7 --- /dev/null +++ b/fastlane/metadata/android/lo-LA/changelogs/40104120.txt @@ -0,0 +1,2 @@ +ການປ່ຽນແປງຫຼັກໃນສະບັບນີ້: ໃຫ້ຜູ້ໃຊ້ສາມາດສະແດງຕົວເປັນ offline ແລະສາມາດຫຼິ້ນສຽງໄດ້ສຳລັບການແນບສຽງ +ບັນທຶກການປ່ຽນແປງສະບັບເຕັມ: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/lo-LA/changelogs/40104130.txt b/fastlane/metadata/android/lo-LA/changelogs/40104130.txt new file mode 100644 index 0000000000..36c6d678f7 --- /dev/null +++ b/fastlane/metadata/android/lo-LA/changelogs/40104130.txt @@ -0,0 +1,2 @@ +ການປ່ຽນແປງຫຼັກໃນສະບັບນີ້: ໃຫ້ຜູ້ໃຊ້ສາມາດສະແດງຕົວເປັນ offline ແລະສາມາດຫຼິ້ນສຽງໄດ້ສຳລັບການແນບສຽງ +ບັນທຶກການປ່ຽນແປງສະບັບເຕັມ: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/lo/full_description.txt b/fastlane/metadata/android/lo-LA/full_description.txt similarity index 100% rename from fastlane/metadata/android/lo/full_description.txt rename to fastlane/metadata/android/lo-LA/full_description.txt diff --git a/fastlane/metadata/android/lo/short_description.txt b/fastlane/metadata/android/lo-LA/short_description.txt similarity index 100% rename from fastlane/metadata/android/lo/short_description.txt rename to fastlane/metadata/android/lo-LA/short_description.txt diff --git a/fastlane/metadata/android/lo/title.txt b/fastlane/metadata/android/lo-LA/title.txt similarity index 100% rename from fastlane/metadata/android/lo/title.txt rename to fastlane/metadata/android/lo-LA/title.txt diff --git a/fastlane/metadata/android/pl-PL/changelogs/40103050.txt b/fastlane/metadata/android/pl-PL/changelogs/40103050.txt new file mode 100644 index 0000000000..b81d5ef037 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40103050.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Dodanie obsługi obecności, dla pokoju wiadomości bezpośrednich (uwaga: obecność jest wyłączona na matrix.org). Dodaje ponownie obsługę Androida Auto. + Pełna lista zmian: https://github.com/vector-im/element-android/releases/tag/v1.3.5 diff --git a/fastlane/metadata/android/pl-PL/changelogs/40104100.txt b/fastlane/metadata/android/pl-PL/changelogs/40104100.txt new file mode 100644 index 0000000000..3d1efbc1d2 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40104100.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Przewijanie w wiadomości głosowej. Różne poprawki błędów i ulepszenia stabilności. + Pełna lista zmian: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/pl-PL/changelogs/40104110.txt b/fastlane/metadata/android/pl-PL/changelogs/40104110.txt new file mode 100644 index 0000000000..6ae86f3c9b --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40104110.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Różne poprawki błędów i ulepszenia stabilności. + Pełna lista zmian: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/pl-PL/changelogs/40104120.txt b/fastlane/metadata/android/pl-PL/changelogs/40104120.txt new file mode 100644 index 0000000000..bd995ad5e5 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Pozwala użytkownikom pojawiać się w trybie offline i dodaje odtwarzacz audio do załączników audio +Pełna lista zmian: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/pl-PL/changelogs/40104130.txt b/fastlane/metadata/android/pl-PL/changelogs/40104130.txt new file mode 100644 index 0000000000..bd995ad5e5 --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Główne zmiany w tej wersji: Pozwala użytkownikom pojawiać się w trybie offline i dodaje odtwarzacz audio do załączników audio +Pełna lista zmian: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/pl-PL/title.txt b/fastlane/metadata/android/pl-PL/title.txt index 907f907f99..df4d9b71f4 100644 --- a/fastlane/metadata/android/pl-PL/title.txt +++ b/fastlane/metadata/android/pl-PL/title.txt @@ -1 +1 @@ -Element +Element - komunikator diff --git a/fastlane/metadata/android/pt-BR/changelogs/40104120.txt b/fastlane/metadata/android/pt-BR/changelogs/40104120.txt new file mode 100644 index 0000000000..f77d426d99 --- /dev/null +++ b/fastlane/metadata/android/pt-BR/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Principais mudanças nesta versão: Permite usuárias(os) aparecer offline e adiciona um tocador de áudio para anexos de áudio +Changelog completo: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/pt-BR/changelogs/40104130.txt b/fastlane/metadata/android/pt-BR/changelogs/40104130.txt new file mode 100644 index 0000000000..f77d426d99 --- /dev/null +++ b/fastlane/metadata/android/pt-BR/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Principais mudanças nesta versão: Permite usuárias(os) aparecer offline e adiciona um tocador de áudio para anexos de áudio +Changelog completo: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/sk/changelogs/40104120.txt b/fastlane/metadata/android/sk/changelogs/40104120.txt new file mode 100644 index 0000000000..2279ddc574 --- /dev/null +++ b/fastlane/metadata/android/sk/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Hlavné zmeny v tejto verzii: Umožňuje používateľom zobrazovať sa v režime offline a pridáva zvukový prehrávač pre zvukové prílohy +Úplný zoznam zmien: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/sk/changelogs/40104130.txt b/fastlane/metadata/android/sk/changelogs/40104130.txt new file mode 100644 index 0000000000..2279ddc574 --- /dev/null +++ b/fastlane/metadata/android/sk/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Hlavné zmeny v tejto verzii: Umožňuje používateľom zobrazovať sa v režime offline a pridáva zvukový prehrávač pre zvukové prílohy +Úplný zoznam zmien: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/sv-SE/changelogs/40104120.txt b/fastlane/metadata/android/sv-SE/changelogs/40104120.txt new file mode 100644 index 0000000000..6692768e1e --- /dev/null +++ b/fastlane/metadata/android/sv-SE/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Huvudsakliga ändringar i den här versionen: Låter användare visas offline och lägger till en ljudspelare för ljudbilagor +Full ändringslogg: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/sv-SE/changelogs/40104130.txt b/fastlane/metadata/android/sv-SE/changelogs/40104130.txt new file mode 100644 index 0000000000..6692768e1e --- /dev/null +++ b/fastlane/metadata/android/sv-SE/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Huvudsakliga ändringar i den här versionen: Låter användare visas offline och lägger till en ljudspelare för ljudbilagor +Full ändringslogg: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/uk/changelogs/40104120.txt b/fastlane/metadata/android/uk/changelogs/40104120.txt new file mode 100644 index 0000000000..aa075bd42e --- /dev/null +++ b/fastlane/metadata/android/uk/changelogs/40104120.txt @@ -0,0 +1,2 @@ +Основні зміни у цій версії: Дозволяє користувачам з’являтися в режимі офлайн та додає аудіопрогравач для аудіовкладень +Вичерпний перелік змін: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/uk/changelogs/40104130.txt b/fastlane/metadata/android/uk/changelogs/40104130.txt new file mode 100644 index 0000000000..aa075bd42e --- /dev/null +++ b/fastlane/metadata/android/uk/changelogs/40104130.txt @@ -0,0 +1,2 @@ +Основні зміни у цій версії: Дозволяє користувачам з’являтися в режимі офлайн та додає аудіопрогравач для аудіовкладень +Вичерпний перелік змін: https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/zh-TW/changelogs/40104120.txt b/fastlane/metadata/android/zh-TW/changelogs/40104120.txt new file mode 100644 index 0000000000..d3d48abab9 --- /dev/null +++ b/fastlane/metadata/android/zh-TW/changelogs/40104120.txt @@ -0,0 +1,2 @@ +此版本中的主要變動:允許使用者顯示為離線並為音訊附件新增音訊播放器 +完整的變更紀錄:https://github.com/vector-im/element-android/releases diff --git a/fastlane/metadata/android/zh-TW/changelogs/40104130.txt b/fastlane/metadata/android/zh-TW/changelogs/40104130.txt new file mode 100644 index 0000000000..d3d48abab9 --- /dev/null +++ b/fastlane/metadata/android/zh-TW/changelogs/40104130.txt @@ -0,0 +1,2 @@ +此版本中的主要變動:允許使用者顯示為離線並為音訊附件新增音訊播放器 +完整的變更紀錄:https://github.com/vector-im/element-android/releases diff --git a/library/core-utils/build.gradle b/library/core-utils/build.gradle index ad3a948808..d3afd8d29b 100644 --- a/library/core-utils/build.gradle +++ b/library/core-utils/build.gradle @@ -44,7 +44,7 @@ android { kotlinOptions { jvmTarget = "11" freeCompilerArgs += [ - "-Xopt-in=kotlin.RequiresOptIn" + "-opt-in=kotlin.RequiresOptIn" ] } } @@ -52,4 +52,4 @@ android { dependencies { implementation libs.androidx.appCompat implementation libs.jetbrains.coroutinesAndroid -} \ No newline at end of file +} diff --git a/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/EpoxyCharSequence.kt b/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/EpoxyCharSequence.kt index 77e2d58001..f0f01bc6ea 100644 --- a/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/EpoxyCharSequence.kt +++ b/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/EpoxyCharSequence.kt @@ -17,7 +17,7 @@ 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) { private val hash = charSequence.toString().hashCode() diff --git a/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/Extensions.kt b/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/Extensions.kt index ba0f0b9ad6..c52eaedbb7 100644 --- a/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/Extensions.kt +++ b/library/core-utils/src/main/java/im/vector/lib/core/utils/epoxy/charsequence/Extensions.kt @@ -17,6 +17,6 @@ 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) diff --git a/library/core-utils/src/main/java/im/vector/lib/core/utils/flow/TimingOperators.kt b/library/core-utils/src/main/java/im/vector/lib/core/utils/flow/TimingOperators.kt index 2efb439ace..aeb5ae7914 100644 --- a/library/core-utils/src/main/java/im/vector/lib/core/utils/flow/TimingOperators.kt +++ b/library/core-utils/src/main/java/im/vector/lib/core/utils/flow/TimingOperators.kt @@ -16,6 +16,7 @@ package im.vector.lib.core.utils.flow +import android.os.SystemClock import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.Channel @@ -68,10 +69,10 @@ fun Flow.chunk(durationInMillis: Long): Flow> { @ExperimentalCoroutinesApi fun Flow.throttleFirst(windowDuration: Long): Flow = flow { - var windowStartTime = System.currentTimeMillis() + var windowStartTime = SystemClock.elapsedRealtime() var emitted = false collect { value -> - val currentTime = System.currentTimeMillis() + val currentTime = SystemClock.elapsedRealtime() val delta = currentTime - windowStartTime if (delta >= windowDuration) { windowStartTime += delta / windowDuration * windowDuration diff --git a/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/ValueItem.kt b/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/ValueItem.kt index fac7099b37..66dfcc5dc3 100644 --- a/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/ValueItem.kt +++ b/library/jsonviewer/src/main/java/org/billcarsonfr/jsonviewer/ValueItem.kt @@ -18,11 +18,11 @@ package org.billcarsonfr.jsonviewer import android.content.ClipData import android.content.ClipboardManager -import android.content.Context import android.view.ContextMenu import android.view.View import android.widget.LinearLayout import android.widget.TextView +import androidx.core.content.getSystemService import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyHolder import com.airbnb.epoxy.EpoxyModelClass @@ -77,8 +77,7 @@ internal abstract class ValueItem : EpoxyModelWithHolder() { ) { if (copyValue != null) { val menuItem = menu?.add(R.string.copy_value) - val clipService = - v?.context?.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager + val clipService = v?.context?.getSystemService() menuItem?.setOnMenuItemClickListener { clipService?.setPrimaryClip(ClipData.newPlainText("", copyValue)) true diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/AudioPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/AudioPicker.kt index 739bda7004..3d6fdb96fc 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/AudioPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/AudioPicker.kt @@ -22,7 +22,7 @@ import im.vector.lib.multipicker.entity.MultiPickerAudioType import im.vector.lib.multipicker.utils.toMultiPickerAudioType /** - * Audio file picker implementation + * Audio file picker implementation. */ class AudioPicker : Picker() { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraPicker.kt index 785b9fae43..c4a2ebbea9 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraPicker.kt @@ -28,12 +28,12 @@ import im.vector.lib.multipicker.utils.createTemporaryMediaFile import im.vector.lib.multipicker.utils.toMultiPickerImageType /** - * Implementation of taking a photo with Camera + * Implementation of taking a photo with Camera. */ 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. */ fun startWithExpectingFile(context: Context, activityResultLauncher: ActivityResultLauncher): Uri { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraVideoPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraVideoPicker.kt index 59601b30d9..e042e2366a 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraVideoPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/CameraVideoPicker.kt @@ -28,12 +28,12 @@ import im.vector.lib.multipicker.utils.createTemporaryMediaFile import im.vector.lib.multipicker.utils.toMultiPickerVideoType /** - * Implementation of taking a video with Camera + * Implementation of taking a video with Camera. */ 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. */ fun startWithExpectingFile(context: Context, activityResultLauncher: ActivityResultLauncher): Uri { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/ContactPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/ContactPicker.kt index bb21196858..be83d2ea47 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/ContactPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/ContactPicker.kt @@ -26,7 +26,7 @@ import im.vector.lib.multipicker.entity.MultiPickerContactType import im.vector.lib.multipicker.utils.getColumnIndexOrNull /** - * Contact Picker implementation + * Contact Picker implementation. */ class ContactPicker : Picker() { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt index 2e3148c9de..13ef5aa637 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/FilePicker.kt @@ -32,7 +32,7 @@ import im.vector.lib.multipicker.utils.toMultiPickerImageType import im.vector.lib.multipicker.utils.toMultiPickerVideoType /** - * Implementation of selecting any type of files + * Implementation of selecting any type of files. */ class FilePicker : Picker() { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/ImagePicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/ImagePicker.kt index 4cc2352109..bc5a13558a 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/ImagePicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/ImagePicker.kt @@ -22,7 +22,7 @@ import im.vector.lib.multipicker.entity.MultiPickerImageType import im.vector.lib.multipicker.utils.toMultiPickerImageType /** - * Image Picker implementation + * Image Picker implementation. */ class ImagePicker : Picker() { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/MediaPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/MediaPicker.kt index c58abde694..db74dbf9ff 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/MediaPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/MediaPicker.kt @@ -24,7 +24,7 @@ import im.vector.lib.multipicker.utils.toMultiPickerImageType import im.vector.lib.multipicker.utils.toMultiPickerVideoType /** - * Image/Video Picker implementation + * Image/Video Picker implementation. */ class MediaPicker : Picker() { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt index 821c2f0d4c..e7883c9e53 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/MultiPicker.kt @@ -16,7 +16,7 @@ package im.vector.lib.multipicker -class MultiPicker { +class MultiPicker private constructor() { companion object Type { val IMAGE by lazy { MultiPicker() } diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/Picker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/Picker.kt index ba765a3b1d..8960f3228b 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/Picker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/Picker.kt @@ -24,7 +24,7 @@ import android.net.Uri import androidx.activity.result.ActivityResultLauncher /** - * Abstract class to provide all types of Pickers + * Abstract class to provide all types of Pickers. */ abstract class Picker { diff --git a/library/multipicker/src/main/java/im/vector/lib/multipicker/VideoPicker.kt b/library/multipicker/src/main/java/im/vector/lib/multipicker/VideoPicker.kt index 6b6bc52c1b..89bb1af6aa 100644 --- a/library/multipicker/src/main/java/im/vector/lib/multipicker/VideoPicker.kt +++ b/library/multipicker/src/main/java/im/vector/lib/multipicker/VideoPicker.kt @@ -22,7 +22,7 @@ import im.vector.lib.multipicker.entity.MultiPickerVideoType import im.vector.lib.multipicker.utils.toMultiPickerVideoType /** - * Video Picker implementation + * Video Picker implementation. */ class VideoPicker : Picker() { diff --git a/library/ui-styles/src/main/res/values/colors.xml b/library/ui-styles/src/main/res/values/colors.xml index d887e7774e..e72d02f51e 100644 --- a/library/ui-styles/src/main/res/values/colors.xml +++ b/library/ui-styles/src/main/res/values/colors.xml @@ -126,6 +126,14 @@ @color/palette_element_green @color/palette_element_green + + @color/element_alert_light + @color/element_alert_dark + + + @color/palette_element_orange + @color/palette_element_orange + @color/palette_prune @@ -136,4 +144,9 @@ #17191C #FF4B55 + + + @color/palette_white + @color/palette_black_950 + diff --git a/library/ui-styles/src/main/res/values/dimens.xml b/library/ui-styles/src/main/res/values/dimens.xml index 81d5a77297..70d051b457 100644 --- a/library/ui-styles/src/main/res/values/dimens.xml +++ b/library/ui-styles/src/main/res/values/dimens.xml @@ -9,6 +9,7 @@ 32dp 50dp + 20dp 16dp 32dp @@ -40,7 +41,7 @@ 24dp 48dp 48dp - 38dp + 34dp 56dp diff --git a/library/ui-styles/src/main/res/values/palette.xml b/library/ui-styles/src/main/res/values/palette.xml index e6cee80b59..73ac768919 100644 --- a/library/ui-styles/src/main/res/values/palette.xml +++ b/library/ui-styles/src/main/res/values/palette.xml @@ -17,6 +17,7 @@ #FF812D #0DBD8B + #D9B072 #FFFFFF #FF5B55 diff --git a/library/ui-styles/src/main/res/values/styles_location.xml b/library/ui-styles/src/main/res/values/styles_location.xml index 5563d28342..7571265241 100644 --- a/library/ui-styles/src/main/res/values/styles_location.xml +++ b/library/ui-styles/src/main/res/values/styles_location.xml @@ -2,10 +2,20 @@ + + diff --git a/library/ui-styles/src/main/res/values/theme_dark.xml b/library/ui-styles/src/main/res/values/theme_dark.xml index 7177687fdd..733f7e8eb5 100644 --- a/library/ui-styles/src/main/res/values/theme_dark.xml +++ b/library/ui-styles/src/main/res/values/theme_dark.xml @@ -30,6 +30,7 @@ @color/element_system_dark @color/vctr_message_bubble_inbound_dark @color/vctr_message_bubble_outbound_dark + @color/vctr_badge_color_border_dark #61708B @@ -44,6 +45,8 @@ @color/vctr_presence_indicator_offline_dark @color/vctr_presence_indicator_online_dark + @color/vctr_presence_indicator_busy_dark + @color/vctr_presence_indicator_away_dark ?vctr_system diff --git a/library/ui-styles/src/main/res/values/theme_light.xml b/library/ui-styles/src/main/res/values/theme_light.xml index c90c021591..77996c8ce5 100644 --- a/library/ui-styles/src/main/res/values/theme_light.xml +++ b/library/ui-styles/src/main/res/values/theme_light.xml @@ -30,6 +30,7 @@ @color/element_background_light @color/vctr_message_bubble_inbound_light @color/vctr_message_bubble_outbound_light + @color/vctr_badge_color_border_light #61708B @@ -44,6 +45,8 @@ @color/vctr_presence_indicator_offline_light @color/vctr_presence_indicator_online_light + @color/vctr_presence_indicator_busy_light + @color/vctr_presence_indicator_away_light ?vctr_system diff --git a/matrix-sdk-android/build.gradle b/matrix-sdk-android/build.gradle index 7cab46c0be..33798d1357 100644 --- a/matrix-sdk-android/build.gradle +++ b/matrix-sdk-android/build.gradle @@ -21,7 +21,7 @@ dokkaHtml { dokkaSourceSets { configureEach { // Emit warnings about not documented members. - reportUndocumented.set(true) + // reportUndocumented.set(true) // Suppress legacy Riot's packages. perPackageOption { matchingRegex.set("org.matrix.android.sdk.internal.legacy.riot") @@ -56,7 +56,7 @@ android { // that the app's state is completely cleared between tests. testInstrumentationRunnerArguments clearPackageData: 'true' - buildConfigField "String", "SDK_VERSION", "\"1.4.16\"" + buildConfigField "String", "SDK_VERSION", "\"1.4.18\"" buildConfigField "String", "GIT_SDK_REVISION", "\"${gitRevision()}\"" buildConfigField "String", "GIT_SDK_REVISION_UNIX_DATE", "\"${gitRevisionUnixDate()}\"" @@ -101,6 +101,9 @@ android { freeCompilerArgs += [ // Disabled for now, there are too many errors. Could be handled in another dedicated PR // '-Xexplicit-api=strict', // or warning + "-opt-in=kotlin.RequiresOptIn", + // Opt in for kotlinx.coroutines.FlowPreview + "-opt-in=kotlinx.coroutines.FlowPreview", ] } diff --git a/matrix-sdk-android/docs/modules.md b/matrix-sdk-android/docs/modules.md index edf5af64d0..fb082c1bc2 100644 --- a/matrix-sdk-android/docs/modules.md +++ b/matrix-sdk-android/docs/modules.md @@ -1,5 +1,8 @@ # Module matrix-sdk-android + +**Note**: You are viewing the nightly documentation of the Android Matrix SDK library. The documentation of the released library can be found here: [https://matrix-org.github.io/matrix-android-sdk2/](https://matrix-org.github.io/matrix-android-sdk2/) + ## Welcome to the matrix-sdk-android documentation! This pages list the complete API that this SDK is exposing to a client application. @@ -8,11 +11,11 @@ This pages list the complete API that this SDK is exposing to a client applicati A few entry points: -- **Matrix**: The app will have to create and manage a Matrix object. -- From this **Matrix** object, you will be able to get various services, including the **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**. -- From the **Session**, you will be able to retrieve many Services, including the **RoomService**. -- From the **RoomService**, you will be able to list the rooms, create a **Room**, and get a specific **Room**. -- And from a **Room**, you will be able to do many things, including get a **Timeline**, send messages, etc. +- **[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](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](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](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](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](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! diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 4b9e605cd0..6678b109a6 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -63,8 +63,9 @@ class CommonTestHelper(context: Context) { fun getTestInterceptor(session: Session): MockOkHttpInterceptor? = TestModule.interceptorForSession(session.sessionId) as? MockOkHttpInterceptor init { + var _matrix: TestMatrix? = null UiThreadStatement.runOnUiThread { - TestMatrix.initialize( + _matrix = TestMatrix( context, MatrixConfiguration( applicationFlavor = "TestFlavor", @@ -72,7 +73,7 @@ class CommonTestHelper(context: Context) { ) ) } - matrix = TestMatrix.getInstance() + matrix = _matrix!! } fun createAccount(userNamePrefix: String, testParams: SessionTestParams): Session { @@ -296,7 +297,7 @@ class CommonTestHelper(context: Context) { val session = (registrationResult as RegistrationResult.Success).session session.open() if (sessionTestParams.withInitialSync) { - syncSession(session, 60_000) + syncSession(session, 120_000) } return session } @@ -377,7 +378,10 @@ class CommonTestHelper(context: Context) { * @throws InterruptedException */ fun await(latch: CountDownLatch, timeout: Long? = TestConstants.timeOutMillis) { - assertTrue(latch.await(timeout ?: TestConstants.timeOutMillis, TimeUnit.MILLISECONDS)) + assertTrue( + "Timed out after " + timeout + "ms waiting for something to happen. See stacktrace for cause.", + latch.await(timeout ?: TestConstants.timeOutMillis, TimeUnit.MILLISECONDS) + ) } suspend fun retryPeriodicallyWithLatch(latch: CountDownLatch, condition: (() -> Boolean)) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 4ead511c4d..348841313b 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -19,6 +19,7 @@ package org.matrix.android.sdk.common import android.os.SystemClock import android.util.Log import androidx.lifecycle.Observer +import org.amshove.kluent.fail import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull @@ -31,8 +32,16 @@ import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM_BACKUP import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.session.Session +import org.matrix.android.sdk.api.session.crypto.MXCryptoError +import org.matrix.android.sdk.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME +import org.matrix.android.sdk.api.session.crypto.crosssigning.MASTER_KEY_SSSS_NAME +import org.matrix.android.sdk.api.session.crypto.crosssigning.SELF_SIGNING_KEY_SSSS_NAME +import org.matrix.android.sdk.api.session.crypto.crosssigning.USER_SIGNING_KEY_SSSS_NAME +import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersion import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupAuthData import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo +import org.matrix.android.sdk.api.session.crypto.keysbackup.extractCurveKeyFromRecoveryKey +import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult import org.matrix.android.sdk.api.session.crypto.verification.IncomingSasVerificationTransaction import org.matrix.android.sdk.api.session.crypto.verification.OutgoingSasVerificationTransaction import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod @@ -40,13 +49,19 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxStat import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.toContent +import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.Room import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams +import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams +import org.matrix.android.sdk.api.session.securestorage.EmptyKeySigner +import org.matrix.android.sdk.api.session.securestorage.SharedSecretStorageService import org.matrix.android.sdk.api.util.Optional +import org.matrix.android.sdk.api.util.awaitCallback +import org.matrix.android.sdk.api.util.toBase64NoPadding import java.util.UUID import kotlin.coroutines.Continuation import kotlin.coroutines.resume @@ -188,17 +203,49 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) { val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! // 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 - testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[0], 1) - testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[1], 1) - testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[2], 1) + testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId -> + // ensure alice got it + 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 - 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 } + 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) { assertEquals(EventType.ENCRYPTED, event.type) assertNotNull(event.content) @@ -296,17 +343,104 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) { } } + /** + * Initialize cross-signing, set up megolm backup and save all in 4S + */ + fun bootstrapSecurity(session: Session) { + initializeCrossSigning(session) + val ssssService = session.sharedSecretStorageService() + testHelper.runBlockingTest { + val keyInfo = ssssService.generateKey( + UUID.randomUUID().toString(), + null, + "ssss_key", + EmptyKeySigner() + ) + ssssService.setDefaultKey(keyInfo.keyId) + + ssssService.storeSecret( + MASTER_KEY_SSSS_NAME, + session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.master!!, + listOf(SharedSecretStorageService.KeyRef(keyInfo.keyId, keyInfo.keySpec)) + ) + + ssssService.storeSecret( + SELF_SIGNING_KEY_SSSS_NAME, + session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.selfSigned!!, + listOf(SharedSecretStorageService.KeyRef(keyInfo.keyId, keyInfo.keySpec)) + ) + + ssssService.storeSecret( + USER_SIGNING_KEY_SSSS_NAME, + session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.user!!, + listOf(SharedSecretStorageService.KeyRef(keyInfo.keyId, keyInfo.keySpec)) + ) + + // set up megolm backup + val creationInfo = awaitCallback { + session.cryptoService().keysBackupService().prepareKeysBackupVersion(null, null, it) + } + val version = awaitCallback { + session.cryptoService().keysBackupService().createKeysBackupVersion(creationInfo, it) + } + // Save it for gossiping + session.cryptoService().keysBackupService().saveBackupRecoveryKey(creationInfo.recoveryKey, version = version.version) + + extractCurveKeyFromRecoveryKey(creationInfo.recoveryKey)?.toBase64NoPadding()?.let { secret -> + ssssService.storeSecret( + KEYBACKUP_SECRET_SSSS_NAME, + secret, + listOf(SharedSecretStorageService.KeyRef(keyInfo.keyId, keyInfo.keySpec)) + ) + } + } + } + fun verifySASCrossSign(alice: Session, bob: Session, roomId: String) { assertTrue(alice.cryptoService().crossSigningService().canCrossSign()) assertTrue(bob.cryptoService().crossSigningService().canCrossSign()) - val requestID = UUID.randomUUID().toString() val aliceVerificationService = alice.cryptoService().verificationService() val bobVerificationService = bob.cryptoService().verificationService() + val localId = UUID.randomUUID().toString() + aliceVerificationService.requestKeyVerificationInDMs( + localId = localId, + methods = listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW), + otherUserId = bob.myUserId, + roomId = roomId + ).transactionId + + testHelper.waitWithLatch { + testHelper.retryPeriodicallyWithLatch(it) { + bobVerificationService.getExistingVerificationRequests(alice.myUserId).firstOrNull { + it.requestInfo?.fromDevice == alice.sessionParams.deviceId + } != null + } + } + val incomingRequest = bobVerificationService.getExistingVerificationRequests(alice.myUserId).first { + it.requestInfo?.fromDevice == alice.sessionParams.deviceId + } + bobVerificationService.readyPendingVerification(listOf(VerificationMethod.SAS), alice.myUserId, incomingRequest.transactionId!!) + + var requestID: String? = null + // wait for it to be readied + testHelper.waitWithLatch { + testHelper.retryPeriodicallyWithLatch(it) { + val outgoingRequest = aliceVerificationService.getExistingVerificationRequests(bob.myUserId) + .firstOrNull { it.localId == localId } + if (outgoingRequest?.isReady == true) { + requestID = outgoingRequest.transactionId!! + true + } else { + false + } + } + } + aliceVerificationService.beginKeyVerificationInDMs( VerificationMethod.SAS, - requestID, + requestID!!, roomId, bob.myUserId, bob.sessionParams.credentials.deviceId!! @@ -316,23 +450,9 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) { var alicePovTx: OutgoingSasVerificationTransaction? = null var bobPovTx: IncomingSasVerificationTransaction? = null - // wait for alice to get the ready testHelper.waitWithLatch { testHelper.retryPeriodicallyWithLatch(it) { - bobPovTx = bobVerificationService.getExistingTransaction(alice.myUserId, requestID) as? IncomingSasVerificationTransaction - Log.v("TEST", "== bobPovTx is ${alicePovTx?.uxState}") - if (bobPovTx?.state == VerificationTxState.OnStarted) { - bobPovTx?.performAccept() - true - } else { - false - } - } - } - - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - alicePovTx = aliceVerificationService.getExistingTransaction(bob.myUserId, requestID) as? OutgoingSasVerificationTransaction + alicePovTx = aliceVerificationService.getExistingTransaction(bob.myUserId, requestID!!) as? OutgoingSasVerificationTransaction Log.v("TEST", "== alicePovTx is ${alicePovTx?.uxState}") alicePovTx?.state == VerificationTxState.ShortCodeReady } @@ -340,7 +460,7 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) { // wait for alice to get the ready testHelper.waitWithLatch { testHelper.retryPeriodicallyWithLatch(it) { - bobPovTx = bobVerificationService.getExistingTransaction(alice.myUserId, requestID) as? IncomingSasVerificationTransaction + bobPovTx = bobVerificationService.getExistingTransaction(alice.myUserId, requestID!!) as? IncomingSasVerificationTransaction Log.v("TEST", "== bobPovTx is ${alicePovTx?.uxState}") if (bobPovTx?.state == VerificationTxState.OnStarted) { bobPovTx?.performAccept() @@ -392,4 +512,50 @@ class CryptoTestHelper(private val testHelper: CommonTestHelper) { return CryptoTestData(roomId, sessions) } + + fun ensureCanDecrypt(sentEventIds: List, session: Session, e2eRoomID: String, messagesText: List) { + sentEventIds.forEachIndexed { index, sentEventId -> + testHelper.waitWithLatch { latch -> + testHelper.retryPeriodicallyWithLatch(latch) { + val event = session.getRoom(e2eRoomID)!!.timelineService().getTimelineEvent(sentEventId)!!.root + testHelper.runBlockingTest { + try { + session.cryptoService().decryptEvent(event, "").let { result -> + event.mxDecryptionResult = OlmDecryptionResult( + payload = result.clearEvent, + senderKey = result.senderCurve25519Key, + keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) }, + forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain + ) + } + } catch (error: MXCryptoError) { + // nop + } + } + Log.v("TEST", "ensureCanDecrypt ${event.getClearType()} is ${event.getClearContent()}") + event.getClearType() == EventType.MESSAGE && + messagesText[index] == event.getClearContent()?.toModel()?.body + } + } + } + } + + fun ensureCannotDecrypt(sentEventIds: List, session: Session, e2eRoomID: String, expectedError: MXCryptoError.ErrorType? = null) { + sentEventIds.forEach { sentEventId -> + val event = session.getRoom(e2eRoomID)!!.timelineService().getTimelineEvent(sentEventId)!!.root + testHelper.runBlockingTest { + try { + session.cryptoService().decryptEvent(event, "") + fail("Should not be able to decrypt event") + } catch (error: MXCryptoError) { + val errorType = (error as? MXCryptoError.Base)?.errorType + if (expectedError == null) { + assertNotNull(errorType) + } else { + assertEquals("Unexpected reason", expectedError, errorType) + } + } + } + } + } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestConstants.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestConstants.kt index 0f79896b2c..89c965c31a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestConstants.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestConstants.kt @@ -23,7 +23,7 @@ object TestConstants { const val TESTS_HOME_SERVER_URL = "http://10.0.2.2:8080" // Time out to use when waiting for server response. - private const val AWAIT_TIME_OUT_MILLIS = 60_000 + private const val AWAIT_TIME_OUT_MILLIS = 120_000 // Time out to use when waiting for server response, when the debugger is connected. 10 minutes private const val AWAIT_TIME_OUT_WITH_DEBUGGER_MILLIS = 10 * 60_000 diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrix.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrix.kt index fa44167a8f..5864a801e6 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrix.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestMatrix.kt @@ -21,7 +21,8 @@ import android.os.Handler import android.os.Looper import androidx.lifecycle.ProcessLifecycleOwner import androidx.work.Configuration -import androidx.work.WorkManager +import androidx.work.impl.WorkManagerImpl +import androidx.work.impl.utils.taskexecutor.WorkManagerTaskExecutor import com.zhuinden.monarchy.Monarchy import org.matrix.android.sdk.BuildConfig import org.matrix.android.sdk.api.MatrixConfiguration @@ -38,13 +39,12 @@ import org.matrix.android.sdk.internal.util.BackgroundDetectionObserver import org.matrix.android.sdk.internal.worker.MatrixWorkerFactory import org.matrix.olm.OlmManager import java.util.concurrent.Executors -import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject /** * 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 authenticationService: AuthenticationService @@ -60,13 +60,19 @@ internal class TestMatrix constructor(context: Context, matrixConfiguration: Mat private val uiHandler = Handler(Looper.getMainLooper()) init { - Monarchy.init(context) - DaggerTestMatrixComponent.factory().create(context, matrixConfiguration).inject(this) + val appContext = context.applicationContext + Monarchy.init(appContext) + DaggerTestMatrixComponent.factory().create(appContext, matrixConfiguration).inject(this) val configuration = Configuration.Builder() .setExecutor(Executors.newCachedThreadPool()) .setWorkerFactory(matrixWorkerFactory) .build() - WorkManager.initialize(context, configuration) + val delegate = WorkManagerImpl( + context, + configuration, + WorkManagerTaskExecutor(configuration.taskExecutor) + ) + WorkManagerImpl.setDelegate(delegate) uiHandler.post { ProcessLifecycleOwner.get().lifecycle.addObserver(backgroundDetectionObserver) } @@ -95,23 +101,6 @@ internal class TestMatrix constructor(context: Context, matrixConfiguration: Mat } 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 { return BuildConfig.SDK_VERSION + " (" + BuildConfig.GIT_SDK_REVISION + ")" } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt index e823aa39a1..cd6c146f03 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/CryptoStoreTest.kt @@ -22,9 +22,11 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNull import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.matrix.android.sdk.InstrumentedTest +import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.internal.crypto.model.OlmSessionWrapper import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore import org.matrix.android.sdk.internal.util.time.DefaultClock @@ -37,6 +39,8 @@ private const val DUMMY_DEVICE_KEY = "DeviceKey" @RunWith(AndroidJUnit4::class) class CryptoStoreTest : InstrumentedTest { + @get:Rule val rule = RetryTestRule(3) + private val cryptoStoreHelper = CryptoStoreHelper() private val clock = DefaultClock() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index ed922fdddc..38597269cb 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -23,6 +23,7 @@ import org.amshove.kluent.fail import org.amshove.kluent.internal.assertEquals import org.junit.Assert import org.junit.FixMethodOrder +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @@ -30,13 +31,21 @@ import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.MXCryptoError +import org.matrix.android.sdk.api.session.crypto.RequestResult 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.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult -import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult +import org.matrix.android.sdk.api.session.crypto.verification.IncomingSasVerificationTransaction +import org.matrix.android.sdk.api.session.crypto.verification.OutgoingSasVerificationTransaction +import org.matrix.android.sdk.api.session.crypto.verification.PendingVerificationRequest +import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod +import org.matrix.android.sdk.api.session.crypto.verification.VerificationService +import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransaction import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent +import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.getRoomSummary @@ -49,17 +58,18 @@ import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CryptoTestHelper +import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.common.TestMatrixCallback +import java.util.concurrent.CountDownLatch @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) @LargeTest class E2eeSanityTests : InstrumentedTest { - private val testHelper = CommonTestHelper(context()) - private val cryptoTestHelper = CryptoTestHelper(testHelper) + @get:Rule val rule = RetryTestRule(3) /** * Simple test that create an e2ee room. @@ -72,16 +82,24 @@ class E2eeSanityTests : InstrumentedTest { */ @Test fun testSendingE2EEMessages() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession val e2eRoomID = cryptoTestData.roomId val aliceRoomPOV = aliceSession.getRoom(e2eRoomID)!! + // we want to disable key gossiping to just check initial sending of keys + aliceSession.cryptoService().enableKeyGossiping(false) + cryptoTestData.secondSession?.cryptoService()?.enableKeyGossiping(false) // add some more users and invite them val otherAccounts = listOf("benoit", "valere", "ganfra") // , "adam", "manu") .map { - testHelper.createAccount(it, SessionTestParams(true)) + testHelper.createAccount(it, SessionTestParams(true)).also { + it.cryptoService().enableKeyGossiping(false) + } } Log.v("#E2E TEST", "All accounts created") @@ -95,18 +113,18 @@ class E2eeSanityTests : InstrumentedTest { // All user should accept invite otherAccounts.forEach { otherSession -> - waitForAndAcceptInviteInRoom(otherSession, e2eRoomID) + waitForAndAcceptInviteInRoom(testHelper, otherSession, e2eRoomID) Log.v("#E2E TEST", "${otherSession.myUserId} joined room $e2eRoomID") } // check that alice see them as joined (not really necessary?) - ensureMembersHaveJoined(aliceSession, otherAccounts, e2eRoomID) + ensureMembersHaveJoined(testHelper, aliceSession, otherAccounts, e2eRoomID) Log.v("#E2E TEST", "All users have joined the room") Log.v("#E2E TEST", "Alice is sending the message") val text = "This is my message" - val sentEventId: String? = sendMessageInRoom(aliceRoomPOV, text) + val sentEventId: String? = sendMessageInRoom(testHelper, aliceRoomPOV, text) // val sentEvent = testHelper.sendTextMessage(aliceRoomPOV, "Hello all", 1).first() Assert.assertTrue("Message should be sent", sentEventId != null) @@ -114,10 +132,10 @@ class E2eeSanityTests : InstrumentedTest { otherAccounts.forEach { otherSession -> testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId!!) - timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE + val timeLineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId!!) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } } @@ -136,10 +154,10 @@ class E2eeSanityTests : InstrumentedTest { } newAccount.forEach { - waitForAndAcceptInviteInRoom(it, e2eRoomID) + waitForAndAcceptInviteInRoom(testHelper, it, e2eRoomID) } - ensureMembersHaveJoined(aliceSession, newAccount, e2eRoomID) + ensureMembersHaveJoined(testHelper, aliceSession, newAccount, e2eRoomID) // wait a bit testHelper.runBlockingTest { @@ -164,7 +182,7 @@ class E2eeSanityTests : InstrumentedTest { Log.v("#E2E TEST", "Alice sends a new message") val secondMessage = "2 This is my message" - val secondSentEventId: String? = sendMessageInRoom(aliceRoomPOV, secondMessage) + val secondSentEventId: String? = sendMessageInRoom(testHelper, aliceRoomPOV, secondMessage) // new members should be able to decrypt it newAccount.forEach { otherSession -> @@ -188,6 +206,14 @@ class E2eeSanityTests : InstrumentedTest { cryptoTestData.cleanUp(testHelper) } + @Test + fun testKeyGossipingIsEnabledByDefault() { + val testHelper = CommonTestHelper(context()) + val session = testHelper.createAccount("alice", SessionTestParams(true)) + Assert.assertTrue("Key gossiping should be enabled by default", session.cryptoService().isKeyGossipingEnabled()) + testHelper.signOutAndClose(session) + } + /** * Quick test for basic key backup * 1. Create e2e between Alice and Bob @@ -204,6 +230,9 @@ class E2eeSanityTests : InstrumentedTest { */ @Test fun testBasicBackupImport() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession!! @@ -227,16 +256,16 @@ class E2eeSanityTests : InstrumentedTest { val sentEventIds = mutableListOf() val messagesText = listOf("1. Hello", "2. Bob", "3. Good morning") messagesText.forEach { text -> - val sentEventId = sendMessageInRoom(aliceRoomPOV, text)!!.also { + val sentEventId = sendMessageInRoom(testHelper, aliceRoomPOV, text)!!.also { sentEventIds.add(it) } testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) - timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE + val timeLineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } // we want more so let's discard the session @@ -289,22 +318,23 @@ class E2eeSanityTests : InstrumentedTest { } } // after initial sync events are not decrypted, so we have to try manually - ensureCannotDecrypt(sentEventIds, newBobSession, e2eRoomID, MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) + cryptoTestHelper.ensureCannotDecrypt(sentEventIds, newBobSession, e2eRoomID, MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) // Let's now import keys from backup - newBobSession.cryptoService().keysBackupService().let { keysBackupService -> + newBobSession.cryptoService().keysBackupService().let { kbs -> val keyVersionResult = testHelper.doSync { - keysBackupService.getVersion(version.version, it) + kbs.getVersion(version.version, it) } val importedResult = testHelper.doSync { - keysBackupService.restoreKeyBackupWithPassword( + kbs.restoreKeyBackupWithPassword( keyVersionResult!!, keyBackupPassword, null, null, - null, it + null, + it ) } @@ -312,7 +342,7 @@ class E2eeSanityTests : InstrumentedTest { } // ensure bob can now decrypt - ensureCanDecrypt(sentEventIds, newBobSession, e2eRoomID, messagesText) + cryptoTestHelper.ensureCanDecrypt(sentEventIds, newBobSession, e2eRoomID, messagesText) testHelper.signOutAndClose(newBobSession) } @@ -323,6 +353,9 @@ class E2eeSanityTests : InstrumentedTest { */ @Test fun testSimpleGossip() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession!! @@ -330,30 +363,28 @@ class E2eeSanityTests : InstrumentedTest { val aliceRoomPOV = aliceSession.getRoom(e2eRoomID)!! - cryptoTestHelper.initializeCrossSigning(bobSession) - // let's send a few message to bob val sentEventIds = mutableListOf() val messagesText = listOf("1. Hello", "2. Bob") Log.v("#E2E TEST", "Alice sends some messages") messagesText.forEach { text -> - val sentEventId = sendMessageInRoom(aliceRoomPOV, text)!!.also { + val sentEventId = sendMessageInRoom(testHelper, aliceRoomPOV, text)!!.also { sentEventIds.add(it) } testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) - timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE + val timeLineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } } // Ensure bob can decrypt - ensureIsDecrypted(sentEventIds, bobSession, e2eRoomID) + ensureIsDecrypted(testHelper, sentEventIds, bobSession, e2eRoomID) // Let's now add a new bob session // Create a new session for bob @@ -363,7 +394,11 @@ class E2eeSanityTests : InstrumentedTest { // check that new bob can't currently decrypt Log.v("#E2E TEST", "check that new bob can't currently decrypt") - ensureCannotDecrypt(sentEventIds, newBobSession, e2eRoomID, MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) + cryptoTestHelper.ensureCannotDecrypt(sentEventIds, newBobSession, e2eRoomID, null) +// newBobSession.cryptoService().getOutgoingRoomKeyRequests() +// .firstOrNull { +// it.sessionId == +// } // Try to request sentEventIds.forEach { sentEventId -> @@ -372,12 +407,34 @@ class E2eeSanityTests : InstrumentedTest { } // wait a bit - testHelper.runBlockingTest { - delay(10_000) - } + // we need to wait a couple of syncs to let sharing occurs +// testHelper.waitFewSyncs(newBobSession, 6) // Ensure that new bob still can't decrypt (keys must have been withheld) - ensureCannotDecrypt(sentEventIds, newBobSession, e2eRoomID, MXCryptoError.ErrorType.KEYS_WITHHELD) + sentEventIds.forEach { sentEventId -> + val megolmSessionId = newBobSession.getRoom(e2eRoomID)!! + .getTimelineEvent(sentEventId)!! + .root.content.toModel()!!.sessionId + testHelper.waitWithLatch { latch -> + testHelper.retryPeriodicallyWithLatch(latch) { + val aliceReply = newBobSession.cryptoService().getOutgoingRoomKeyRequests() + .first { + it.sessionId == megolmSessionId && + it.roomId == e2eRoomID + } + .results.also { + Log.w("##TEST", "result list is $it") + } + .firstOrNull { it.userId == aliceSession.myUserId } + ?.result + aliceReply != null && + aliceReply is RequestResult.Failure && + WithHeldCode.UNAUTHORISED == aliceReply.code + } + } + } + + cryptoTestHelper.ensureCannotDecrypt(sentEventIds, newBobSession, e2eRoomID, null) // Now mark new bob session as verified @@ -390,12 +447,7 @@ class E2eeSanityTests : InstrumentedTest { newBobSession.cryptoService().reRequestRoomKeyForEvent(event) } - // wait a bit - testHelper.runBlockingTest { - delay(10_000) - } - - ensureCanDecrypt(sentEventIds, newBobSession, e2eRoomID, messagesText) + cryptoTestHelper.ensureCanDecrypt(sentEventIds, newBobSession, e2eRoomID, messagesText) cryptoTestData.cleanUp(testHelper) testHelper.signOutAndClose(newBobSession) @@ -406,6 +458,9 @@ class E2eeSanityTests : InstrumentedTest { */ @Test fun testForwardBetterKey() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession val bobSessionWithBetterKey = cryptoTestData.secondSession!! @@ -413,35 +468,33 @@ class E2eeSanityTests : InstrumentedTest { val aliceRoomPOV = aliceSession.getRoom(e2eRoomID)!! - cryptoTestHelper.initializeCrossSigning(bobSessionWithBetterKey) - // let's send a few message to bob var firstEventId: String val firstMessage = "1. Hello" Log.v("#E2E TEST", "Alice sends some messages") firstMessage.let { text -> - firstEventId = sendMessageInRoom(aliceRoomPOV, text)!! + firstEventId = sendMessageInRoom(testHelper, aliceRoomPOV, text)!! testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = bobSessionWithBetterKey.getRoom(e2eRoomID)?.getTimelineEvent(firstEventId) - timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE + val timeLineEvent = bobSessionWithBetterKey.getRoom(e2eRoomID)?.getTimelineEvent(firstEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } } // Ensure bob can decrypt - ensureIsDecrypted(listOf(firstEventId), bobSessionWithBetterKey, e2eRoomID) + ensureIsDecrypted(testHelper, listOf(firstEventId), bobSessionWithBetterKey, e2eRoomID) // Let's add a new unverified session from bob val newBobSession = testHelper.logIntoAccount(bobSessionWithBetterKey.myUserId, SessionTestParams(true)) // check that new bob can't currently decrypt Log.v("#E2E TEST", "check that new bob can't currently decrypt") - ensureCannotDecrypt(listOf(firstEventId), newBobSession, e2eRoomID, MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) + cryptoTestHelper.ensureCannotDecrypt(listOf(firstEventId), newBobSession, e2eRoomID, null) // Now let alice send a new message. this time the new bob session will be able to decrypt var secondEventId: String @@ -449,14 +502,14 @@ class E2eeSanityTests : InstrumentedTest { Log.v("#E2E TEST", "Alice sends some messages") secondMessage.let { text -> - secondEventId = sendMessageInRoom(aliceRoomPOV, text)!! + secondEventId = sendMessageInRoom(testHelper, aliceRoomPOV, text)!! testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = newBobSession.getRoom(e2eRoomID)?.getTimelineEvent(secondEventId) - timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE + val timeLineEvent = newBobSession.getRoom(e2eRoomID)?.getTimelineEvent(secondEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } } @@ -475,9 +528,7 @@ class E2eeSanityTests : InstrumentedTest { try { newBobSession.cryptoService().decryptEvent(firstEventNewBobPov.root, "") fail("Should not be able to decrypt event") - } catch (error: MXCryptoError) { - val errorType = (error as? MXCryptoError.Base)?.errorType - assertEquals(MXCryptoError.ErrorType.UNKNOWN_MESSAGE_INDEX, errorType) + } catch (_: MXCryptoError) { } } @@ -499,41 +550,45 @@ class E2eeSanityTests : InstrumentedTest { .markedLocallyAsManuallyVerified(bobSessionWithBetterKey.myUserId, bobSessionWithBetterKey.sessionParams.deviceId!!) // now let new session request - newBobSession.cryptoService().requestRoomKeyForEvent(firstEventNewBobPov.root) + newBobSession.cryptoService().reRequestRoomKeyForEvent(firstEventNewBobPov.root) - // wait a bit - testHelper.runBlockingTest { - delay(10_000) - } + // We need to wait for the key request to be sent out and then a reply to be received // old session should have shared the key at earliest known index now // we should be able to decrypt both - testHelper.runBlockingTest { - try { - newBobSession.cryptoService().decryptEvent(firstEventNewBobPov.root, "") - } catch (error: MXCryptoError) { - fail("Should be able to decrypt first event now $error") - } - } - testHelper.runBlockingTest { - try { - newBobSession.cryptoService().decryptEvent(secondEventNewBobPov.root, "") - } catch (error: MXCryptoError) { - fail("Should be able to decrypt event $error") + testHelper.waitWithLatch { + testHelper.retryPeriodicallyWithLatch(it) { + val canDecryptFirst = try { + testHelper.runBlockingTest { + newBobSession.cryptoService().decryptEvent(firstEventNewBobPov.root, "") + } + true + } catch (error: MXCryptoError) { + false + } + val canDecryptSecond = try { + testHelper.runBlockingTest { + newBobSession.cryptoService().decryptEvent(secondEventNewBobPov.root, "") + } + true + } catch (error: MXCryptoError) { + false + } + canDecryptFirst && canDecryptSecond } } - cryptoTestData.cleanUp(testHelper) + testHelper.signOutAndClose(aliceSession) + testHelper.signOutAndClose(bobSessionWithBetterKey) testHelper.signOutAndClose(newBobSession) } - private fun sendMessageInRoom(aliceRoomPOV: Room, text: String): String? { + private fun sendMessageInRoom(testHelper: CommonTestHelper, aliceRoomPOV: Room, text: String): String? { aliceRoomPOV.sendService().sendTextMessage(text) var sentEventId: String? = null testHelper.waitWithLatch(4 * TestConstants.timeOutMillis) { latch -> val timeline = aliceRoomPOV.timelineService().createTimeline(null, TimelineSettings(60)) timeline.start() - testHelper.retryPeriodicallyWithLatch(latch) { val decryptedMsg = timeline.getSnapshot() .filter { it.root.getClearType() == EventType.MESSAGE } @@ -552,7 +607,157 @@ class E2eeSanityTests : InstrumentedTest { return sentEventId } - private fun ensureMembersHaveJoined(aliceSession: Session, otherAccounts: List, e2eRoomID: String) { + /** + * Test that if a better key is forwared (lower index, it is then used) + */ + @Test + fun testSelfInteractiveVerificationAndGossip() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + + val aliceSession = testHelper.createAccount("alice", SessionTestParams(true)) + cryptoTestHelper.bootstrapSecurity(aliceSession) + + // now let's create a new login from alice + + val aliceNewSession = testHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) + + val oldCompleteLatch = CountDownLatch(1) + lateinit var oldCode: String + aliceSession.cryptoService().verificationService().addListener(object : VerificationService.Listener { + + override fun verificationRequestUpdated(pr: PendingVerificationRequest) { + val readyInfo = pr.readyInfo + if (readyInfo != null) { + aliceSession.cryptoService().verificationService().beginKeyVerification( + VerificationMethod.SAS, + aliceSession.myUserId, + readyInfo.fromDevice, + readyInfo.transactionId + + ) + } + } + + override fun transactionUpdated(tx: VerificationTransaction) { + Log.d("##TEST", "exitsingPov: $tx") + val sasTx = tx as OutgoingSasVerificationTransaction + when (sasTx.uxState) { + OutgoingSasVerificationTransaction.UxState.SHOW_SAS -> { + // for the test we just accept? + oldCode = sasTx.getDecimalCodeRepresentation() + sasTx.userHasVerifiedShortCode() + } + OutgoingSasVerificationTransaction.UxState.VERIFIED -> { + // we can release this latch? + oldCompleteLatch.countDown() + } + else -> Unit + } + } + }) + + val newCompleteLatch = CountDownLatch(1) + lateinit var newCode: String + aliceNewSession.cryptoService().verificationService().addListener(object : VerificationService.Listener { + + override fun verificationRequestCreated(pr: PendingVerificationRequest) { + // let's ready + aliceNewSession.cryptoService().verificationService().readyPendingVerification( + listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW), + aliceSession.myUserId, + pr.transactionId!! + ) + } + + var matchOnce = true + override fun transactionUpdated(tx: VerificationTransaction) { + Log.d("##TEST", "newPov: $tx") + + val sasTx = tx as IncomingSasVerificationTransaction + when (sasTx.uxState) { + IncomingSasVerificationTransaction.UxState.SHOW_ACCEPT -> { + // no need to accept as there was a request first it will auto accept + } + IncomingSasVerificationTransaction.UxState.SHOW_SAS -> { + if (matchOnce) { + sasTx.userHasVerifiedShortCode() + newCode = sasTx.getDecimalCodeRepresentation() + matchOnce = false + } + } + IncomingSasVerificationTransaction.UxState.VERIFIED -> { + newCompleteLatch.countDown() + } + else -> Unit + } + } + }) + + // initiate self verification + aliceSession.cryptoService().verificationService().requestKeyVerification( + listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW), + aliceNewSession.myUserId, + listOf(aliceNewSession.sessionParams.deviceId!!) + ) + testHelper.await(oldCompleteLatch) + testHelper.await(newCompleteLatch) + assertEquals("Decimal code should have matched", oldCode, newCode) + + // Assert that devices are verified + val newDeviceFromOldPov: CryptoDeviceInfo? = aliceSession.cryptoService().getDeviceInfo(aliceSession.myUserId, aliceNewSession.sessionParams.deviceId) + val oldDeviceFromNewPov: CryptoDeviceInfo? = aliceSession.cryptoService().getDeviceInfo(aliceSession.myUserId, aliceSession.sessionParams.deviceId) + + Assert.assertTrue("new device should be verified from old point of view", newDeviceFromOldPov!!.isVerified) + Assert.assertTrue("old device should be verified from new point of view", oldDeviceFromNewPov!!.isVerified) + + // wait for secret gossiping to happen + testHelper.waitWithLatch { latch -> + testHelper.retryPeriodicallyWithLatch(latch) { + aliceNewSession.cryptoService().crossSigningService().allPrivateKeysKnown() + } + } + + testHelper.waitWithLatch { latch -> + testHelper.retryPeriodicallyWithLatch(latch) { + aliceNewSession.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo() != null + } + } + + assertEquals( + "MSK Private parts should be the same", + aliceSession.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.master, + aliceNewSession.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.master + ) + assertEquals( + "USK Private parts should be the same", + aliceSession.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.user, + aliceNewSession.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.user + ) + + assertEquals( + "SSK Private parts should be the same", + aliceSession.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.selfSigned, + aliceNewSession.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.selfSigned + ) + + // Let's check that we have the megolm backup key + assertEquals( + "Megolm key should be the same", + aliceSession.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo()!!.recoveryKey, + aliceNewSession.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo()!!.recoveryKey + ) + assertEquals( + "Megolm version should be the same", + aliceSession.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo()!!.version, + aliceNewSession.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo()!!.version + ) + + testHelper.signOutAndClose(aliceSession) + testHelper.signOutAndClose(aliceNewSession) + } + + private fun ensureMembersHaveJoined(testHelper: CommonTestHelper, aliceSession: Session, otherAccounts: List, e2eRoomID: String) { testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { otherAccounts.map { @@ -564,7 +769,7 @@ class E2eeSanityTests : InstrumentedTest { } } - private fun waitForAndAcceptInviteInRoom(otherSession: Session, e2eRoomID: String) { + private fun waitForAndAcceptInviteInRoom(testHelper: CommonTestHelper, otherSession: Session, e2eRoomID: String) { testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { val roomSummary = otherSession.getRoomSummary(e2eRoomID) @@ -576,7 +781,8 @@ class E2eeSanityTests : InstrumentedTest { } } - testHelper.runBlockingTest(60_000) { + // not sure why it's taking so long :/ + testHelper.runBlockingTest(90_000) { Log.v("#E2E TEST", "${otherSession.myUserId} tries to join room $e2eRoomID") try { otherSession.roomService().joinRoom(e2eRoomID) @@ -594,59 +800,14 @@ class E2eeSanityTests : InstrumentedTest { } } - private fun ensureCanDecrypt(sentEventIds: MutableList, session: Session, e2eRoomID: String, messagesText: List) { - sentEventIds.forEachIndexed { index, sentEventId -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val event = session.getRoom(e2eRoomID)!!.getTimelineEvent(sentEventId)!!.root - testHelper.runBlockingTest { - try { - session.cryptoService().decryptEvent(event, "").let { result -> - event.mxDecryptionResult = OlmDecryptionResult( - payload = result.clearEvent, - senderKey = result.senderCurve25519Key, - keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) }, - forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain - ) - } - } catch (error: MXCryptoError) { - // nop - } - } - event.getClearType() == EventType.MESSAGE && - messagesText[index] == event.getClearContent()?.toModel()?.body - } - } - } - } - - private fun ensureIsDecrypted(sentEventIds: List, session: Session, e2eRoomID: String) { + private fun ensureIsDecrypted(testHelper: CommonTestHelper, sentEventIds: List, session: Session, e2eRoomID: String) { testHelper.waitWithLatch { latch -> sentEventIds.forEach { sentEventId -> testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = session.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) - timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE - } - } - } - } - - private fun ensureCannotDecrypt(sentEventIds: List, newBobSession: Session, e2eRoomID: String, expectedError: MXCryptoError.ErrorType?) { - sentEventIds.forEach { sentEventId -> - val event = newBobSession.getRoom(e2eRoomID)!!.getTimelineEvent(sentEventId)!!.root - testHelper.runBlockingTest { - try { - newBobSession.cryptoService().decryptEvent(event, "") - fail("Should not be able to decrypt event") - } catch (error: MXCryptoError) { - val errorType = (error as? MXCryptoError.Base)?.errorType - if (expectedError == null) { - Assert.assertNotNull(errorType) - } else { - assertEquals(expectedError, errorType, "Message expected to be UISI") - } + val timeLineEvent = session.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt index 8a1edec5e3..93aa78a305 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt @@ -27,7 +27,6 @@ import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent -import org.matrix.android.sdk.api.session.events.model.content.RoomKeyContent import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent @@ -51,10 +50,7 @@ class PreShareKeysTest : InstrumentedTest { // clear any outbound session aliceSession.cryptoService().discardOutboundSession(e2eRoomID) - val preShareCount = bobSession.cryptoService().getGossipingEvents().count { - it.senderId == aliceSession.myUserId && - it.getClearType() == EventType.ROOM_KEY - } + val preShareCount = bobSession.cryptoService().keysBackupService().getTotalNumbersOfKeys() assertEquals("Bob should not have receive any key from alice at this point", 0, preShareCount) Log.d("#Test", "Room Key Received from alice $preShareCount") @@ -66,23 +62,23 @@ class PreShareKeysTest : InstrumentedTest { testHelper.waitWithLatch { latch -> testHelper.retryPeriodicallyWithLatch(latch) { - val newGossipCount = bobSession.cryptoService().getGossipingEvents().count { - it.senderId == aliceSession.myUserId && - it.getClearType() == EventType.ROOM_KEY - } - newGossipCount > preShareCount + val newKeysCount = bobSession.cryptoService().keysBackupService().getTotalNumbersOfKeys() + newKeysCount > preShareCount } } - val latest = bobSession.cryptoService().getGossipingEvents().lastOrNull { - it.senderId == aliceSession.myUserId && - it.getClearType() == EventType.ROOM_KEY - } + val aliceCryptoStore = (aliceSession.cryptoService() as DefaultCryptoService).cryptoStoreForTesting + val aliceOutboundSessionInRoom = aliceCryptoStore.getCurrentOutboundGroupSessionForRoom(e2eRoomID)!!.outboundGroupSession.sessionIdentifier() - val content = latest?.getClearContent().toModel() - assertNotNull("Bob should have received and decrypted a room key event from alice", content) - assertEquals("Wrong room", e2eRoomID, content!!.roomId) - val megolmSessionId = content.sessionId!! + val bobCryptoStore = (bobSession.cryptoService() as DefaultCryptoService).cryptoStoreForTesting + val aliceDeviceBobPov = bobCryptoStore.getUserDevice(aliceSession.myUserId, aliceSession.sessionParams.deviceId!!)!! + val bobInboundForAlice = bobCryptoStore.getInboundGroupSession(aliceOutboundSessionInRoom, aliceDeviceBobPov.identityKey()!!) + assertNotNull("Bob should have received and decrypted a room key event from alice", bobInboundForAlice) + assertEquals("Wrong room", e2eRoomID, bobInboundForAlice!!.roomId) + + val megolmSessionId = bobInboundForAlice.olmInboundGroupSession!!.sessionIdentifier() + + assertEquals("Wrong session", aliceOutboundSessionInRoom, megolmSessionId) val sharedIndex = aliceSession.cryptoService().getSharedWithInfo(e2eRoomID, megolmSessionId) .getObject(bobSession.myUserId, bobSession.sessionParams.deviceId) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt index a37626dc20..abcf1714b8 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt @@ -25,7 +25,6 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.FixMethodOrder -import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -143,7 +142,6 @@ class XSigningTest : InstrumentedTest { } @Test - @Ignore("This test will be ignored until it is fixed") fun test_CrossSigningTestAliceTrustBobNewDevice() { val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index 5066a4339f..1bd2a46381 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -19,59 +19,49 @@ package org.matrix.android.sdk.internal.crypto.gossiping import android.util.Log import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest -import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertNotNull import junit.framework.TestCase.assertTrue import junit.framework.TestCase.fail +import org.amshove.kluent.internal.assertEquals import org.junit.Assert +import org.junit.Assert.assertNull import org.junit.FixMethodOrder -import org.junit.Ignore +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest -import org.matrix.android.sdk.api.auth.UIABaseAuth -import org.matrix.android.sdk.api.auth.UserInteractiveAuthInterceptor -import org.matrix.android.sdk.api.auth.UserPasswordAuth -import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse -import org.matrix.android.sdk.api.extensions.tryOrNull +import org.matrix.android.sdk.api.session.crypto.OutgoingRoomKeyRequestState +import org.matrix.android.sdk.api.session.crypto.RequestResult import org.matrix.android.sdk.api.session.crypto.crosssigning.DeviceTrustLevel -import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersion -import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo -import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo -import org.matrix.android.sdk.api.session.crypto.model.GossipingRequestState -import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap -import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState -import org.matrix.android.sdk.api.session.crypto.verification.IncomingSasVerificationTransaction -import org.matrix.android.sdk.api.session.crypto.verification.SasVerificationTransaction -import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod -import org.matrix.android.sdk.api.session.crypto.verification.VerificationService -import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransaction -import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent +import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent import org.matrix.android.sdk.api.session.room.model.RoomDirectoryVisibility import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams -import org.matrix.android.sdk.api.session.room.model.message.MessageContent +import org.matrix.android.sdk.api.session.room.timeline.getLastMessageContent import org.matrix.android.sdk.common.CommonTestHelper +import org.matrix.android.sdk.common.CryptoTestHelper +import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants -import kotlin.coroutines.Continuation -import kotlin.coroutines.resume @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) @LargeTest class KeyShareTests : InstrumentedTest { - private val commonTestHelper = CommonTestHelper(context()) + @get:Rule val rule = RetryTestRule(3) @Test - @Ignore("This test will be ignored until it is fixed") fun test_DoNotSelfShareIfNotTrusted() { + val commonTestHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(commonTestHelper) + val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) + Log.v("TEST", "=======> AliceSession 1 is ${aliceSession.sessionParams.deviceId}") // Create an encrypted room and add a message val roomId = commonTestHelper.runBlockingTest { @@ -86,11 +76,18 @@ class KeyShareTests : InstrumentedTest { assertNotNull(room) Thread.sleep(4_000) assertTrue(room?.roomCryptoService()?.isEncrypted() == true) - val sentEventId = commonTestHelper.sendTextMessage(room!!, "My Message", 1).first().eventId - // Open a new sessionx + val sentEvent = commonTestHelper.sendTextMessage(room!!, "My Message", 1).first() + val sentEventId = sentEvent.eventId + val sentEventText = sentEvent.getLastMessageContent()?.body - val aliceSession2 = commonTestHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) + // Open a new session + val aliceSession2 = commonTestHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(false)) + // block key requesting for now as decrypt will send requests (room summary is trying to decrypt) + aliceSession2.cryptoService().enableKeyGossiping(false) + commonTestHelper.syncSession(aliceSession2) + + Log.v("TEST", "=======> AliceSession 2 is ${aliceSession2.sessionParams.deviceId}") val roomSecondSessionPOV = aliceSession2.getRoom(roomId) @@ -107,7 +104,10 @@ class KeyShareTests : InstrumentedTest { } val outgoingRequestsBefore = aliceSession2.cryptoService().getOutgoingRoomKeyRequests() + assertEquals("There should be no request as it's disabled", 0, outgoingRequestsBefore.size) + // Try to request + aliceSession2.cryptoService().enableKeyGossiping(true) aliceSession2.cryptoService().requestRoomKeyForEvent(receivedEvent.root) val eventMegolmSessionId = receivedEvent.root.content.toModel()?.sessionId @@ -117,10 +117,6 @@ class KeyShareTests : InstrumentedTest { commonTestHelper.waitWithLatch { latch -> commonTestHelper.retryPeriodicallyWithLatch(latch) { aliceSession2.cryptoService().getOutgoingRoomKeyRequests() - .filter { req -> - // filter out request that was known before - !outgoingRequestsBefore.any { req.requestId == it.requestId } - } .let { val outgoing = it.firstOrNull { it.sessionId == eventMegolmSessionId } outGoingRequestId = outgoing?.requestId @@ -141,20 +137,34 @@ class KeyShareTests : InstrumentedTest { commonTestHelper.waitWithLatch { latch -> commonTestHelper.retryPeriodicallyWithLatch(latch) { // DEBUG LOGS - aliceSession.cryptoService().getIncomingRoomKeyRequests().let { - Log.v("TEST", "Incoming request Session 1 (looking for $outGoingRequestId)") +// aliceSession.cryptoService().getIncomingRoomKeyRequests().let { +// Log.v("TEST", "Incoming request Session 1 (looking for $outGoingRequestId)") +// Log.v("TEST", "=========================") +// it.forEach { keyRequest -> +// Log.v("TEST", "[ts${keyRequest.localCreationTimestamp}] requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId}") +// } +// Log.v("TEST", "=========================") +// } + + val incoming = aliceSession.cryptoService().getIncomingRoomKeyRequests().firstOrNull { it.requestId == outGoingRequestId } + incoming != null + } + } + + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + // DEBUG LOGS + aliceSession2.cryptoService().getOutgoingRoomKeyRequests().forEach { keyRequest -> Log.v("TEST", "=========================") - it.forEach { keyRequest -> - Log.v( - "TEST", - "[ts${keyRequest.localCreationTimestamp}] requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId} is ${keyRequest.state}" - ) - } + Log.v("TEST", "requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId}") + Log.v("TEST", "replies -> ${keyRequest.results.joinToString { it.toString() }}") Log.v("TEST", "=========================") } - val incoming = aliceSession.cryptoService().getIncomingRoomKeyRequests().firstOrNull { it.requestId == outGoingRequestId } - incoming?.state == GossipingRequestState.REJECTED + val outgoing = aliceSession2.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.requestId == outGoingRequestId } + val reply = outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val resultCode = (reply?.result as? RequestResult.Failure)?.code + resultCode == WithHeldCode.UNVERIFIED } } @@ -175,254 +185,301 @@ class KeyShareTests : InstrumentedTest { // Re request aliceSession2.cryptoService().reRequestRoomKeyForEvent(receivedEvent.root) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - aliceSession.cryptoService().getIncomingRoomKeyRequests().let { - Log.v("TEST", "Incoming request Session 1") - Log.v("TEST", "=========================") - it.forEach { - Log.v("TEST", "requestId ${it.requestId}, for sessionId ${it.requestBody?.sessionId} is ${it.state}") - } - Log.v("TEST", "=========================") - - it.any { it.requestBody?.sessionId == eventMegolmSessionId && it.state == GossipingRequestState.ACCEPTED } - } - } - } - - Thread.sleep(6_000) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - aliceSession2.cryptoService().getOutgoingRoomKeyRequests().let { - it.any { it.requestBody?.sessionId == eventMegolmSessionId && it.state == OutgoingGossipingRequestState.CANCELLED } - } - } - } - - try { - commonTestHelper.runBlockingTest { - aliceSession2.cryptoService().decryptEvent(receivedEvent.root, "foo") - } - } catch (failure: Throwable) { - fail("should have been able to decrypt") - } + cryptoTestHelper.ensureCanDecrypt(listOf(receivedEvent.eventId), aliceSession2, roomId, listOf(sentEventText ?: "")) commonTestHelper.signOutAndClose(aliceSession) commonTestHelper.signOutAndClose(aliceSession2) } + // See E2ESanityTest for a test regarding secret sharing + + /** + * Test that the sender of a message accepts to re-share to another user + * if the key was originally shared with him + */ @Test - @Ignore("This test will be ignored until it is fixed") - fun test_ShareSSSSSecret() { - val aliceSession1 = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) + fun test_reShareIfWasIntendedToBeShared() { + val commonTestHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(commonTestHelper) - commonTestHelper.doSync { - aliceSession1.cryptoService().crossSigningService() - .initializeCrossSigning( - object : UserInteractiveAuthInterceptor { - override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { - promise.resume( - UserPasswordAuth( - user = aliceSession1.myUserId, - password = TestConstants.PASSWORD - ) - ) - } - }, it - ) - } + val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) + val aliceSession = testData.firstSession + val roomFromAlice = aliceSession.getRoom(testData.roomId)!! + val bobSession = testData.secondSession!! - // Also bootstrap keybackup on first session - val creationInfo = commonTestHelper.doSync { - aliceSession1.cryptoService().keysBackupService().prepareKeysBackupVersion(null, null, it) - } - val version = commonTestHelper.doSync { - aliceSession1.cryptoService().keysBackupService().createKeysBackupVersion(creationInfo, it) - } - // Save it for gossiping - aliceSession1.cryptoService().keysBackupService().saveBackupRecoveryKey(creationInfo.recoveryKey, version = version.version) + val sentEvent = commonTestHelper.sendTextMessage(roomFromAlice, "Hello", 1).first() + val sentEventMegolmSession = sentEvent.root.content.toModel()!!.sessionId!! - val aliceSession2 = commonTestHelper.logIntoAccount(aliceSession1.myUserId, SessionTestParams(true)) + // bob should be able to decrypt + cryptoTestHelper.ensureCanDecrypt(listOf(sentEvent.eventId), bobSession, testData.roomId, listOf(sentEvent.getLastMessageContent()?.body ?: "")) - val aliceVerificationService1 = aliceSession1.cryptoService().verificationService() - val aliceVerificationService2 = aliceSession2.cryptoService().verificationService() - - // force keys download - commonTestHelper.doSync> { - aliceSession1.cryptoService().downloadKeys(listOf(aliceSession1.myUserId), true, it) - } - commonTestHelper.doSync> { - aliceSession2.cryptoService().downloadKeys(listOf(aliceSession2.myUserId), true, it) - } - - var session1ShortCode: String? = null - var session2ShortCode: String? = null - - aliceVerificationService1.addListener(object : VerificationService.Listener { - override fun transactionUpdated(tx: VerificationTransaction) { - Log.d("#TEST", "AA: tx incoming?:${tx.isIncoming} state ${tx.state}") - if (tx is SasVerificationTransaction) { - if (tx.state == VerificationTxState.OnStarted) { - (tx as IncomingSasVerificationTransaction).performAccept() - } - if (tx.state == VerificationTxState.ShortCodeReady) { - session1ShortCode = tx.getDecimalCodeRepresentation() - Thread.sleep(500) - tx.userHasVerifiedShortCode() - } - } - } - }) - - aliceVerificationService2.addListener(object : VerificationService.Listener { - override fun transactionUpdated(tx: VerificationTransaction) { - Log.d("#TEST", "BB: tx incoming?:${tx.isIncoming} state ${tx.state}") - if (tx is SasVerificationTransaction) { - if (tx.state == VerificationTxState.ShortCodeReady) { - session2ShortCode = tx.getDecimalCodeRepresentation() - Thread.sleep(500) - tx.userHasVerifiedShortCode() - } - } - } - }) - - val txId = "m.testVerif12" - aliceVerificationService2.beginKeyVerification( - VerificationMethod.SAS, aliceSession1.myUserId, aliceSession1.sessionParams.deviceId - ?: "", txId - ) + // Let's try to request any how. + // As it was share previously alice should accept to reshare + bobSession.cryptoService().reRequestRoomKeyForEvent(sentEvent.root) commonTestHelper.waitWithLatch { latch -> commonTestHelper.retryPeriodicallyWithLatch(latch) { - aliceSession1.cryptoService().getDeviceInfo(aliceSession1.myUserId, aliceSession2.sessionParams.deviceId ?: "")?.isVerified == true + val outgoing = bobSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val aliceReply = outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + aliceReply != null && aliceReply.result is RequestResult.Success } } - - assertNotNull(session1ShortCode) - Log.d("#TEST", "session1ShortCode: $session1ShortCode") - assertNotNull(session2ShortCode) - Log.d("#TEST", "session2ShortCode: $session2ShortCode") - assertEquals(session1ShortCode, session2ShortCode) - - // SSK and USK private keys should have been shared - - commonTestHelper.waitWithLatch(60_000) { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - Log.d("#TEST", "CAN XS :${aliceSession2.cryptoService().crossSigningService().getMyCrossSigningKeys()}") - aliceSession2.cryptoService().crossSigningService().canCrossSign() - } - } - - // Test that key backup key has been shared to - commonTestHelper.waitWithLatch(60_000) { latch -> - val keysBackupService = aliceSession2.cryptoService().keysBackupService() - commonTestHelper.retryPeriodicallyWithLatch(latch) { - Log.d("#TEST", "Recovery :${keysBackupService.getKeyBackupRecoveryKeyInfo()?.recoveryKey}") - keysBackupService.getKeyBackupRecoveryKeyInfo()?.recoveryKey == creationInfo.recoveryKey - } - } - - commonTestHelper.signOutAndClose(aliceSession1) - commonTestHelper.signOutAndClose(aliceSession2) } + /** + * Test that our own devices accept to reshare to unverified device if it was shared initialy + * if the key was originally shared with him + */ @Test - @Ignore("This test will be ignored until it is fixed") - fun test_ImproperKeyShareBug() { - val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) + fun test_reShareToUnverifiedIfWasIntendedToBeShared() { + val commonTestHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(commonTestHelper) - commonTestHelper.doSync { - aliceSession.cryptoService().crossSigningService() - .initializeCrossSigning( - object : UserInteractiveAuthInterceptor { - override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { - promise.resume( - UserPasswordAuth( - user = aliceSession.myUserId, - password = TestConstants.PASSWORD, - session = flowResponse.session - ) - ) - } - }, it - ) + val testData = cryptoTestHelper.doE2ETestWithAliceInARoom(true) + val aliceSession = testData.firstSession + val roomFromAlice = aliceSession.getRoom(testData.roomId)!! + + val aliceNewSession = commonTestHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) + + // we wait for alice first session to be aware of that session? + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val newSession = aliceSession.cryptoService().getUserDevices(aliceSession.myUserId) + .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } + newSession != null + } } + val sentEvent = commonTestHelper.sendTextMessage(roomFromAlice, "Hello", 1).first() + val sentEventMegolmSession = sentEvent.root.content.toModel()!!.sessionId!! - // Create an encrypted room and send a couple of messages - val roomId = commonTestHelper.runBlockingTest { - aliceSession.roomService().createRoom( - CreateRoomParams().apply { - visibility = RoomDirectoryVisibility.PRIVATE - enableEncryption() - } - ) + // Let's try to request any how. + // As it was share previously alice should accept to reshare + aliceNewSession.cryptoService().reRequestRoomKeyForEvent(sentEvent.root) + + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = + outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + ownDeviceReply != null && ownDeviceReply.result is RequestResult.Success + } } - val roomAlicePov = aliceSession.getRoom(roomId) - assertNotNull(roomAlicePov) - Thread.sleep(1_000) - assertTrue(roomAlicePov?.roomCryptoService()?.isEncrypted() == true) - val secondEventId = commonTestHelper.sendTextMessage(roomAlicePov!!, "Message", 3)[1].eventId + } - // Create bob session + /** + * Tests that keys reshared with own verified session are done from the earliest known index + */ + @Test + fun test_reShareFromTheEarliestKnownIndexWithOwnVerifiedSession() { + val commonTestHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(commonTestHelper) - val bobSession = commonTestHelper.createAccount(TestConstants.USER_BOB, SessionTestParams(true)) - commonTestHelper.doSync { - bobSession.cryptoService().crossSigningService() - .initializeCrossSigning( - object : UserInteractiveAuthInterceptor { - override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { - promise.resume( - UserPasswordAuth( - user = bobSession.myUserId, - password = TestConstants.PASSWORD, - session = flowResponse.session - ) - ) - } - }, it - ) - } + val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) + val aliceSession = testData.firstSession + val bobSession = testData.secondSession!! + val roomFromBob = bobSession.getRoom(testData.roomId)!! - // Let alice invite bob - commonTestHelper.runBlockingTest { - roomAlicePov.membershipService().invite(bobSession.myUserId, null) - } + val sentEvents = commonTestHelper.sendTextMessage(roomFromBob, "Hello", 3) + val sentEventMegolmSession = sentEvents.first().root.content.toModel()!!.sessionId!! - commonTestHelper.runBlockingTest { - bobSession.roomService().joinRoom(roomAlicePov.roomId, null, emptyList()) - } + // Let alice now add a new session + val aliceNewSession = commonTestHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(false)) + aliceNewSession.cryptoService().enableKeyGossiping(false) + commonTestHelper.syncSession(aliceNewSession) - // we want to discard alice outbound session - aliceSession.cryptoService().discardOutboundSession(roomAlicePov.roomId) - - // and now resend a new message to reset index to 0 - commonTestHelper.sendTextMessage(roomAlicePov, "After", 1) - - val roomRoomBobPov = aliceSession.getRoom(roomId) - val beforeJoin = roomRoomBobPov!!.getTimelineEvent(secondEventId) - - var dRes = tryOrNull { - commonTestHelper.runBlockingTest { - bobSession.cryptoService().decryptEvent(beforeJoin!!.root, "") + // we wait bob first session to be aware of that session? + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val newSession = bobSession.cryptoService().getUserDevices(aliceSession.myUserId) + .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } + newSession != null } } - assert(dRes == null) + val newEvent = commonTestHelper.sendTextMessage(roomFromBob, "The New", 1).first() + val newEventId = newEvent.eventId + val newEventText = newEvent.getLastMessageContent()!!.body - // Try to re-ask the keys + // alice should be able to decrypt the new one + cryptoTestHelper.ensureCanDecrypt(listOf(newEventId), aliceNewSession, testData.roomId, listOf(newEventText)) + // but not the first one! + cryptoTestHelper.ensureCannotDecrypt(sentEvents.map { it.eventId }, aliceNewSession, testData.roomId) - bobSession.cryptoService().reRequestRoomKeyForEvent(beforeJoin!!.root) + // All should be using the same session id + sentEvents.forEach { + assertEquals(sentEventMegolmSession, it.root.content.toModel()!!.sessionId) + } + assertEquals(sentEventMegolmSession, newEvent.root.content.toModel()!!.sessionId) - Thread.sleep(3_000) + // Request a first time, bob should reply with unauthorized and alice should reply with unverified + aliceNewSession.cryptoService().enableKeyGossiping(true) + aliceNewSession.cryptoService().reRequestRoomKeyForEvent(newEvent.root) - // With the bug the first session would have improperly reshare that key :/ - dRes = tryOrNull { - commonTestHelper.runBlockingTest { - bobSession.cryptoService().decryptEvent(beforeJoin.root, "") + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = outgoing?.results + ?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val result = ownDeviceReply?.result + Log.v("TEST", "own device result is $result") + result != null && result is RequestResult.Failure && result.code == WithHeldCode.UNVERIFIED } } - Log.d("#TEST", "KS: sgould not decrypt that ${beforeJoin.root.getClearContent().toModel()?.body}") - assert(dRes?.clearEvent == null) + + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val bobDeviceReply = outgoing?.results + ?.firstOrNull { it.userId == bobSession.myUserId && it.fromDevice == bobSession.sessionParams.deviceId } + val result = bobDeviceReply?.result + Log.v("TEST", "bob device result is $result") + result != null && result is RequestResult.Success && result.chainIndex > 0 + } + } + + // it's a success but still can't decrypt first message + cryptoTestHelper.ensureCannotDecrypt(sentEvents.map { it.eventId }, aliceNewSession, testData.roomId) + + // Mark the new session as verified + aliceSession.cryptoService() + .verificationService() + .markedLocallyAsManuallyVerified(aliceNewSession.myUserId, aliceNewSession.sessionParams.deviceId!!) + + // Let's now try to request + aliceNewSession.cryptoService().reRequestRoomKeyForEvent(sentEvents.first().root) + + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + // DEBUG LOGS + aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().forEach { keyRequest -> + Log.v("TEST", "=========================") + Log.v("TEST", "requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId}") + Log.v("TEST", "replies -> ${keyRequest.results.joinToString { it.toString() }}") + Log.v("TEST", "=========================") + } + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = + outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val result = ownDeviceReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 0 + } + } + + // now the new session should be able to decrypt all! + cryptoTestHelper.ensureCanDecrypt( + sentEvents.map { it.eventId }, + aliceNewSession, + testData.roomId, + sentEvents.map { it.getLastMessageContent()!!.body } + ) + + // Additional test, can we check that bob replied successfully but with a ratcheted key + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val bobReply = outgoing?.results?.firstOrNull { it.userId == bobSession.myUserId } + val result = bobReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 3 + } + } + + commonTestHelper.signOutAndClose(aliceNewSession) + commonTestHelper.signOutAndClose(aliceSession) + commonTestHelper.signOutAndClose(bobSession) + } + + /** + * Tests that we don't cancel a request to early on first forward if the index is not good enough + */ + @Test + fun test_dontCancelToEarly() { + val commonTestHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(commonTestHelper) + + val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) + val aliceSession = testData.firstSession + val bobSession = testData.secondSession!! + val roomFromBob = bobSession.getRoom(testData.roomId)!! + + val sentEvents = commonTestHelper.sendTextMessage(roomFromBob, "Hello", 3) + val sentEventMegolmSession = sentEvents.first().root.content.toModel()!!.sessionId!! + + // Let alice now add a new session + val aliceNewSession = commonTestHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) + + // we wait bob first session to be aware of that session? + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val newSession = bobSession.cryptoService().getUserDevices(aliceSession.myUserId) + .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } + newSession != null + } + } + + val newEvent = commonTestHelper.sendTextMessage(roomFromBob, "The New", 1).first() + val newEventId = newEvent.eventId + val newEventText = newEvent.getLastMessageContent()!!.body + + // alice should be able to decrypt the new one + cryptoTestHelper.ensureCanDecrypt(listOf(newEventId), aliceNewSession, testData.roomId, listOf(newEventText)) + // but not the first one! + cryptoTestHelper.ensureCannotDecrypt(sentEvents.map { it.eventId }, aliceNewSession, testData.roomId) + + // All should be using the same session id + sentEvents.forEach { + assertEquals(sentEventMegolmSession, it.root.content.toModel()!!.sessionId) + } + assertEquals(sentEventMegolmSession, newEvent.root.content.toModel()!!.sessionId) + + // Mark the new session as verified + aliceSession.cryptoService() + .verificationService() + .markedLocallyAsManuallyVerified(aliceNewSession.myUserId, aliceNewSession.sessionParams.deviceId!!) + + // /!\ Stop initial alice session syncing so that it can't reply + aliceSession.cryptoService().enableKeyGossiping(false) + aliceSession.stopSync() + + // Let's now try to request + aliceNewSession.cryptoService().reRequestRoomKeyForEvent(sentEvents.first().root) + + // Should get a reply from bob and not from alice + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + // Log.d("#TEST", "outgoing key requests :${aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().joinToString { it.sessionId ?: "?" }}") + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val bobReply = outgoing?.results?.firstOrNull { it.userId == bobSession.myUserId } + val result = bobReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 3 + } + } + + val outgoingReq = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + + assertNull("We should not have a reply from first session", outgoingReq!!.results.firstOrNull { it.fromDevice == aliceSession.sessionParams.deviceId }) + assertEquals("The request should not be canceled", OutgoingRoomKeyRequestState.SENT, outgoingReq.state) + + // let's wake up alice + aliceSession.cryptoService().enableKeyGossiping(true) + aliceSession.startSync(true) + + // We should now get a reply from first session + commonTestHelper.waitWithLatch { latch -> + commonTestHelper.retryPeriodicallyWithLatch(latch) { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = + outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val result = ownDeviceReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 0 + } + } + + // It should be in sent then cancel + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + assertEquals("The request should be canceled", OutgoingRoomKeyRequestState.SENT_THEN_CANCELED, outgoing!!.state) + + commonTestHelper.signOutAndClose(aliceNewSession) + commonTestHelper.signOutAndClose(aliceSession) + commonTestHelper.signOutAndClose(bobSession) } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index b3896b02de..1c3c6c46e7 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -21,7 +21,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.Assert import org.junit.FixMethodOrder -import org.junit.Ignore +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -29,6 +29,7 @@ import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.NoOpMatrixCallback import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.session.crypto.MXCryptoError +import org.matrix.android.sdk.api.session.crypto.RequestResult import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode @@ -38,6 +39,7 @@ import org.matrix.android.sdk.api.session.room.getTimelineEvent import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CryptoTestHelper import org.matrix.android.sdk.common.MockOkHttpInterceptor +import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -46,12 +48,13 @@ import org.matrix.android.sdk.common.TestConstants @LargeTest class WithHeldTests : InstrumentedTest { - private val testHelper = CommonTestHelper(context()) - private val cryptoTestHelper = CryptoTestHelper(testHelper) + @get:Rule val rule = RetryTestRule(3) @Test - @Ignore("This test will be ignored until it is fixed") fun test_WithHeldUnverifiedReason() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + // ============================= // ARRANGE // ============================= @@ -69,7 +72,6 @@ class WithHeldTests : InstrumentedTest { val roomAlicePOV = aliceSession.getRoom(roomId)!! val bobUnverifiedSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(true)) - // ============================= // ACT // ============================= @@ -88,6 +90,7 @@ class WithHeldTests : InstrumentedTest { val eventBobPOV = bobUnverifiedSession.getRoom(roomId)?.getTimelineEvent(timelineEvent.eventId)!! + val megolmSessionId = eventBobPOV.root.content.toModel()!!.sessionId!! // ============================= // ASSERT // ============================= @@ -106,6 +109,20 @@ class WithHeldTests : InstrumentedTest { Assert.assertEquals("Cause should be unverified", WithHeldCode.UNVERIFIED.value, technicalMessage) } + // Let's see if the reply we got from bob first session is unverified + testHelper.waitWithLatch { latch -> + testHelper.retryPeriodicallyWithLatch(latch) { + bobUnverifiedSession.cryptoService().getOutgoingRoomKeyRequests() + .firstOrNull { it.sessionId == megolmSessionId } + ?.results + ?.firstOrNull { it.fromDevice == bobSession.sessionParams.deviceId } + ?.result + ?.let { + it as? RequestResult.Failure + } + ?.code == WithHeldCode.UNVERIFIED + } + } // enable back sending to unverified aliceSession.cryptoService().setGlobalBlacklistUnverifiedDevices(false) @@ -139,8 +156,10 @@ class WithHeldTests : InstrumentedTest { } @Test - @Ignore("This test will be ignored until it is fixed") fun test_WithHeldNoOlm() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = testData.firstSession val bobSession = testData.secondSession!! @@ -220,8 +239,10 @@ class WithHeldTests : InstrumentedTest { } @Test - @Ignore("This test will be ignored until it is fixed") fun test_WithHeldKeyRequest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = testData.firstSession val bobSession = testData.secondSession!! @@ -267,5 +288,8 @@ class WithHeldTests : InstrumentedTest { wc?.code == WithHeldCode.UNAUTHORISED } } + + testHelper.signOutAndClose(aliceSession) + testHelper.signOutAndClose(bobSecondSession) } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index a7ddb6c553..9136272b1e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -24,7 +24,6 @@ import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.FixMethodOrder -import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith 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.KeysBackupStateListener 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.KeysVersionResult 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.model.ImportRoomKeysResult @@ -54,18 +55,16 @@ import java.util.concurrent.CountDownLatch @LargeTest 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 * - Check backup keys after having marked one as backed up * - Reset keys backup markers */ @Test - @Ignore("This test will be ignored until it is fixed") fun roomKeysTest_testBackupStore_ok() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() // From doE2ETestWithAliceAndBobInARoomWithEncryptedMessages, we should have no backed up keys @@ -104,6 +103,8 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun prepareKeysBackupVersionTest() { + val testHelper = CommonTestHelper(context()) + val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) assertNotNull(bobSession.cryptoService().keysBackupService()) @@ -132,7 +133,11 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun createKeysBackupVersionTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) + cryptoTestHelper.initializeCrossSigning(bobSession) val keysBackup = bobSession.cryptoService().keysBackupService() @@ -147,13 +152,46 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled) // Create the version - testHelper.doSync { + val version = testHelper.doSync { keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) } // Backup must be enable now assertTrue(keysBackup.isEnabled) + // Check that it's signed with MSK + val versionResult = testHelper.doSync { + keysBackup.getVersion(version.version, it) + } + val trust = testHelper.doSync { + 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) testHelper.signOutAndClose(bobSession) } @@ -163,8 +201,11 @@ class KeysBackupTest : InstrumentedTest { * - Check the backup completes */ @Test - @Ignore("This test will be ignored until it is fixed") fun backupAfterCreateKeysBackupVersionTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() keysBackupTestHelper.waitForKeybackUpBatching() @@ -204,8 +245,11 @@ class KeysBackupTest : InstrumentedTest { * Check that backupAllGroupSessions() returns valid data */ @Test - @Ignore("This test will be ignored until it is fixed") fun backupAllGroupSessionsTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() @@ -249,8 +293,11 @@ class KeysBackupTest : InstrumentedTest { * - Compare the decrypted megolm key with the original one */ @Test - @Ignore("This test will be ignored until it is fixed") fun testEncryptAndDecryptKeysBackupData() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService @@ -293,8 +340,11 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - @Ignore("This test will be ignored until it is fixed") fun restoreKeysBackupTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - 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 */ @Test - @Ignore("This test will be ignored until it is fixed") 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 // - And log Alice on a new device val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -438,8 +491,11 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - @Ignore("This test will be ignored until it is fixed") 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 // - And log Alice on a new device val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -496,8 +552,11 @@ class KeysBackupTest : InstrumentedTest { * - The backup must still be untrusted and disabled */ @Test - @Ignore("This test will be ignored until it is fixed") 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 // - And log Alice on a new device val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -538,8 +597,11 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - @Ignore("This test will be ignored until it is fixed") fun trustKeyBackupVersionWithPasswordTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val password = "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 */ @Test - @Ignore("This test will be ignored until it is fixed") fun trustKeyBackupVersionWithWrongPasswordTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val password = "Password" val badPassword = "Bad Password" @@ -639,8 +704,11 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - @Ignore("This test will be ignored until it is fixed") fun restoreKeysBackupWithAWrongRecoveryKeyTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Try to restore the e2e backup with a wrong recovery key @@ -673,8 +741,11 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - @Ignore("This test will be ignored until it is fixed") fun testBackupWithPassword() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val password = "password" val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password) @@ -730,8 +801,11 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - @Ignore("This test will be ignored until it is fixed") fun restoreKeysBackupWithAWrongPasswordTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val password = "password" val wrongPassword = "passw0rd" @@ -767,8 +841,11 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - @Ignore("This test will be ignored until it is fixed") fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val password = "password" val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password) @@ -797,8 +874,11 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - @Ignore("This test will be ignored until it is fixed") fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Try to restore the e2e backup with a password @@ -829,8 +909,11 @@ class KeysBackupTest : InstrumentedTest { * - Check the returned KeysVersionResult is trusted */ @Test - @Ignore("This test will be ignored until it is fixed") fun testIsKeysBackupTrusted() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + // - Create a backup version val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -855,7 +938,7 @@ class KeysBackupTest : InstrumentedTest { assertTrue(keysBackupVersionTrust.usable) assertEquals(1, keysBackupVersionTrust.signatures.size) - val signature = keysBackupVersionTrust.signatures[0] + val signature = keysBackupVersionTrust.signatures[0] as KeysBackupVersionTrustSignature.DeviceSignature assertTrue(signature.valid) assertNotNull(signature.device) assertEquals(cryptoTestData.firstSession.cryptoService().getMyDevice().deviceId, signature.deviceId) @@ -865,66 +948,6 @@ class KeysBackupTest : InstrumentedTest { 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 * @@ -935,6 +958,10 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun testBackupWhenAnotherBackupWasCreated() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + // - Create a backup version val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -1005,8 +1032,11 @@ class KeysBackupTest : InstrumentedTest { * -> It must success */ @Test - @Ignore("This test will be ignored until it is fixed") fun testBackupAfterVerifyingADevice() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + // - Create a backup version val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -1039,6 +1069,8 @@ class KeysBackupTest : InstrumentedTest { // - Try to backup all in aliceSession2, it must fail val keysBackup2 = aliceSession2.cryptoService().keysBackupService() + assertFalse("Backup should not be enabled", keysBackup2.isEnabled) + val stateObserver2 = StateObserver(keysBackup2) var isSuccessful = false @@ -1056,8 +1088,8 @@ class KeysBackupTest : InstrumentedTest { assertFalse(isSuccessful) // Backup state must be NotTrusted - assertEquals(KeysBackupState.NotTrusted, keysBackup2.state) - assertFalse(keysBackup2.isEnabled) + assertEquals("Backup state must be NotTrusted", KeysBackupState.NotTrusted, keysBackup2.state) + assertFalse("Backup should not be enabled", keysBackup2.isEnabled) // - Validate the old device from the new one aliceSession2.cryptoService().setDeviceVerification( @@ -1103,6 +1135,10 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun deleteKeysBackupTest() { + val testHelper = CommonTestHelper(context()) + val cryptoTestHelper = CryptoTestHelper(testHelper) + val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) + // - Create a backup version val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt index 90e7fc1e45..2220536e28 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -106,14 +106,14 @@ internal class KeysBackupTestHelper( Assert.assertNotNull(megolmBackupCreationInfo) - Assert.assertFalse(keysBackup.isEnabled) + Assert.assertFalse("Key backup should not be enabled before creation", keysBackup.isEnabled) // Create the version val keysVersion = testHelper.doSync { keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) } - Assert.assertNotNull(keysVersion.version) + Assert.assertNotNull("Key backup version should not be null", keysVersion.version) // Backup must be enable now Assert.assertTrue(keysBackup.isEnabled) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index 6097bf8c93..ceebc3cd01 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -19,7 +19,6 @@ package org.matrix.android.sdk.internal.crypto.verification.qrcode import androidx.test.ext.junit.runners.AndroidJUnit4 import org.amshove.kluent.shouldBe import org.junit.FixMethodOrder -import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @@ -28,11 +27,13 @@ import org.matrix.android.sdk.api.auth.UIABaseAuth import org.matrix.android.sdk.api.auth.UserInteractiveAuthInterceptor import org.matrix.android.sdk.api.auth.UserPasswordAuth import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse +import org.matrix.android.sdk.api.session.crypto.verification.CancelCode import org.matrix.android.sdk.api.session.crypto.verification.PendingVerificationRequest import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod import org.matrix.android.sdk.api.session.crypto.verification.VerificationService import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CryptoTestHelper +import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import java.util.concurrent.CountDownLatch import kotlin.coroutines.Continuation @@ -40,7 +41,6 @@ import kotlin.coroutines.resume @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) -@Ignore("This test is flaky ; see issue #5449") class VerificationTest : InstrumentedTest { data class ExpectedResult( @@ -254,4 +254,48 @@ class VerificationTest : InstrumentedTest { cryptoTestData.cleanUp(testHelper) } + + @Test + fun test_selfVerificationAcceptedCancelsItForOtherSessions() { + val defaultSessionParams = SessionTestParams(true) + val testHelper = CommonTestHelper(context()) + + val aliceSessionToVerify = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) + val aliceSessionThatVerifies = testHelper.logIntoAccount(aliceSessionToVerify.myUserId, TestConstants.PASSWORD, defaultSessionParams) + val aliceSessionThatReceivesCanceledEvent = testHelper.logIntoAccount(aliceSessionToVerify.myUserId, TestConstants.PASSWORD, defaultSessionParams) + + val verificationMethods = listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW) + + val serviceOfVerified = aliceSessionToVerify.cryptoService().verificationService() + val serviceOfVerifier = aliceSessionThatVerifies.cryptoService().verificationService() + val serviceOfUserWhoReceivesCancellation = aliceSessionThatReceivesCanceledEvent.cryptoService().verificationService() + + serviceOfVerifier.addListener(object : VerificationService.Listener { + override fun verificationRequestCreated(pr: PendingVerificationRequest) { + // Accept verification request + serviceOfVerifier.readyPendingVerification( + verificationMethods, + pr.otherUserId, + pr.transactionId!!, + ) + } + }) + + serviceOfVerified.requestKeyVerification( + methods = verificationMethods, + otherUserId = aliceSessionToVerify.myUserId, + otherDevices = listOfNotNull(aliceSessionThatVerifies.sessionParams.deviceId, aliceSessionThatReceivesCanceledEvent.sessionParams.deviceId), + ) + + testHelper.waitWithLatch { latch -> + testHelper.retryPeriodicallyWithLatch(latch) { + val requests = serviceOfUserWhoReceivesCancellation.getExistingVerificationRequests(aliceSessionToVerify.myUserId) + requests.any { it.cancelConclusion == CancelCode.AcceptedByAnotherDevice } + } + } + + testHelper.signOutAndClose(aliceSessionToVerify) + testHelper.signOutAndClose(aliceSessionThatVerifies) + testHelper.signOutAndClose(aliceSessionThatReceivesCanceledEvent) + } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt index d5b4a07fc0..e407c1b42d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt @@ -140,9 +140,24 @@ class TimelineForwardPaginationTest : InstrumentedTest { aliceTimeline.hasMoreToLoad(Timeline.Direction.BACKWARDS).shouldBeFalse() assertEquals(EventType.STATE_ROOM_CREATE, snapshot.lastOrNull()?.root?.getClearType()) - // 6 for room creation item (backward pagination), 1 for the context, and 50 for the forward pagination - // 6 + 1 + 50 - assertEquals(57, snapshot.size) + + // We explicitly test all the types we expect here, as we expect 51 messages and "some" state events + // But state events can change over time. So this acts as a kinda documentation of what we expect and + // provides a good error message if it doesn't match + + val snapshotTypes = mutableMapOf() + snapshot.groupingBy { it -> it.root.type }.eachCountTo(snapshotTypes) + // Some state events on room creation + assertEquals("m.room.name", 1, snapshotTypes.remove("m.room.name")) + assertEquals("m.room.guest_access", 1, snapshotTypes.remove("m.room.guest_access")) + assertEquals("m.room.history_visibility", 1, snapshotTypes.remove("m.room.history_visibility")) + assertEquals("m.room.join_rules", 1, snapshotTypes.remove("m.room.join_rules")) + assertEquals("m.room.power_levels", 1, snapshotTypes.remove("m.room.power_levels")) + assertEquals("m.room.create", 1, snapshotTypes.remove("m.room.create")) + assertEquals("m.room.member", 1, snapshotTypes.remove("m.room.member")) + // 50 from pagination + 1 context + assertEquals("m.room.message", 51, snapshotTypes.remove("m.room.message")) + assertEquals("Additional events found in timeline", setOf(), snapshotTypes.keys) } // Alice paginates once again FORWARD for 50 events @@ -152,8 +167,8 @@ class TimelineForwardPaginationTest : InstrumentedTest { val snapshot = runBlocking { aliceTimeline.awaitPaginate(Timeline.Direction.FORWARDS, 50) } - // 6 for room creation item (backward pagination),and numberOfMessagesToSend (all the message of the room) - snapshot.size == 6 + numberOfMessagesToSend && + // 7 for room creation item (backward pagination),and numberOfMessagesToSend (all the message of the room) + snapshot.size == 7 + numberOfMessagesToSend && snapshot.checkSendOrder(message, numberOfMessagesToSend, 0) // The timeline is fully loaded diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt index 6e5fed8df9..1a36adec44 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt @@ -74,8 +74,12 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { Timber.w(" event ${it.root}") } - // Ok, we have the 8 first messages of the initial sync (room creation and bob invite and join events) - snapshot.size == 8 + // Ok, we have the 9 first messages of the initial sync (room creation and bob invite and join events) + // create + // join alice + // power_levels, join_rules, history_visibility, guest_access, name + // invite, join bob + snapshot.size == 9 } bobTimeline.addListener(eventsListener) @@ -192,7 +196,7 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { Timber.w(" event ${it.root}") } - snapshot.size == 44 // 8 + 1 + 35 + snapshot.size == 45 // 9 + 1 + 35 } bobTimeline.addListener(eventsListener) @@ -220,8 +224,8 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { // Bob can see the first event of the room (so Back pagination has worked) snapshot.lastOrNull()?.root?.getClearType() == EventType.STATE_ROOM_CREATE && - // 8 for room creation item 60 message from Alice - snapshot.size == 68 && // 8 + 60 + // 9 for room creation item 60 message from Alice + snapshot.size == 69 && // 9 + 60U snapshot.checkSendOrder(secondMessage, 30, 0) && snapshot.checkSendOrder(firstMessage, 30, 30) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/Matrix.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/Matrix.kt index e7d1e64a2b..979201706b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/Matrix.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/Matrix.kt @@ -38,15 +38,18 @@ import org.matrix.android.sdk.internal.util.BackgroundDetectionObserver import org.matrix.android.sdk.internal.worker.MatrixWorkerFactory import org.matrix.olm.OlmManager import java.util.concurrent.Executors -import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject /** * This is the main entry point to the matrix sdk. *
- * 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 authenticationService: AuthenticationService @@ -61,89 +64,72 @@ class Matrix private constructor(context: Context, matrixConfiguration: MatrixCo @Inject internal lateinit var lightweightSettingsStorage: LightweightSettingsStorage init { - Monarchy.init(context) - DaggerMatrixComponent.factory().create(context, matrixConfiguration).inject(this) - if (context.applicationContext !is Configuration.Provider) { + val appContext = context.applicationContext + Monarchy.init(appContext) + DaggerMatrixComponent.factory().create(appContext, matrixConfiguration).inject(this) + if (appContext !is Configuration.Provider) { val configuration = Configuration.Builder() .setExecutor(Executors.newCachedThreadPool()) .setWorkerFactory(matrixWorkerFactory) .build() - WorkManager.initialize(context, configuration) + WorkManager.initialize(appContext, configuration) } 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 + /** + * Return the AuthenticationService. + */ fun authenticationService() = authenticationService + /** + * Return the RawService. + */ fun rawService() = rawService + /** + * Return the LightweightSettingsStorage. + */ fun lightweightSettingsStorage() = lightweightSettingsStorage + /** + * Return the 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 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) { apiInterceptor.addListener(path, listener) } + /** + * Un-register an API interceptor. + */ fun unregisterApiInterceptorListener(path: ApiPath, listener: ApiInterceptorListener) { apiInterceptor.removeListener(path, listener) } 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. - * 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 + * @return a String with details about the Matrix SDK version. */ fun getSdkVersion(): String { return BuildConfig.SDK_VERSION + " (" + BuildConfig.GIT_SDK_REVISION + ")" diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixCallback.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixCallback.kt index 166ba8eab9..7cd450b5ad 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixCallback.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixCallback.kt @@ -23,7 +23,7 @@ package org.matrix.android.sdk.api interface MatrixCallback { /** - * On success method, default to no-op + * On success method, default to no-op. * @param data the data successfully returned from the async function */ fun onSuccess(data: T) { @@ -31,7 +31,7 @@ interface MatrixCallback { } /** - * On failure method, default to no-op + * On failure method, default to no-op. * @param failure the failure data returned from the async function */ fun onFailure(failure: Throwable) { @@ -40,6 +40,6 @@ interface MatrixCallback { } /** - * Basic no op implementation + * Basic no op implementation. */ class NoOpMatrixCallback : MatrixCallback diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConfiguration.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConfiguration.kt index f8472319fd..21106fba6c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConfiguration.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConfiguration.kt @@ -46,7 +46,7 @@ data class MatrixConfiguration( */ 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, /** @@ -62,16 +62,7 @@ data class MatrixConfiguration( */ val roomDisplayNameFallbackProvider: RoomDisplayNameFallbackProvider, /** - * Thread messages default enable/disabled value + * Thread messages default enable/disabled value. */ 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 - } -} +) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConstants.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConstants.kt index 49520f3678..33a820ddde 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConstants.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixConstants.kt @@ -17,7 +17,7 @@ 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 { /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt index 2a26b612fb..82f39806c0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixPatterns.kt @@ -147,7 +147,7 @@ object MatrixPatterns { } /** - * Extract server name from a matrix id + * Extract server name from a matrix id. * * @param matrixId * @return null if not found or if matrixId is null @@ -172,12 +172,12 @@ object MatrixPatterns { } /** - * Return the domain form a userId + * Return the domain form a userId. * Examples: * - "@alice:domain.org".getDomain() will return "domain.org" * - "@bob:domain.org:3455".getDomain() will return "domain.org:3455" */ - fun String.getDomain(): String { + fun String.getServerName(): String { if (BuildConfig.DEBUG && !isUserId(this)) { // They are some invalid userId localpart in the wild, but the domain part should be there anyway Timber.w("Not a valid user ID: $this") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixUrls.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixUrls.kt index 4a41eaec4a..7958186f16 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixUrls.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/MatrixUrls.kt @@ -17,21 +17,21 @@ 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 { /** - * "mxc" scheme, including "://". So "mxc://" + * "mxc" scheme, including "://". So "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) /** - * 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) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt index 9cb784c9c0..5a19df90c4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/AuthenticationService.kt @@ -40,12 +40,12 @@ interface AuthenticationService { suspend fun getLoginFlowOfSession(sessionId: String): LoginFlowResult /** - * Get a SSO url + * Get a SSO url. */ 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? @@ -64,17 +64,17 @@ interface AuthenticationService { 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 /** - * Cancel pending login or pending registration + * Cancel pending login or pending registration. */ suspend fun cancelPendingLoginOrRegistration() /** - * Reset all pending settings, including current HomeServerConnectionConfig + * Reset all pending settings, including current HomeServerConnectionConfig. */ suspend fun reset() @@ -91,20 +91,20 @@ interface AuthenticationService { fun getLastAuthenticatedSession(): Session? /** - * Create a session after a SSO successful login + * Create a session after a SSO successful login. */ suspend fun createSessionFromSso(homeServerConnectionConfig: HomeServerConnectionConfig, credentials: Credentials): Session /** - * Perform a wellknown request, using the domain from the matrixId + * Perform a wellknown request, using the domain from the matrixId. */ suspend fun getWellKnownData(matrixId: String, homeServerConnectionConfig: HomeServerConnectionConfig?): WellknownResult /** - * Authenticate with a matrixId and a password - * Usually call this after a successful call to getWellKnownData() + * Authenticate with a matrixId and a password. + * Usually call this after a successful call to getWellKnownData(). * @param homeServerConnectionConfig the information about the homeserver and other configuration * @param matrixId the matrixId of the user * @param password the password of the account diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/TokenBasedAuth.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/TokenBasedAuth.kt index e522352c38..2c99ced995 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/TokenBasedAuth.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/TokenBasedAuth.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.JsonClass 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) data class TokenBasedAuth( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/UserPasswordAuth.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/UserPasswordAuth.kt index e985c5f08a..8cd5b5e6eb 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/UserPasswordAuth.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/UserPasswordAuth.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.JsonClass 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) data class UserPasswordAuth( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/Credentials.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/Credentials.kt index 317acccfb5..e3728753ad 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/Credentials.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/Credentials.kt @@ -37,7 +37,7 @@ data class Credentials( */ @Json(name = "access_token") val accessToken: String, /** - * Not documented + * Not documented. */ @Json(name = "refresh_token") val refreshToken: String?, /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt index b490ac877e..e3815231d9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/SessionParams.kt @@ -22,12 +22,12 @@ package org.matrix.android.sdk.api.auth.data */ data class SessionParams( /** - * Please consider using shortcuts instead + * Please consider using shortcuts instead. */ val credentials: Credentials, /** - * Please consider using shortcuts instead + * Please consider using shortcuts instead. */ 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 /** - * The deviceId of the session (Ex: "ABCDEFGH") + * The deviceId of the session (Ex: "ABCDEFGH"). */ val deviceId = credentials.deviceId @@ -62,12 +62,12 @@ data class SessionParams( 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 /** - * 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() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnown.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnown.kt index 4bcef60605..10c7d51392 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnown.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnown.kt @@ -43,6 +43,7 @@ import org.matrix.android.sdk.api.util.JsonDict * } * } * + * . */ @JsonClass(generateAdapter = true) data class WellKnown( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnownBaseConfig.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnownBaseConfig.kt index ad6b9970de..df00099232 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnownBaseConfig.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/data/WellKnownBaseConfig.kt @@ -26,6 +26,7 @@ import com.squareup.moshi.JsonClass * "base_url": "https://vector.im" * } * + * . */ @JsonClass(generateAdapter = true) data class WellKnownBaseConfig( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt index 247d58ce79..3232025de3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/login/LoginWizard.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.util.JsonDict */ 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 diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt index 2b421f2873..1252e93b84 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationFlowResponse.kt @@ -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 { // Get all the returned stages diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/CryptoConstants.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/CryptoConstants.kt index 172cfa8360..37b9ac379e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/CryptoConstants.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/CryptoConstants.kt @@ -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" /** - * Secured Shared Storage algorithm constant + * Secured Shared Storage algorithm constant. */ const val SSSS_ALGORITHM_CURVE25519_AES_SHA2 = "m.secret_storage.v1.curve25519-aes-sha2" diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/Emojis.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/Emojis.kt index 9c0eb10970..85d6961384 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/Emojis.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/Emojis.kt @@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.EmojiRepresentatio 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 { return (0..63).map { getEmojiForCode(it) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/MXCryptoConfig.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/MXCryptoConfig.kt index 9a686de2e1..9507ddda65 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/MXCryptoConfig.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/crypto/MXCryptoConfig.kt @@ -31,5 +31,11 @@ data class MXCryptoConfig constructor( * If set to false, the request will be forwarded to the application layer; in this * case the application can decide to prompt the user. */ - val discardRoomKeyRequestsFromUntrustedDevices: Boolean = true + val discardRoomKeyRequestsFromUntrustedDevices: Boolean = true, + + /** + * Currently megolm keys are requested to the sender device and to all of our devices. + * You can limit request only to your sessions by turning this setting to `true` + */ + val limitRoomKeyRequestsToMyDevices: Boolean = false, ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt index e264843ea4..5e1350e327 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/extensions/Strings.kt @@ -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) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/Extensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/Extensions.kt index 362ebcec26..d3cc8fc8e4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/Extensions.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/Extensions.kt @@ -47,7 +47,7 @@ fun Throwable.shouldBeRetried() = this is Failure.NetworkConnection || 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 { return (this as? Failure.ServerError) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/InitialSyncRequestReason.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/InitialSyncRequestReason.kt index ebe07823f4..8bebbcc3a5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/InitialSyncRequestReason.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/InitialSyncRequestReason.kt @@ -17,11 +17,11 @@ 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 { /** - * 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, } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/MatrixError.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/MatrixError.kt index 32e1aca17d..3dbbc39564 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/MatrixError.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/failure/MatrixError.kt @@ -28,9 +28,9 @@ import org.matrix.android.sdk.api.util.JsonDict */ @JsonClass(generateAdapter = true) 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, - /** human-readable error message */ + /** human-readable error message. */ @Json(name = "error") val message: String, // 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. */ const val M_ROOM_IN_USE = "M_ROOM_IN_USE" - /** (Not documented yet) */ + /** (Not documented yet). */ const val M_BAD_PAGINATION = "M_BAD_PAGINATION" /** The request was not correctly authorized. Usually due to login failures. */ const val M_UNAUTHORIZED = "M_UNAUTHORIZED" - /** (Not documented yet) */ + /** (Not documented yet). */ const val M_OLD_VERSION = "M_OLD_VERSION" /** The server did not understand the request. */ 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" /** Authentication could not be performed on the third party identifier. */ @@ -122,7 +122,7 @@ data class MatrixError( /** The request or entity was 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" /** 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. */ 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" - /** (Not documented yet) */ + /** (Not documented yet). */ const val M_WEAK_PASSWORD = "M_WEAK_PASSWORD" /** The provided password's length is shorter than the minimum length required by the server. */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/federation/FederationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/federation/FederationService.kt index 0761ef8d21..8fe6460753 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/federation/FederationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/federation/FederationService.kt @@ -18,7 +18,7 @@ package org.matrix.android.sdk.api.federation interface FederationService { /** - * Get information about the homeserver + * Get information about the homeserver. */ suspend fun getFederationVersion(): FederationVersion } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/ProgressListener.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/ProgressListener.kt index 02ebd7f784..ec55348dc5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/ProgressListener.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/ProgressListener.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.api.listeners /** - * Interface to send a progress info + * Interface to send a progress info. */ interface ProgressListener { /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/StepProgressListener.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/StepProgressListener.kt index 0fabfed2ff..4b87507c02 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/StepProgressListener.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/listeners/StepProgressListener.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.api.listeners /** - * Interface to send a progress info + * Interface to send a progress info. */ interface StepProgressListener { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/logger/LoggerTag.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/logger/LoggerTag.kt index 44ac439d7b..ae65963f37 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/logger/LoggerTag.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/logger/LoggerTag.kt @@ -22,15 +22,15 @@ package org.matrix.android.sdk.api.logger * val loggerTag = LoggerTag("MyTag", LoggerTag.VOIP) * 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 VOIP : LoggerTag("VOIP") object CRYPTO : LoggerTag("CRYPTO") val value: String = if (parentTag == null) { - _value + name } else { - "${parentTag.value}/$_value" + "${parentTag.value}/$name" } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/query/QueryStringValue.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/query/QueryStringValue.kt index 31ec131c5c..368ff98661 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/query/QueryStringValue.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/query/QueryStringValue.kt @@ -36,19 +36,19 @@ sealed interface QueryStringValue { enum class Case { /** - * Match query sensitive to case + * Match query sensitive to case. */ 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, /** - * Match query with input normalized (case insensitive) - * Works around Realms inability to sort or filter by case for non Latin-1 character sets - * Expects the target field to contain normalized data + * Match query with input normalized (case insensitive). + * Works around Realms inability to sort or filter by case for non Latin-1 character sets. + * Expects the target field to contain normalized data. * * @see org.matrix.android.sdk.internal.util.Normalizer.normalize */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/raw/RawService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/raw/RawService.kt index 3366d040f7..71a4f84a8d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/raw/RawService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/raw/RawService.kt @@ -23,19 +23,19 @@ import org.matrix.android.sdk.api.cache.CacheStrategy */ 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 /** - * 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". * The URL will be "https://{domain}/.well-known/matrix/client" */ suspend fun getWellknown(domain: String): String /** - * Clear all the cache data + * Clear all the cache data. */ suspend fun clearCache() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt index 19502f0b46..2f1ae8cd87 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/Session.kt @@ -72,23 +72,23 @@ interface Session { val coroutineDispatchers: MatrixCoroutineDispatchers /** - * The params associated to the session + * The params associated to the session. */ 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 /** - * Useful shortcut to get access to the userId + * Useful shortcut to get access to the userId. */ val myUserId: String get() = sessionParams.userId /** - * The sessionId + * The sessionId. */ val sessionId: String @@ -99,16 +99,16 @@ interface Session { fun open() /** - * Requires a one time background sync + * Requires a one time background sync. */ 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 - * along with disabling battery optimizations + * along with disabling battery optimizations. */ fun startAutomaticBackgroundSync(timeOutInSeconds: Long, repeatDelayInSeconds: Long) @@ -125,7 +125,7 @@ interface Session { fun stopSync() /** - * Clear cache of the session + * Clear cache of the session. */ suspend fun clearCache() @@ -147,7 +147,7 @@ interface Session { fun syncFlow(): SharedFlow /** - * 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 @@ -162,187 +162,187 @@ interface Session { fun contentUrlResolver(): ContentUrlResolver /** - * Returns the ContentUploadProgressTracker associated with the session + * Returns the ContentUploadProgressTracker associated with the session. */ fun contentUploadProgressTracker(): ContentUploadStateTracker /** - * Returns the TypingUsersTracker associated with the session + * Returns the TypingUsersTracker associated with the session. */ fun typingUsersTracker(): TypingUsersTracker /** - * Returns the ContentDownloadStateTracker associated with the session + * Returns the ContentDownloadStateTracker associated with the session. */ fun contentDownloadProgressTracker(): ContentDownloadStateTracker /** - * Returns the cryptoService associated with the session + * Returns the cryptoService associated with the session. */ fun cryptoService(): CryptoService /** - * Returns the ContentScannerService associated with the session + * Returns the ContentScannerService associated with the session. */ fun contentScannerService(): ContentScannerService /** - * Returns the identity service associated with the session + * Returns the identity service associated with the session. */ fun identityService(): IdentityService /** - * Returns the HomeServerCapabilities service associated with the session + * Returns the HomeServerCapabilities service associated with the session. */ fun homeServerCapabilitiesService(): HomeServerCapabilitiesService /** - * Returns the RoomService associated with the session + * Returns the RoomService associated with the session. */ fun roomService(): RoomService /** - * Returns the RoomDirectoryService associated with the session + * Returns the RoomDirectoryService associated with the session. */ fun roomDirectoryService(): RoomDirectoryService /** - * Returns the GroupService associated with the session + * Returns the GroupService associated with the session. */ fun groupService(): GroupService /** - * Returns the UserService associated with the session + * Returns the UserService associated with the session. */ fun userService(): UserService /** - * Returns the SignOutService associated with the session + * Returns the SignOutService associated with the session. */ fun signOutService(): SignOutService /** - * Returns the FilterService associated with the session + * Returns the FilterService associated with the session. */ fun filterService(): FilterService /** - * Returns the PushRuleService associated with the session + * Returns the PushRuleService associated with the session. */ fun pushRuleService(): PushRuleService /** - * Returns the PushersService associated with the session + * Returns the PushersService associated with the session. */ fun pushersService(): PushersService /** - * Returns the EventService associated with the session + * Returns the EventService associated with the session. */ fun eventService(): EventService /** - * Returns the TermsService associated with the session + * Returns the TermsService associated with the session. */ fun termsService(): TermsService /** - * Returns the SyncStatusService associated with the session + * Returns the SyncStatusService associated with the session. */ fun syncStatusService(): SyncStatusService /** - * Returns the SecureStorageService associated with the session + * Returns the SecureStorageService associated with the session. */ fun secureStorageService(): SecureStorageService /** - * Returns the ProfileService associated with the session + * Returns the ProfileService associated with the session. */ fun profileService(): ProfileService /** - * Returns the PresenceService associated with the session + * Returns the PresenceService associated with the session. */ fun presenceService(): PresenceService /** - * Returns the AccountService associated with the session + * Returns the AccountService associated with the session. */ fun accountService(): AccountService /** - * Returns the ToDeviceService associated with the session + * Returns the ToDeviceService associated with the session. */ fun toDeviceService(): ToDeviceService /** - * Returns the EventStreamService associated with the session + * Returns the EventStreamService associated with the session. */ fun eventStreamService(): EventStreamService /** - * Returns the widget service associated with the session + * Returns the widget service associated with the session. */ fun widgetService(): WidgetService /** - * Returns the media service associated with the session + * Returns the media service associated with the session. */ fun mediaService(): MediaService /** - * Returns the integration manager service associated with the session + * Returns the integration manager service associated with the session. */ fun integrationManagerService(): IntegrationManagerService /** - * Returns the call signaling service associated with the session + * Returns the call signaling service associated with the session. */ fun callSignalingService(): CallSignalingService /** - * Returns the file download service associated with the session + * Returns the file download service associated with the session. */ fun fileService(): FileService /** - * Returns the permalink service associated with the session + * Returns the permalink service associated with the session. */ fun permalinkService(): PermalinkService /** - * Returns the search service associated with the session + * Returns the search service associated with the session. */ fun searchService(): SearchService /** - * Returns the federation service associated with the session + * Returns the federation service associated with the session. */ fun federationService(): FederationService /** - * Returns the third party service associated with the session + * Returns the third party service associated with the session. */ fun thirdPartyService(): ThirdPartyService /** - * Returns the space service associated with the session + * Returns the space service associated with the session. */ fun spaceService(): SpaceService /** - * Returns the open id service associated with the session + * Returns the open id service associated with the session. */ fun openIdService(): OpenIdService /** - * Returns the account data service associated with the session + * Returns the account data service associated with the session. */ fun accountDataService(): SessionAccountDataService /** - * Returns the SharedSecretStorageService associated with the session + * Returns the SharedSecretStorageService associated with the session. */ fun sharedSecretStorageService(): SharedSecretStorageService @@ -377,8 +377,8 @@ interface Session { /** * Possible cases: * - The access token is not valid anymore, - * - a M_CONSENT_NOT_GIVEN error has been received from the homeserver - * See [GlobalError] for all the possible cases + * - a M_CONSENT_NOT_GIVEN error has been received from the homeserver; + * See [GlobalError] for all the possible cases. */ fun onGlobalError(session: Session, globalError: GlobalError) = Unit } @@ -386,7 +386,7 @@ interface Session { 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() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/SessionExtensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/SessionExtensions.kt index aeb0e7e4ee..a15e73eb88 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/SessionExtensions.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/SessionExtensions.kt @@ -21,16 +21,16 @@ import org.matrix.android.sdk.api.session.room.model.RoomSummary 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) /** - * 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) /** - * 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) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/ToDeviceService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/ToDeviceService.kt index d7afad5b6c..56e5ebdbe7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/ToDeviceService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/ToDeviceService.kt @@ -21,9 +21,8 @@ import org.matrix.android.sdk.api.session.events.model.Content import java.util.UUID 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, txnId: String? = UUID.randomUUID().toString()) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/accountdata/SessionAccountDataService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/accountdata/SessionAccountDataService.kt index 2ffb9112d1..a22dd33774 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/accountdata/SessionAccountDataService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/accountdata/SessionAccountDataService.kt @@ -26,12 +26,12 @@ import org.matrix.android.sdk.api.util.Optional */ 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? /** - * Observe the account data with the provided type + * Observe the account data with the provided type. */ fun getLiveUserAccountDataEvent(type: String): LiveData> @@ -60,7 +60,7 @@ interface SessionAccountDataService { fun getLiveRoomAccountDataEvents(types: Set): LiveData> /** - * 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) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallListener.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallListener.kt index d17be59cd4..7f932e8815 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallListener.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallListener.kt @@ -39,32 +39,32 @@ interface CallListener { fun onCallAnswerReceived(callAnswerContent: CallAnswerContent) /** - * Called when a called has been hung up + * Called when a called has been hung up. */ fun onCallHangupReceived(callHangupContent: CallHangupContent) /** - * Called when a called has been rejected + * Called when a called has been rejected. */ fun onCallRejectReceived(callRejectContent: CallRejectContent) /** - * Called when an answer has been selected + * Called when an answer has been selected. */ fun onCallSelectAnswerReceived(callSelectAnswerContent: CallSelectAnswerContent) /** - * Called when a negotiation is sent + * Called when a negotiation is sent. */ 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) /** - * Called when an asserted identity event is received + * Called when an asserted identity event is received. */ fun onCallAssertedIdentityReceived(callAssertedIdentityContent: CallAssertedIdentityContent) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallSignalingService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallSignalingService.kt index c34744e75f..e17c02c40a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallSignalingService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallSignalingService.kt @@ -21,7 +21,7 @@ interface CallSignalingService { suspend fun getTurnServer(): TurnServerResponse /** - * Create an outgoing call + * Create an outgoing call. */ fun createOutgoingCall(roomId: String, otherUserId: String, isVideoCall: Boolean): MxCall diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallState.kt index ff1df63300..4bf78c9d6a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallState.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/CallState.kt @@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.room.model.call.EndCallReason sealed class CallState { - /** Idle, setting up objects */ + /** Idle, setting up objects. */ object Idle : CallState() /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt index dd23e81cc6..e13f7310e0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/call/MxCall.kt @@ -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 { @@ -46,13 +46,13 @@ interface MxCall : MxCallDetail { var state: CallState /** - * Pick Up the incoming call - * It has no effect on outgoing call + * Pick Up the incoming call. + * It has no effect on outgoing call. */ 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) @@ -62,17 +62,17 @@ interface MxCall : MxCallDetail { fun selectAnswer() /** - * Reject an incoming call + * Reject an incoming call. */ fun reject() /** - * End the call + * End the call. */ fun hangUp(reason: EndCallReason? = null) /** - * Start a call + * Start a call. * Send offer SDP to the other participant. */ fun offerSdp(sdpString: String) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/content/ContentUrlResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/content/ContentUrlResolver.kt index 523d60359b..e59e676ed9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/content/ContentUrlResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/content/ContentUrlResolver.kt @@ -29,7 +29,7 @@ interface ContentUrlResolver { } /** - * URL to use to upload content + * URL to use to upload content. */ val uploadUrl: String @@ -42,7 +42,7 @@ interface ContentUrlResolver { 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 elementToDecrypt Encryption data may be required if you use a content scanner diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt index d6d1248de7..35f3ab3162 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/CryptoService.kt @@ -26,6 +26,7 @@ import org.matrix.android.sdk.api.session.crypto.crosssigning.CrossSigningServic import org.matrix.android.sdk.api.session.crypto.crosssigning.DeviceTrustLevel import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupService import org.matrix.android.sdk.api.session.crypto.keyshare.GossipingRequestListener +import org.matrix.android.sdk.api.session.crypto.model.AuditTrail import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo import org.matrix.android.sdk.api.session.crypto.model.DevicesListResponse @@ -35,8 +36,6 @@ import org.matrix.android.sdk.api.session.crypto.model.MXDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.MXEncryptEventContentResult import org.matrix.android.sdk.api.session.crypto.model.MXEventDecryptionResult import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap -import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest -import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody import org.matrix.android.sdk.api.session.crypto.verification.VerificationService import org.matrix.android.sdk.api.session.events.model.Content import org.matrix.android.sdk.api.session.events.model.Event @@ -76,6 +75,15 @@ interface CryptoService { fun setGlobalBlacklistUnverifiedDevices(block: Boolean) + /** + * Enable or disable key gossiping. + * Default is true. + * If set to false this device won't send key_request nor will accept key forwarded + */ + fun enableKeyGossiping(enable: Boolean) + + fun isKeyGossipingEnabled(): Boolean + fun setRoomUnBlacklistUnverifiedDevices(roomId: String) fun getDeviceTrackingStatus(userId: String): Int @@ -94,8 +102,6 @@ interface CryptoService { fun reRequestRoomKeyForEvent(event: Event) - fun cancelRoomKeyRequest(requestBody: RoomKeyRequestBody) - fun addRoomKeysRequestListener(listener: GossipingRequestListener) fun removeRoomKeysRequestListener(listener: GossipingRequestListener) @@ -142,14 +148,20 @@ interface CryptoService { fun addNewSessionListener(newSessionListener: NewSessionListener) fun removeSessionListener(listener: NewSessionListener) - fun getOutgoingRoomKeyRequests(): List - fun getOutgoingRoomKeyRequestsPaged(): LiveData> + fun getOutgoingRoomKeyRequests(): List + fun getOutgoingRoomKeyRequestsPaged(): LiveData> fun getIncomingRoomKeyRequests(): List fun getIncomingRoomKeyRequestsPaged(): LiveData> - fun getGossipingEventsTrail(): LiveData> - fun getGossipingEvents(): List + /** + * Can be called by the app layer to accept a request manually. + * Use carefully as it is prone to social attacks. + */ + suspend fun manuallyAcceptRoomKeyRequest(request: IncomingRoomKeyRequest) + + fun getGossipingEventsTrail(): LiveData> + fun getGossipingEvents(): List // For testing shared session fun getSharedWithInfo(roomId: String?, sessionId: String): MXUsersDevicesMap diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt index 5ff4b54b11..0b5bbe3bbd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/MXCryptoError.kt @@ -28,7 +28,7 @@ sealed class MXCryptoError : Throwable() { data class Base(val errorType: ErrorType, val technicalMessage: String, /** - * Describe the error with more details + * Describe the error with more details. */ val detailedErrorDescription: String? = null) : MXCryptoError() @@ -63,7 +63,7 @@ sealed class MXCryptoError : Throwable() { companion object { /** - * Resource for technicalMessage + * Resource for technicalMessage. */ const val UNABLE_TO_ENCRYPT_REASON = "Unable to encrypt %s" const val UNABLE_TO_DECRYPT_REASON = "Unable to decrypt %1\$s. Algorithm: %2\$s" diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/NewSessionListener.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/NewSessionListener.kt index 73cbf5fb78..d9e841a50f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/NewSessionListener.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/NewSessionListener.kt @@ -17,7 +17,7 @@ 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 { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingKeyRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingKeyRequest.kt new file mode 100644 index 0000000000..855f17a34f --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingKeyRequest.kt @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.api.session.crypto + +import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody +import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode + +data class RequestReply( + val userId: String, + val fromDevice: String?, + val result: RequestResult +) + +sealed class RequestResult { + data class Success(val chainIndex: Int) : RequestResult() + data class Failure(val code: WithHeldCode) : RequestResult() +} + +data class OutgoingKeyRequest( + var requestBody: RoomKeyRequestBody?, + // recipients for the request map of users to list of deviceId + val recipients: Map>, + val fromIndex: Int, + // Unique id for this request. Used for both + // an id within the request for later pairing with a cancellation, and for + // the transaction id when sending the to_device messages to our local + val requestId: String, // current state of this request + val state: OutgoingRoomKeyRequestState, + val results: List +) { + /** + * Used only for log. + * + * @return the room id. + */ + val roomId = requestBody?.roomId + + /** + * Used only for log. + * + * @return the session id + */ + val sessionId = requestBody?.sessionId +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OutgoingGossipingRequestState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingRoomKeyRequestState.kt similarity index 57% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OutgoingGossipingRequestState.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingRoomKeyRequestState.kt index 8c1bdf6768..6e80bdc133 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OutgoingGossipingRequestState.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/OutgoingRoomKeyRequestState.kt @@ -1,5 +1,5 @@ /* - * Copyright 2020 The Matrix.org Foundation C.I.C. + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,14 +14,20 @@ * limitations under the License. */ -package org.matrix.android.sdk.api.session.crypto.model +package org.matrix.android.sdk.api.session.crypto -enum class OutgoingGossipingRequestState { +enum class OutgoingRoomKeyRequestState { UNSENT, - SENDING, SENT, - CANCELLING, - CANCELLED, - FAILED_TO_SEND, - FAILED_TO_CANCEL + SENT_THEN_CANCELED, + CANCELLATION_PENDING, + CANCELLATION_PENDING_AND_WILL_RESEND; + + companion object { + fun pendingStates() = setOf( + UNSENT, + CANCELLATION_PENDING_AND_WILL_RESEND, + CANCELLATION_PENDING + ) + } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/attachments/ElementToDecrypt.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/attachments/ElementToDecrypt.kt index de168ac6e5..2591703e0c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/attachments/ElementToDecrypt.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/attachments/ElementToDecrypt.kt @@ -35,7 +35,7 @@ fun EncryptedFileInfo.toElementToDecrypt(): ElementToDecrypt? { } /** - * Represent data to decode an attachment + * Represent data to decode an attachment. */ @Parcelize data class ElementToDecrypt( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt index 46b131f613..5439389096 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/crosssigning/CrossSigningService.kt @@ -66,7 +66,7 @@ interface CrossSigningService { fun markMyMasterKeyAsTrusted() /** - * Sign one of your devices and upload the signature + * Sign one of your devices and upload the signature. */ fun trustDevice(deviceId: String, callback: MatrixCallback) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt index 9ff99f8dce..0d40490c3e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupService.kt @@ -23,7 +23,7 @@ import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult 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. * @param callback Asynchronous callback @@ -40,12 +40,12 @@ interface KeysBackupService { callback: MatrixCallback) /** - * 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 /** - * Facility method to get the number of backed up keys + * Facility method to get the number of backed up keys. */ fun getTotalNumbersOfBackedUpKeys(): Int @@ -68,7 +68,7 @@ interface KeysBackupService { callback: MatrixCallback) /** - * Return the current progress of the backup + * Return the current progress of the backup. */ fun getBackupProgress(progressListener: ProgressListener) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupStateListener.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupStateListener.kt index a6f4bd0ec7..32216fe3f5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupStateListener.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupStateListener.kt @@ -19,7 +19,7 @@ package org.matrix.android.sdk.api.session.crypto.keysbackup interface KeysBackupStateListener { /** - * The keys backup state has changed + * The keys backup state has changed. * @param newState the new state */ fun onStateChange(newState: KeysBackupState) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt index 219a328cfd..7127c8d3f4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysBackupVersionTrustSignature.kt @@ -16,25 +16,35 @@ 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 /** * A signature in a `KeysBackupVersionTrust` object. */ -data class KeysBackupVersionTrustSignature( - /** - * The id of the device that signed the backup version. - */ - val deviceId: String?, - /** - * The device that signed the backup version. - * Can be null if the device is not known. - */ - val device: CryptoDeviceInfo?, +sealed class KeysBackupVersionTrustSignature { - /** - * Flag to indicate the signature from this device is valid. - */ - val valid: Boolean, -) + data class DeviceSignature( + /** + * The id of the device that signed the backup version. + */ + 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() +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysVersionResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysVersionResult.kt index f283a34e98..3d89bf9e2f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysVersionResult.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/KeysVersionResult.kt @@ -30,8 +30,8 @@ data class KeysVersionResult( override val algorithm: String, /** - * algorithm-dependent data, for "m.megolm_backup.v1.curve25519-aes-sha2" - * see [org.matrix.android.sdk.internal.crypto.keysbackup.MegolmBackupAuthData] + * algorithm-dependent data, for "m.megolm_backup.v1.curve25519-aes-sha2". + * @see [org.matrix.android.sdk.internal.crypto.keysbackup.MegolmBackupAuthData] */ @Json(name = "auth_data") override val authData: JsonDict, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/RecoveryKey.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/RecoveryKey.kt index 85d6ef4365..9ad0bfc8b6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/RecoveryKey.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keysbackup/RecoveryKey.kt @@ -30,7 +30,7 @@ private const val CHAR_1 = 0x01.toByte() 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 * @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 * @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 * @return curveKey, or null in case of error diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keyshare/GossipingRequestListener.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keyshare/GossipingRequestListener.kt index 3cd36c2ce8..cc160f8d85 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keyshare/GossipingRequestListener.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/keyshare/GossipingRequestListener.kt @@ -16,12 +16,11 @@ package org.matrix.android.sdk.api.session.crypto.keyshare -import org.matrix.android.sdk.api.session.crypto.model.IncomingRequestCancellation import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest -import org.matrix.android.sdk.api.session.crypto.model.IncomingSecretShareRequest +import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest /** - * Room keys events listener + * Room keys events listener. */ interface GossipingRequestListener { /** @@ -32,15 +31,15 @@ interface GossipingRequestListener { fun onRoomKeyRequest(request: IncomingRoomKeyRequest) /** - * Returns the secret value to be shared + * Returns the secret value to be shared. * @return true if is handled */ - fun onSecretShareRequest(request: IncomingSecretShareRequest): Boolean + fun onSecretShareRequest(request: SecretShareRequest): Boolean /** * A room key request cancellation has been received. * * @param request the cancellation request */ - fun onRoomKeyRequestCancellation(request: IncomingRequestCancellation) + fun onRequestCancelled(request: IncomingRoomKeyRequest) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/AuditTrail.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/AuditTrail.kt new file mode 100644 index 0000000000..861f3bd30b --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/AuditTrail.kt @@ -0,0 +1,85 @@ +/* + * Copyright 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.api.session.crypto.model + +import com.squareup.moshi.JsonClass +import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode + +enum class TrailType { + OutgoingKeyForward, + IncomingKeyForward, + OutgoingKeyWithheld, + IncomingKeyRequest, + Unknown +} + +interface AuditInfo { + val roomId: String + val sessionId: String + val senderKey: String + val alg: String + val userId: String + val deviceId: String +} + +@JsonClass(generateAdapter = true) +data class ForwardInfo( + override val roomId: String, + override val sessionId: String, + override val senderKey: String, + override val alg: String, + override val userId: String, + override val deviceId: String, + val chainIndex: Long? +) : AuditInfo + +object UnknownInfo : AuditInfo { + override val roomId: String = "" + override val sessionId: String = "" + override val senderKey: String = "" + override val alg: String = "" + override val userId: String = "" + override val deviceId: String = "" +} + +@JsonClass(generateAdapter = true) +data class WithheldInfo( + override val roomId: String, + override val sessionId: String, + override val senderKey: String, + override val alg: String, + val code: WithHeldCode, + override val userId: String, + override val deviceId: String +) : AuditInfo + +@JsonClass(generateAdapter = true) +data class IncomingKeyRequestInfo( + override val roomId: String, + override val sessionId: String, + override val senderKey: String, + override val alg: String, + override val userId: String, + override val deviceId: String, + val requestId: String +) : AuditInfo + +data class AuditTrail( + val ageLocalTs: Long, + val type: TrailType, + val info: AuditInfo +) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/DeviceInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/DeviceInfo.kt index 221d0793d9..b144069b99 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/DeviceInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/DeviceInfo.kt @@ -20,24 +20,24 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.api.interfaces.DatedObject /** - * This class describes the device information + * This class describes the device information. */ @JsonClass(generateAdapter = true) 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") val userId: String? = null, /** - * The device id + * The device id. */ @Json(name = "device_id") val deviceId: String? = null, /** - * The device display name + * The device display name. */ @Json(name = "display_name") val displayName: String? = null, @@ -49,7 +49,7 @@ data class DeviceInfo( val lastSeenTs: Long? = null, /** - * The last ip address + * The last ip address. */ @Json(name = "last_seen_ip") val lastSeenIp: String? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileInfo.kt index 13ad1df476..fb64c6f338 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileInfo.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * In Matrix specs: EncryptedFile + * In Matrix specs: EncryptedFile. */ @JsonClass(generateAdapter = true) data class EncryptedFileInfo( @@ -56,7 +56,7 @@ data class EncryptedFileInfo( val v: String? = null ) { /** - * Check what the spec tells us + * Check what the spec tells us. */ fun isValid(): Boolean { if (url.isNullOrBlank()) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileKey.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileKey.kt index 859c6ac43f..6308e3d615 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileKey.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/EncryptedFileKey.kt @@ -52,7 +52,7 @@ data class EncryptedFileKey( val k: String? = null ) { /** - * Check what the spec tells us + * Check what the spec tells us. */ fun isValid(): Boolean { if (alg != "A256CTR") { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/GossipingToDeviceObject.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/GossipingToDeviceObject.kt index 1922b2bcee..ac575332da 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/GossipingToDeviceObject.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/GossipingToDeviceObject.kt @@ -17,7 +17,7 @@ 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] */ interface GossipingToDeviceObject : SendToDeviceObject { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingRequestCancellation.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingRequestCancellation.kt deleted file mode 100755 index ad11ef9a5e..0000000000 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingRequestCancellation.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.api.session.crypto.model - -import org.matrix.android.sdk.api.session.events.model.Event -import org.matrix.android.sdk.api.session.events.model.toModel -import org.matrix.android.sdk.internal.crypto.IncomingShareRequestCommon -import org.matrix.android.sdk.internal.crypto.model.rest.ShareRequestCancellation - -/** - * IncomingRequestCancellation describes the incoming room key cancellation. - */ -data class IncomingRequestCancellation( - /** - * The user id - */ - override val userId: String? = null, - - /** - * The device id - */ - override val deviceId: String? = null, - - /** - * The request id - */ - override val requestId: String? = null, - override val localCreationTimestamp: Long? -) : IncomingShareRequestCommon { - companion object { - /** - * Factory - * - * @param event the event - * @param currentTimeMillis the current time in milliseconds - */ - fun fromEvent(event: Event, currentTimeMillis: Long): IncomingRequestCancellation? { - return event.getClearContent() - .toModel() - ?.let { - IncomingRequestCancellation( - userId = event.senderId, - deviceId = it.requestingDeviceId, - requestId = it.requestId, - localCreationTimestamp = event.ageLocalTs ?: currentTimeMillis - ) - } - } - } -} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingRoomKeyRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingRoomKeyRequest.kt index 0b2c32284b..0c19d275cc 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingRoomKeyRequest.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingRoomKeyRequest.kt @@ -16,68 +16,71 @@ package org.matrix.android.sdk.api.session.crypto.model -import org.matrix.android.sdk.api.session.events.model.Event -import org.matrix.android.sdk.api.session.events.model.toModel -import org.matrix.android.sdk.internal.crypto.IncomingShareRequestCommon +import org.matrix.android.sdk.internal.util.time.Clock /** * IncomingRoomKeyRequest class defines the incoming room keys request. */ data class IncomingRoomKeyRequest( /** - * The user id + * The user id. */ - override val userId: String? = null, + val userId: String? = null, /** - * The device id + * The device id. */ - override val deviceId: String? = null, + val deviceId: String? = null, /** - * The request id + * The request id. */ - override val requestId: String? = null, + val requestId: String? = null, /** - * The request body + * The request body. */ val requestBody: RoomKeyRequestBody? = null, - val state: GossipingRequestState = GossipingRequestState.NONE, - - /** - * The runnable to call to accept to share the keys - */ - @Transient - var share: Runnable? = null, - - /** - * The runnable to call to ignore the key share request. - */ - @Transient - var ignore: Runnable? = null, - override val localCreationTimestamp: Long? -) : IncomingShareRequestCommon { + val localCreationTimestamp: Long? +) { companion object { /** - * Factory + * Factory. * * @param event the event * @param currentTimeMillis the current time in milliseconds */ - fun fromEvent(event: Event, currentTimeMillis: Long): IncomingRoomKeyRequest? { - return event.getClearContent() - .toModel() + fun fromEvent(trail: AuditTrail): IncomingRoomKeyRequest? { + return trail + .takeIf { it.type == TrailType.IncomingKeyRequest } + ?.let { + it.info as? IncomingKeyRequestInfo + } ?.let { IncomingRoomKeyRequest( - userId = event.senderId, - deviceId = it.requestingDeviceId, + userId = it.userId, + deviceId = it.deviceId, requestId = it.requestId, - requestBody = it.body ?: RoomKeyRequestBody(), - localCreationTimestamp = event.ageLocalTs ?: currentTimeMillis + requestBody = RoomKeyRequestBody( + algorithm = it.alg, + roomId = it.roomId, + senderKey = it.senderKey, + sessionId = it.sessionId + ), + localCreationTimestamp = trail.ageLocalTs ) } } + + internal fun fromRestRequest(senderId: String, request: RoomKeyShareRequest, clock: Clock): IncomingRoomKeyRequest? { + return IncomingRoomKeyRequest( + userId = senderId, + deviceId = request.requestingDeviceId, + requestId = request.requestId, + requestBody = request.body, + localCreationTimestamp = clock.epochMillis() + ) + } } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingSecretShareRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingSecretShareRequest.kt deleted file mode 100755 index 80f70c83f3..0000000000 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/IncomingSecretShareRequest.kt +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.api.session.crypto.model - -import org.matrix.android.sdk.api.session.events.model.Event -import org.matrix.android.sdk.api.session.events.model.toModel -import org.matrix.android.sdk.internal.crypto.IncomingShareRequestCommon - -/** - * IncomingSecretShareRequest class defines the incoming secret keys request. - */ -data class IncomingSecretShareRequest( - /** - * The user id - */ - override val userId: String? = null, - - /** - * The device id - */ - override val deviceId: String? = null, - - /** - * The request id - */ - override val requestId: String? = null, - - /** - * The request body - */ - val secretName: String? = null, - - /** - * The runnable to call to accept to share the keys - */ - @Transient - var share: ((String) -> Unit)? = null, - - /** - * The runnable to call to ignore the key share request. - */ - @Transient - var ignore: Runnable? = null, - - override val localCreationTimestamp: Long? - -) : IncomingShareRequestCommon { - companion object { - /** - * Factory - * - * @param event the event - * @param currentTimeMillis the current time in milliseconds - */ - fun fromEvent(event: Event, currentTimeMillis: Long): IncomingSecretShareRequest? { - return event.getClearContent() - .toModel() - ?.let { - IncomingSecretShareRequest( - userId = event.senderId, - deviceId = it.requestingDeviceId, - requestId = it.requestId, - secretName = it.secretName, - localCreationTimestamp = event.ageLocalTs ?: currentTimeMillis - ) - } - } - } -} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXDeviceInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXDeviceInfo.kt index 286ab2b7d5..a5a581d240 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXDeviceInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXDeviceInfo.kt @@ -30,7 +30,7 @@ data class MXDeviceInfo( val deviceId: String, /** - * the user id + * the user id. */ @Json(name = "user_id") val userId: String, @@ -66,7 +66,7 @@ data class MXDeviceInfo( val verified: Int = DEVICE_VERIFICATION_UNKNOWN ) : Serializable { /** - * Tells if the device is unknown + * Tells if the device is unknown. * * @return true if the device is unknown */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXEncryptEventContentResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXEncryptEventContentResult.kt index 706e40a769..4cfcc01a26 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXEncryptEventContentResult.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXEncryptEventContentResult.kt @@ -20,11 +20,11 @@ import org.matrix.android.sdk.api.session.events.model.Content data class MXEncryptEventContentResult( /** - * The encrypted event content + * The encrypted event content. */ val eventContent: Content, /** - * the event type + * The event type. */ val eventType: String ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXUsersDevicesMap.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXUsersDevicesMap.kt index dc5567e908..744fe74d0d 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXUsersDevicesMap.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/MXUsersDevicesMap.kt @@ -31,7 +31,7 @@ class MXUsersDevicesMap { 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 * * @param userId the user id @@ -44,7 +44,7 @@ class MXUsersDevicesMap { } /** - * 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 userId the object id @@ -57,7 +57,7 @@ class MXUsersDevicesMap { } /** - * 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 deviceId the device id @@ -71,7 +71,7 @@ class MXUsersDevicesMap { } /** - * Defines the objects map for a user Id + * Defines the objects map for a user Id. * * @param objectsPerDevices the objects maps * @param userId the user id @@ -87,7 +87,7 @@ class MXUsersDevicesMap { } /** - * Removes objects for a dedicated user + * Removes objects for a dedicated user. * * @param userId the user id. */ @@ -98,14 +98,14 @@ class MXUsersDevicesMap { } /** - * Clear the internal dictionary + * Clear the internal dictionary. */ fun removeAllObjects() { map.clear() } /** - * Add entries from another MXUsersDevicesMap + * Add entries from another MXUsersDevicesMap. * * @param other the other one */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OlmDecryptionResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OlmDecryptionResult.kt index 9cf2bf75fb..a26f6606ed 100755 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OlmDecryptionResult.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OlmDecryptionResult.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.util.JsonDict @JsonClass(generateAdapter = true) data class OlmDecryptionResult( /** - * The decrypted payload (with properties 'type', 'content') + * The decrypted payload (with properties 'type', 'content'). */ @Json(name = "payload") val payload: JsonDict? = null, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OutgoingRoomKeyRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OutgoingRoomKeyRequest.kt deleted file mode 100755 index 5f35cc908f..0000000000 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/OutgoingRoomKeyRequest.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.api.session.crypto.model - -import com.squareup.moshi.JsonClass -import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequest - -/** - * Represents an outgoing room key request - */ -@JsonClass(generateAdapter = true) -data class OutgoingRoomKeyRequest( - // RequestBody - val requestBody: RoomKeyRequestBody?, - // list of recipients for the request - override val recipients: Map>, - // Unique id for this request. Used for both - // an id within the request for later pairing with a cancellation, and for - // the transaction id when sending the to_device messages to our local - override val requestId: String, // current state of this request - override val state: OutgoingGossipingRequestState - // transaction id for the cancellation, if any - // override var cancellationTxnId: String? = null -) : OutgoingGossipingRequest { - - /** - * Used only for log. - * - * @return the room id. - */ - val roomId: String? - get() = requestBody?.roomId - - /** - * Used only for log. - * - * @return the session id - */ - val sessionId: String? - get() = requestBody?.sessionId -} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyRequestBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyRequestBody.kt index 15163248dc..8352949263 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyRequestBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyRequestBody.kt @@ -21,7 +21,7 @@ import com.squareup.moshi.JsonClass 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) data class RoomKeyRequestBody( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyShareRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyShareRequest.kt index b6bb4c55af..adbe831a07 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyShareRequest.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/RoomKeyShareRequest.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing a room key request content + * Class representing a room key request content. */ @JsonClass(generateAdapter = true) data class RoomKeyShareRequest( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/SecretShareRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/SecretShareRequest.kt index 6009077806..263a7b16e4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/SecretShareRequest.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/SecretShareRequest.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing a room key request content + * Class representing a room key request content. */ @JsonClass(generateAdapter = true) data class SecretShareRequest( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/CancelCode.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/CancelCode.kt index 5a025f37e1..e4716d7794 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/CancelCode.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/CancelCode.kt @@ -28,7 +28,8 @@ enum class CancelCode(val value: String, val humanReadable: String) { MismatchedKeys("m.key_mismatch", "Key mismatch"), UserError("m.user_error", "User error"), MismatchedUser("m.user_mismatch", "User mismatch"), - QrCodeInvalid("m.qr_code.invalid", "Invalid QR code") + QrCodeInvalid("m.qr_code.invalid", "Invalid QR code"), + AcceptedByAnotherDevice("m.accepted", "Verification request accepted by another device") } fun safeValueOf(code: String?): CancelCode { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/PendingVerificationRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/PendingVerificationRequest.kt index be450b9d03..7db450e861 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/PendingVerificationRequest.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/PendingVerificationRequest.kt @@ -22,7 +22,7 @@ import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_SAS import java.util.UUID /** - * Stores current pending verification requests + * Stores current pending verification requests. */ data class PendingVerificationRequest( val ageLocalTs: Long, @@ -45,7 +45,7 @@ data class PendingVerificationRequest( 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 { 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 { 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 { return if (isIncoming) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/QrCodeVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/QrCodeVerificationTransaction.kt index 37855099be..06bac4109b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/QrCodeVerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/QrCodeVerificationTransaction.kt @@ -19,22 +19,22 @@ package org.matrix.android.sdk.api.session.crypto.verification 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? /** - * Call when you have scan the other user QR code + * Call when you have scan the other user QR code. */ 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() /** - * 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() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/SasVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/SasVerificationTransaction.kt index da546be68f..095b4208f8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/SasVerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/SasVerificationTransaction.kt @@ -28,7 +28,7 @@ interface SasVerificationTransaction : VerificationTransaction { /** * To be called by the client when the user has verified that - * both short codes do match + * both short codes do match. */ fun userHasVerifiedShortCode() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationMethod.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationMethod.kt index 4efec93a34..f2de2c4b47 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationMethod.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationMethod.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.api.session.crypto.verification /** - * Verification methods + * Verification methods. */ enum class VerificationMethod { // Use it when your application supports the SAS verification method diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt index ec67e4b31d..321ec73094 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationService.kt @@ -34,7 +34,7 @@ interface VerificationService { fun removeListener(listener: Listener) /** - * Mark this device as verified manually + * Mark this device as verified manually. */ fun markedLocallyAsManuallyVerified(userId: String, deviceID: String) @@ -52,7 +52,7 @@ interface VerificationService { transactionId: String?): String? /** - * Request key verification with another user via room events (instead of the to-device API) + * Request key verification with another user via room events (instead of the to-device API). */ fun requestKeyVerificationInDMs(methods: List, otherUserId: String, @@ -81,7 +81,7 @@ interface VerificationService { otherDeviceId: String): String /** - * Returns false if the request is unknown + * Returns false if the request is unknown. */ fun readyPendingVerificationInDMs(methods: List, otherUserId: String, @@ -89,7 +89,7 @@ interface VerificationService { transactionId: String): Boolean /** - * Returns false if the request is unknown + * Returns false if the request is unknown. */ fun readyPendingVerification(methods: List, otherUserId: String, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationTransaction.kt index 4d35bc44ac..b68a82c604 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationTransaction.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/verification/VerificationTransaction.kt @@ -28,7 +28,7 @@ interface VerificationTransaction { val isIncoming: Boolean /** - * User wants to cancel the transaction + * User wants to cancel the transaction. */ fun cancel() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt index 1ce51a2bde..7124d8a1a3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/Event.kt @@ -26,6 +26,7 @@ import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomMemberContent +import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconLocationDataContent import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.model.message.MessagePollContent import org.matrix.android.sdk.api.session.room.model.message.MessageStickerContent @@ -62,7 +63,7 @@ inline fun Content?.toModel(catchError: Boolean = true): T? { } /** - * This methods is a facility method to map a model to a json Content + * This methods is a facility method to map a model to a json Content. */ @Suppress("UNCHECKED_CAST") inline fun T.toContent(): Content { @@ -123,7 +124,7 @@ data class Event( var ageLocalTs: Long? = null /** - * Copy all fields, including transient fields + * Copy all fields, including transient fields. */ fun copyAll(): Event { return copy().also { @@ -227,14 +228,14 @@ data class Event( } /** - * Determines whether or not current event has mentioned the user + * Determines whether or not current event has mentioned the user. */ fun isUserMentioned(userId: String): Boolean { return getDecryptedValue("formatted_body")?.contains(userId) ?: false } /** - * Decrypt the message, or return the pure payload value if there is no encryption + * Decrypt the message, or return the pure payload value if there is no encryption. */ private fun getDecryptedValue(key: String = "body"): String? { return if (isEncrypted()) { @@ -247,7 +248,7 @@ data class Event( } /** - * Tells if the event is redacted + * Tells if the event is redacted. */ fun isRedacted() = unsignedData?.redactedEvent != null @@ -305,7 +306,7 @@ data class Event( /** * Return the value of "content.msgtype", if the Event type is "m.room.message" - * and if the content has it, and if it is a String + * and if the content has it, and if it is a String. */ fun Event.getMsgType(): String? { if (getClearType() != EventType.MESSAGE) return null @@ -375,24 +376,24 @@ fun Event.getRelationContent(): RelationDefaultContent? { content.toModel()?.relatesTo } else { content.toModel()?.relatesTo ?: run { - // Special case to handle stickers, while there is only a local msgtype for stickers - if (getClearType() == EventType.STICKER) { - getClearContent().toModel()?.relatesTo - } else { - null + // Special cases when there is only a local msgtype for some event types + when (getClearType()) { + EventType.STICKER -> getClearContent().toModel()?.relatesTo + in EventType.BEACON_LOCATION_DATA -> getClearContent().toModel()?.relatesTo + else -> null } } } } /** - * Returns the poll question or null otherwise + * Returns the poll question or null otherwise. */ fun Event.getPollQuestion(): String? = getPollContent()?.getBestPollCreationInfo()?.question?.getBestQuestion() /** - * Returns the relation content for a specific type or null otherwise + * Returns the relation content for a specific type or null otherwise. */ fun Event.getRelationContentForType(type: String): RelationDefaultContent? = getRelationContent()?.takeIf { it.type == type } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/RelationType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/RelationType.kt index 74dc74b294..3db9262c5b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/RelationType.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/RelationType.kt @@ -16,7 +16,7 @@ package org.matrix.android.sdk.api.session.events.model /** - * Constants defining known event relation types from Matrix specifications + * Constants defining known event relation types from Matrix specifications. */ object RelationType { /** Lets you define an event which annotates an existing event.*/ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptedEventContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptedEventContent.kt index 4f39bb61e1..b8388ea002 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptedEventContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptedEventContent.kt @@ -20,37 +20,37 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultContent /** - * Class representing an encrypted event content + * Class representing an encrypted event content. */ @JsonClass(generateAdapter = true) data class EncryptedEventContent( /** - * the used algorithm + * The used algorithm. */ @Json(name = "algorithm") val algorithm: String? = null, /** - * The encrypted event + * The encrypted event. */ @Json(name = "ciphertext") val ciphertext: String? = null, /** - * The device id + * The device id. */ @Json(name = "device_id") val deviceId: String? = null, /** - * the sender key + * The sender key. */ @Json(name = "sender_key") val senderKey: String? = null, /** - * The session id + * The session id. */ @Json(name = "session_id") val sessionId: String? = null, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptionEventContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptionEventContent.kt index 103293ba83..321afd186d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptionEventContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/EncryptionEventContent.kt @@ -19,7 +19,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing an encrypted event content + * Class representing an encrypted event content. */ @JsonClass(generateAdapter = true) data class EncryptionEventContent( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmEventContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmEventContent.kt index b972dd20bb..65e8128182 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmEventContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmEventContent.kt @@ -19,7 +19,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing an encrypted event content + * Class representing an encrypted event content. */ @JsonClass(generateAdapter = true) data class OlmEventContent( @@ -30,7 +30,7 @@ data class OlmEventContent( val ciphertext: Map? = null, /** - * the sender key + * the sender key. */ @Json(name = "sender_key") val senderKey: String? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmPayloadContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmPayloadContent.kt index 6060ab5c4b..c3d8a5a800 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmPayloadContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/OlmPayloadContent.kt @@ -20,36 +20,36 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.internal.di.MoshiProvider /** - * Class representing the OLM payload content + * Class representing the OLM payload content. */ @JsonClass(generateAdapter = true) data class OlmPayloadContent( /** - * The room id + * The room id. */ @Json(name = "room_id") val roomId: String? = null, /** - * The sender + * The sender. */ @Json(name = "sender") val sender: String? = null, /** - * The recipient + * The recipient. */ @Json(name = "recipient") val recipient: String? = null, /** - * the recipient keys + * The recipient keys. */ @Json(name = "recipient_keys") val recipientKeys: Map? = null, /** - * The keys + * The keys. */ @Json(name = "keys") val keys: Map? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyContent.kt index 43a47b818f..0830a566ab 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyContent.kt @@ -19,7 +19,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing an sharekey content + * Class representing an sharekey content. */ @JsonClass(generateAdapter = true) data class RoomKeyContent( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt index a577daf9e4..d58c3614a7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/RoomKeyWithHeldContent.kt @@ -19,7 +19,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing an sharekey content + * Class representing an sharekey content. */ @JsonClass(generateAdapter = true) data class RoomKeyWithHeldContent( @@ -52,7 +52,13 @@ data class RoomKeyWithHeldContent( /** * A human-readable reason for why the key was not sent. The receiving client should only use this string if it does not understand the code. */ - @Json(name = "reason") val reason: String? = null + @Json(name = "reason") val reason: String? = null, + + /** + * the device ID of the device sending the m.room_key.withheld message + * MSC3735. + */ + @Json(name = "from_device") val fromDevice: String? = null ) { val code: WithHeldCode? @@ -63,23 +69,23 @@ data class RoomKeyWithHeldContent( enum class WithHeldCode(val value: String) { /** - * the user/device was blacklisted + * the user/device was blacklisted. */ BLACKLISTED("m.blacklisted"), /** - * the user/devices is unverified + * the user/devices is unverified. */ UNVERIFIED("m.unverified"), /** * the user/device is not allowed have the key. For example, this would usually be sent in response - * to a key request if the user was not in the room when the message was sent + * to a key request if the user was not in the room when the message was sent. */ UNAUTHORISED("m.unauthorised"), /** - * Sent in reply to a key request if the device that the key is requested from does not have the requested key + * Sent in reply to a key request if the device that the key is requested from does not have the requested key. */ UNAVAILABLE("m.unavailable"), diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/SecretSendEventContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/SecretSendEventContent.kt index 5099aba403..be9d9d638c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/SecretSendEventContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/events/model/content/SecretSendEventContent.kt @@ -19,7 +19,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing an encrypted event content + * Class representing an encrypted event content. */ @JsonClass(generateAdapter = true) data class SecretSendEventContent( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt index 8e930f2a50..84a9990826 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/FileService.kt @@ -73,7 +73,7 @@ interface FileService { /** * Use this URI and pass it to intent using flag Intent.FLAG_GRANT_READ_URI_PERMISSION - * (if not other app won't be able to access it) + * (if not other app won't be able to access it). */ fun getTemporarySharableURI(mxcUrl: String?, fileName: String, @@ -106,17 +106,17 @@ interface FileService { ) /** - * Clears all the files downloaded by the service, including decrypted files + * Clears all the files downloaded by the service, including decrypted files. */ fun clearCache() /** - * Clears all the decrypted files by the service + * Clears all the decrypted files by the service. */ fun clearDecryptedCache() /** - * Get size of cached files + * Get size of cached files. */ fun getCacheSize(): Long } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/MatrixSDKFileProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/MatrixSDKFileProvider.kt index ee1550d1db..113bf9333f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/MatrixSDKFileProvider.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/file/MatrixSDKFileProvider.kt @@ -21,7 +21,7 @@ import androidx.core.content.FileProvider /** * We have to declare our own file provider to avoid collision with apps using the sdk - * and having their own + * and having their own. */ class MatrixSDKFileProvider : FileProvider() { override fun getType(uri: Uri): String? { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupService.kt index a96466603c..1968af222a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupService.kt @@ -23,16 +23,15 @@ import org.matrix.android.sdk.api.session.group.model.GroupSummary * This interface defines methods to get groups. It's implemented at the session level. */ interface GroupService { - /** - * Get a group from a groupId + * Get a group from a groupId. * @param groupId the groupId to look for. * @return the group with groupId or null */ fun getGroup(groupId: String): Group? /** - * Get a groupSummary from a groupId + * Get a groupSummary from a groupId. * @param groupId the groupId to look for. * @return the groupSummary with groupId or null */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupSummaryQueryParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupSummaryQueryParams.kt index 0761a22c77..5104b3ee53 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupSummaryQueryParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/group/GroupSummaryQueryParams.kt @@ -24,7 +24,7 @@ fun groupSummaryQueryParams(init: (GroupSummaryQueryParams.Builder.() -> Unit) = } /** - * This class can be used to filter group summaries + * This class can be used to filter group summaries. */ data class GroupSummaryQueryParams( val displayName: QueryStringValue, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt index 597c1a0ca8..5b06fdacae 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilities.kt @@ -34,25 +34,25 @@ data class HomeServerCapabilities( */ val canChange3pid: Boolean = true, /** - * Max size of file which can be uploaded to the homeserver in bytes. [MAX_UPLOAD_FILE_SIZE_UNKNOWN] if unknown or not retrieved yet + * Max size of file which can be uploaded to the homeserver in bytes. [MAX_UPLOAD_FILE_SIZE_UNKNOWN] if unknown or not retrieved yet. */ val maxUploadFileSize: Long = MAX_UPLOAD_FILE_SIZE_UNKNOWN, /** - * Last version identity server and binding supported + * Last version identity server and binding supported. */ val lastVersionIdentityServerSupported: Boolean = false, /** - * Default identity server url, provided in Wellknown + * Default identity server url, provided in Wellknown. */ val defaultIdentityServerUrl: String? = null, /** - * Room versions supported by the server + * Room versions supported by the server. * This capability describes the default and available room versions a server supports, and at what level of stability. * Clients should make use of this capability to determine if users need to be encouraged to upgrade their rooms. */ val roomVersions: RoomVersionCapabilities? = null, /** - * True if the home server support threading + * True if the home server support threading. */ val canUseThreading: Boolean = false ) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilitiesService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilitiesService.kt index f12cbcd6db..9d2c48e194 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilitiesService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/homeserver/HomeServerCapabilitiesService.kt @@ -22,12 +22,12 @@ package org.matrix.android.sdk.api.session.homeserver interface HomeServerCapabilitiesService { /** - * Force a refresh of the stored data + * Force a refresh of the stored data. */ suspend fun refreshHomeServerCapabilities() /** - * Get the HomeServer capabilities + * Get the HomeServer capabilities. */ fun getHomeServerCapabilities(): HomeServerCapabilities } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/IdentityService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/IdentityService.kt index fdcb30a5c8..c03b42e6c8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/IdentityService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/IdentityService.kt @@ -19,13 +19,13 @@ package org.matrix.android.sdk.api.session.identity import org.matrix.android.sdk.api.session.identity.model.SignInvitationResult /** - * Provides access to the identity server configuration and services identity server can provide + * Provides access to the identity server configuration and services identity server can provide. */ interface IdentityService { /** * Return the default identity server of the user, which may have been provided at login time by the homeserver, - * or by the Well-known setup of the homeserver - * It may be different from the current configured identity server + * or by the Well-known setup of the homeserver. + * It may be different from the current configured identity server. */ fun getDefaultIdentityServer(): String? @@ -35,9 +35,9 @@ interface IdentityService { fun getCurrentIdentityServerUrl(): String? /** - * Check if the identity server is valid - * See https://matrix.org/docs/spec/identity_service/latest#status-check - * Matrix Android SDK2 only supports identity server API v2 + * Check if the identity server is valid. + * See https://matrix.org/docs/spec/identity_service/latest#status-check. + * Matrix Android SDK2 only supports identity server API v2. */ suspend fun isValidIdentityServer(url: String) @@ -52,12 +52,12 @@ interface IdentityService { suspend fun setNewIdentityServer(url: String): String /** - * Disconnect (logout) from the current identity server + * Disconnect (logout) from the current identity server. */ suspend fun disconnect() /** - * This will ask the identity server to send an email or an SMS to let the user confirm he owns the ThreePid + * This will ask the identity server to send an email or an SMS to let the user confirm he owns the ThreePid. */ suspend fun startBindThreePid(threePid: ThreePid) @@ -67,32 +67,32 @@ interface IdentityService { suspend fun cancelBindThreePid(threePid: ThreePid) /** - * This will ask the identity server to send an new email or a new SMS to let the user confirm he owns the ThreePid + * This will ask the identity server to send an new email or a new SMS to let the user confirm he owns the ThreePid. */ suspend fun sendAgainValidationCode(threePid: ThreePid) /** - * Submit the code that the identity server has sent to the user (in email or SMS) + * Submit the code that the identity server has sent to the user (in email or SMS). * Once successful, you will have to call [finalizeBindThreePid] * @param code the code sent to the user */ suspend fun submitValidationToken(threePid: ThreePid, code: String) /** - * This will perform the actual association of ThreePid and Matrix account + * This will perform the actual association of ThreePid and Matrix account. */ suspend fun finalizeBindThreePid(threePid: ThreePid) /** - * Unbind a threePid - * The request will actually be done on the homeserver + * Unbind a threePid. + * The request will actually be done on the homeserver. */ suspend fun unbindThreePid(threePid: ThreePid) /** - * Search MatrixId of users providing email and phone numbers - * Note the the user consent has to be set to true, or it will throw a UserConsentNotProvided failure - * Application has to explicitly ask for the user consent, and the answer can be stored using [setUserConsent] + * Search MatrixId of users providing email and phone numbers. + * Note the the user consent has to be set to true, or it will throw a UserConsentNotProvided failure. + * Application has to explicitly ask for the user consent, and the answer can be stored using [setUserConsent]. * Please see https://support.google.com/googleplay/android-developer/answer/9888076?hl=en for more details. */ suspend fun lookUp(threePids: List): List @@ -115,8 +115,8 @@ interface IdentityService { fun setUserConsent(newValue: Boolean) /** - * Get the status of the current user's threePid - * A lookup will be performed, but also pending binding state will be restored + * Get the status of the current user's threePid. + * A lookup will be performed, but also pending binding state will be restored. * * @param threePids the list of threePid the user owns (retrieved form the homeserver) * @return a map of ThreePid -> SharedState @@ -126,7 +126,7 @@ interface IdentityService { /** * When one performs a 3pid invite and the third party identifier is unknown, the home server * will store the invitation in the Identity server and store some information in the room state membership event. - * The email invite will contains the token and secret that can be used to claim the stored invitation + * The email invite will contains the token and secret that can be used to claim the stored invitation. * * To aid clients who may not be able to perform crypto themselves, * the identity server offers some crypto functionality to help in accepting invitations. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/model/SignInvitationResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/model/SignInvitationResult.kt index b1662b9cf8..28d9d154f3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/model/SignInvitationResult.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/identity/model/SignInvitationResult.kt @@ -33,7 +33,7 @@ data class SignInvitationResult( */ val signatures: Map, /** - * The token for the invitation + * The token for the invitation. */ val token: String ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/SyncStatusService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/SyncStatusService.kt index 759813939f..7006e11751 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/SyncStatusService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/initsync/SyncStatusService.kt @@ -23,7 +23,7 @@ interface SyncStatusService { sealed class Status { /** - * For initial sync + * For initial sync. */ abstract class InitialSyncStatus : Status() @@ -34,7 +34,7 @@ interface SyncStatusService { ) : InitialSyncStatus() /** - * For incremental sync + * For incremental sync. */ abstract class IncrementalSyncStatus : Status() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/integrationmanager/IntegrationManagerConfig.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/integrationmanager/IntegrationManagerConfig.kt index 069ed7427c..b04b31af3b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/integrationmanager/IntegrationManagerConfig.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/integrationmanager/IntegrationManagerConfig.kt @@ -30,17 +30,17 @@ data class IntegrationManagerConfig( */ enum class Kind { /** - * Defined in UserAccountData + * Defined in UserAccountData. */ ACCOUNT, /** - * Defined in Wellknown + * Defined in Wellknown. */ HOMESERVER, /** - * Fallback value, hardcoded by the SDK + * Fallback value, hardcoded by the SDK. */ DEFAULT } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/MediaService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/MediaService.kt index 3b3ef57d73..2e53e67b0c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/MediaService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/MediaService.kt @@ -36,7 +36,7 @@ interface MediaService { suspend fun getRawPreviewUrl(url: String, timestamp: Long?): JsonDict /** - * Get Url Preview data from the homeserver, or from cache, depending on the cache strategy + * Get Url Preview data from the homeserver, or from cache, depending on the cache strategy. * @param url The url to get the preview data from * @param timestamp The optional timestamp. Note that this parameter is not taken into account * if the data is already in cache and the cache strategy allow to use it @@ -45,7 +45,7 @@ interface MediaService { suspend fun getPreviewUrl(url: String, timestamp: Long?, cacheStrategy: CacheStrategy): PreviewUrlData /** - * Clear the cache of all retrieved UrlPreview data + * Clear the cache of all retrieved UrlPreview data. */ suspend fun clearCache() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/PreviewUrlData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/PreviewUrlData.kt index bfba43a82d..b142ad9754 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/PreviewUrlData.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/media/PreviewUrlData.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.api.session.media /** - * Facility data class to get the common field of a PreviewUrl response form the server + * Facility data class to get the common field of a PreviewUrl response form the server. * * Example of return data for the url `https://matrix.org`: *
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkData.kt
index 57aacc98b8..e8d9c89b54 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkData.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkData.kt
@@ -33,10 +33,10 @@ sealed class PermalinkData {
             val viaParameters: List
     ) : PermalinkData()
 
-    /**
+    /*
      * &room_name=Team2
-    &room_avatar_url=mxc:
-    &inviter_name=bob
+     * &room_avatar_url=mxc:
+     * &inviter_name=bob
      */
     @Parcelize
     data class RoomEmailInviteLink(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt
index edb748c76e..9d078dc4b2 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkParser.kt
@@ -23,7 +23,7 @@ import timber.log.Timber
 import java.net.URLDecoder
 
 /**
- * This class turns a uri to a [PermalinkData]
+ * This class turns a uri to a [PermalinkData].
  * element-based domains (e.g. https://app.element.io/#/user/@chagai95:matrix.org) permalinks
  * or matrix.to permalinks (e.g. https://matrix.to/#/@chagai95:matrix.org)
  * or client permalinks (e.g. user/@chagai95:matrix.org)
@@ -31,7 +31,7 @@ import java.net.URLDecoder
 object PermalinkParser {
 
     /**
-     * Turns a uri string to a [PermalinkData]
+     * Turns a uri string to a [PermalinkData].
      */
     fun parse(uriString: String): PermalinkData {
         val uri = Uri.parse(uriString)
@@ -39,7 +39,7 @@ object PermalinkParser {
     }
 
     /**
-     * Turns a uri to a [PermalinkData]
+     * Turns a uri to a [PermalinkData].
      * https://github.com/matrix-org/matrix-doc/blob/master/proposals/1704-matrix.to-permalinks.md
      */
     fun parse(uri: Uri): PermalinkData {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkService.kt
index c139da813a..b49b80df09 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/permalinks/PermalinkService.kt
@@ -57,7 +57,7 @@ interface PermalinkService {
     fun createPermalink(id: String, forceMatrixTo: Boolean = false): String?
 
     /**
-     * Creates a permalink for a roomId, including the via parameters
+     * Creates a permalink for a roomId, including the via parameters.
      *
      * @param roomId the room id
      * @param forceMatrixTo whether we should force using matrix.to base URL
@@ -79,7 +79,7 @@ interface PermalinkService {
     fun createPermalink(roomId: String, eventId: String, forceMatrixTo: Boolean = false): String
 
     /**
-     * Extract the linked id from the universal link
+     * Extract the linked id from the universal link.
      *
      * @param url the universal link, Ex: "https://matrix.to/#/@benoit:matrix.org"
      * @return the id from the url, ex: "@benoit:matrix.org", or null if the url is not a permalink
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/PresenceService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/PresenceService.kt
index 82a81f4b64..901e7ec3dd 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/PresenceService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/PresenceService.kt
@@ -25,7 +25,7 @@ import org.matrix.android.sdk.api.session.presence.model.UserPresence
  */
 interface PresenceService {
     /**
-     * Update the presence status for the current user
+     * Update the presence status for the current user.
      * @param presence the new presence state
      * @param statusMsg the status message to attach to this state
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/model/PresenceEnum.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/model/PresenceEnum.kt
index 6d9994ef1c..c678e2a706 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/model/PresenceEnum.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/presence/model/PresenceEnum.kt
@@ -28,7 +28,10 @@ enum class PresenceEnum(val value: String) {
     OFFLINE("offline"),
 
     @Json(name = "unavailable")
-    UNAVAILABLE("unavailable");
+    UNAVAILABLE("unavailable"),
+
+    @Json(name = "org.matrix.msc3026.busy")
+    BUSY("busy");
 
     companion object {
         fun from(s: String): PresenceEnum? = values().find { it.value == s }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt
index d2c677bb31..095f2ef7c2 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/profile/ProfileService.kt
@@ -36,21 +36,21 @@ interface ProfileService {
     }
 
     /**
-     * Return the current display name for this user
+     * Return the current display name for this user.
      * @param userId the userId param to look for
      *
      */
     suspend fun getDisplayName(userId: String): Optional
 
     /**
-     * Update the display name for this user
+     * Update the display name for this user.
      * @param userId the userId to update the display name of
      * @param newDisplayName the new display name of the user
      */
     suspend fun setDisplayName(userId: String, newDisplayName: String)
 
     /**
-     * Update the avatar for this user
+     * Update the avatar for this user.
      * @param userId the userId to update the avatar of
      * @param newAvatarUri the new avatar uri of the user
      * @param fileName the fileName of selected image
@@ -74,12 +74,12 @@ interface ProfileService {
     suspend fun getProfile(userId: String): JsonDict
 
     /**
-     * Get the current user 3Pids
+     * Get the current user 3Pids.
      */
     fun getThreePids(): List
 
     /**
-     * Get the current user 3Pids Live
+     * Get the current user 3Pids Live.
      * @param refreshData set to true to fetch data from the homeserver
      */
     fun getThreePidsLive(refreshData: Boolean): LiveData>
@@ -90,7 +90,7 @@ interface ProfileService {
     fun getPendingThreePids(): List
 
     /**
-     * Get the pending 3Pids Live
+     * Get the pending 3Pids Live.
      */
     fun getPendingThreePidsLive(): LiveData>
 
@@ -100,18 +100,18 @@ interface ProfileService {
     suspend fun addThreePid(threePid: ThreePid)
 
     /**
-     * Validate a code received by text message
+     * Validate a code received by text message.
      */
     suspend fun submitSmsCode(threePid: ThreePid.Msisdn, code: String)
 
     /**
-     * Finalize adding a 3Pids. Call this method once the user has validated that he owns the ThreePid
+     * Finalize adding a 3Pids. Call this method once the user has validated that he owns the ThreePid.
      */
     suspend fun finalizeAddingThreePid(threePid: ThreePid,
                                        userInteractiveAuthInterceptor: UserInteractiveAuthInterceptor)
 
     /**
-     * Cancel adding a threepid. It will remove locally stored data about this ThreePid
+     * Cancel adding a threepid. It will remove locally stored data about this ThreePid.
      */
     suspend fun cancelAddingThreePid(threePid: ThreePid)
 
@@ -121,7 +121,7 @@ interface ProfileService {
     suspend fun deleteThreePid(threePid: ThreePid)
 
     /**
-     * Return a User object from a userId
+     * Return a User object from a userId.
      */
     suspend fun getProfileAsUser(userId: String): User {
         return getProfile(userId).let { dict ->
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt
index f884d3e890..5f9857eb2f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushers/PushersService.kt
@@ -21,7 +21,7 @@ import java.util.UUID
 interface PushersService {
 
     /**
-     * Refresh pushers from server state
+     * Refresh pushers from server state.
      */
     fun refreshPushers()
 
@@ -66,7 +66,7 @@ interface PushersService {
                                append: Boolean = true)
 
     /**
-     * Directly ask the push gateway to send a push to this device
+     * Directly ask the push gateway to send a push to this device.
      * If successful, the push gateway has accepted the request. In this case, the app should receive a Push with the provided eventId.
      * In case of error, PusherRejected will be thrown. In this case it means that the pushkey is not valid.
      *
@@ -81,30 +81,30 @@ interface PushersService {
                          eventId: String)
 
     /**
-     * Remove a registered pusher
+     * Remove a registered pusher.
      * @param pusher the pusher to remove, can be http or email
      */
     suspend fun removePusher(pusher: Pusher)
 
     /**
-     * Remove a Http pusher by its pushkey and appId
+     * Remove a Http pusher by its pushkey and appId.
      * @see addHttpPusher
      */
     suspend fun removeHttpPusher(pushkey: String, appId: String)
 
     /**
-     * Remove an Email pusher
+     * Remove an Email pusher.
      * @see addEmailPusher
      */
     suspend fun removeEmailPusher(email: String)
 
     /**
-     * Get the current pushers, as a LiveData
+     * Get the current pushers, as a LiveData.
      */
     fun getPushersLive(): LiveData>
 
     /**
-     * Get the current pushers
+     * Get the current pushers.
      */
     fun getPushers(): List
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt
index 7790942d84..2b2930c1ba 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/Action.kt
@@ -42,7 +42,7 @@ sealed class Action {
 }
 
 /**
- * Ref: https://matrix.org/docs/spec/client_server/latest#actions
+ * Ref: https://matrix.org/docs/spec/client_server/latest#actions.
  *
  * Convert
  * 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt
index abbdbf8104..bc4860be11 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/PushRuleService.kt
@@ -22,7 +22,7 @@ import org.matrix.android.sdk.api.session.pushrules.rest.RuleSet
 
 interface PushRuleService {
     /**
-     * Fetch the push rules from the server
+     * Fetch the push rules from the server.
      */
     fun fetchPushRules(scope: String = RuleScope.GLOBAL)
 
@@ -33,7 +33,7 @@ interface PushRuleService {
     suspend fun addPushRule(kind: RuleKind, pushRule: PushRule)
 
     /**
-     * Enables/Disables a push rule and updates the actions if necessary
+     * Enables/Disables a push rule and updates the actions if necessary.
      * @param enable Enables/Disables the rule
      * @param actions Actions to update if not null
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushRule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushRule.kt
index 270ffb2940..a11ffc0a98 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushRule.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/pushrules/rest/PushRule.kt
@@ -49,7 +49,7 @@ data class PushRule(
         @Json(name = "rule_id")
         val ruleId: String,
         /**
-         * The conditions that must hold true for an event in order for a rule to be applied to an event
+         * The conditions that must hold true for an event in order for a rule to be applied to an event.
          */
         @Json(name = "conditions")
         val conditions: List? = null,
@@ -71,7 +71,7 @@ data class PushRule(
     }
 
     /**
-     * Set the notification sound
+     * Set the notification sound.
      *
      * @param sound notification sound
      */
@@ -82,7 +82,7 @@ data class PushRule(
     }
 
     /**
-     * Remove the notification sound
+     * Remove the notification sound.
      */
     fun removeNotificationSound(): PushRule {
         return copy(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/Room.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/Room.kt
index 1f990f4c0a..3a18cf1497 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/Room.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/Room.kt
@@ -49,18 +49,18 @@ interface Room {
     val coroutineDispatchers: MatrixCoroutineDispatchers
 
     /**
-     * The roomId of this room
+     * The roomId of this room.
      */
     val roomId: String
 
     /**
-     * A live [RoomSummary] associated with the room
+     * A live [RoomSummary] associated with the room.
      * You can observe this summary to get dynamic data from this room.
      */
     fun getRoomSummaryLive(): LiveData>
 
     /**
-     * A current snapshot of [RoomSummary] associated with the room
+     * A current snapshot of [RoomSummary] associated with the room.
      */
     fun roomSummary(): RoomSummary?
 
@@ -70,97 +70,97 @@ interface Room {
     fun asSpace(): Space?
 
     /**
-     * Get the TimelineService associated to this Room
+     * Get the TimelineService associated to this Room.
      */
     fun timelineService(): TimelineService
 
     /**
-     * Get the ThreadsService associated to this Room
+     * Get the ThreadsService associated to this Room.
      */
     fun threadsService(): ThreadsService
 
     /**
-     * Get the ThreadsLocalService associated to this Room
+     * Get the ThreadsLocalService associated to this Room.
      */
     fun threadsLocalService(): ThreadsLocalService
 
     /**
-     * Get the SendService associated to this Room
+     * Get the SendService associated to this Room.
      */
     fun sendService(): SendService
 
     /**
-     * Get the DraftService associated to this Room
+     * Get the DraftService associated to this Room.
      */
     fun draftService(): DraftService
 
     /**
-     * Get the ReadService associated to this Room
+     * Get the ReadService associated to this Room.
      */
     fun readService(): ReadService
 
     /**
-     * Get the TypingService associated to this Room
+     * Get the TypingService associated to this Room.
      */
     fun typingService(): TypingService
 
     /**
-     * Get the AliasService associated to this Room
+     * Get the AliasService associated to this Room.
      */
     fun aliasService(): AliasService
 
     /**
-     * Get the TagsService associated to this Room
+     * Get the TagsService associated to this Room.
      */
     fun tagsService(): TagsService
 
     /**
-     * Get the MembershipService associated to this Room
+     * Get the MembershipService associated to this Room.
      */
     fun membershipService(): MembershipService
 
     /**
-     * Get the StateService associated to this Room
+     * Get the StateService associated to this Room.
      */
     fun stateService(): StateService
 
     /**
-     * Get the UploadsService associated to this Room
+     * Get the UploadsService associated to this Room.
      */
     fun uploadsService(): UploadsService
 
     /**
-     * Get the ReportingService associated to this Room
+     * Get the ReportingService associated to this Room.
      */
     fun reportingService(): ReportingService
 
     /**
-     * Get the RoomCallService associated to this Room
+     * Get the RoomCallService associated to this Room.
      */
     fun roomCallService(): RoomCallService
 
     /**
-     * Get the RelationService associated to this Room
+     * Get the RelationService associated to this Room.
      */
     fun relationService(): RelationService
 
     /**
-     * Get the RoomCryptoService associated to this Room
+     * Get the RoomCryptoService associated to this Room.
      */
     fun roomCryptoService(): RoomCryptoService
 
     /**
-     * Get the RoomPushRuleService associated to this Room
+     * Get the RoomPushRuleService associated to this Room.
      */
     fun roomPushRuleService(): RoomPushRuleService
 
     /**
-     * Get the RoomAccountDataService associated to this Room
+     * Get the RoomAccountDataService associated to this Room.
      */
     fun roomAccountDataService(): RoomAccountDataService
 
     /**
-     * Get the RoomVersionService associated to this Room
+     * Get the RoomVersionService associated to this Room.
      */
     fun roomVersionService(): RoomVersionService
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt
index 9446f0fdff..cb70603e66 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomDirectoryService.kt
@@ -26,18 +26,18 @@ import org.matrix.android.sdk.api.session.room.model.roomdirectory.PublicRoomsRe
 interface RoomDirectoryService {
 
     /**
-     * Get rooms from directory
+     * Get rooms from directory.
      */
     suspend fun getPublicRooms(server: String?,
                                publicRoomsParams: PublicRoomsParams): PublicRoomsResponse
 
     /**
-     * Get the visibility of a room in the directory
+     * Get the visibility of a room in the directory.
      */
     suspend fun getRoomDirectoryVisibility(roomId: String): RoomDirectoryVisibility
 
     /**
-     * Set the visibility of a room in the directory
+     * Set the visibility of a room in the directory.
      */
     suspend fun setRoomDirectoryVisibility(roomId: String, roomDirectoryVisibility: RoomDirectoryVisibility)
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomExtensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomExtensions.kt
index ece9cfbfac..0e631427bd 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomExtensions.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomExtensions.kt
@@ -21,13 +21,13 @@ import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent
 
 /**
- * Get a TimelineEvent using the TimelineService of a Room
+ * Get a TimelineEvent using the TimelineService of a Room.
  */
 fun Room.getTimelineEvent(eventId: String): TimelineEvent? =
         timelineService().getTimelineEvent(eventId)
 
 /**
- * Get a StateEvent using the StateService of a Room
+ * Get a StateEvent using the StateService of a Room.
  */
 fun Room.getStateEvent(eventType: String, stateKey: QueryStringValue = QueryStringValue.NoCondition): Event? =
         stateService().getStateEvent(eventType, stateKey)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt
index 700e292b0c..6d5551ddf0 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomService.kt
@@ -36,12 +36,12 @@ import org.matrix.android.sdk.api.util.Optional
 interface RoomService {
 
     /**
-     * Create a room asynchronously
+     * Create a room asynchronously.
      */
     suspend fun createRoom(createRoomParams: CreateRoomParams): String
 
     /**
-     * Create a direct room asynchronously. This is a facility method to create a direct room with the necessary parameters
+     * Create a direct room asynchronously. This is a facility method to create a direct room with the necessary parameters.
      */
     suspend fun createDirectRoom(otherUserId: String): String {
         return createRoom(
@@ -55,7 +55,7 @@ interface RoomService {
     }
 
     /**
-     * Join a room by id
+     * Join a room by id.
      * @param roomIdOrAlias the roomId or the room alias of the room to join
      * @param reason optional reason for joining the room
      * @param viaServers the servers to attempt to join the room through. One of the servers must be participating in the room.
@@ -84,14 +84,14 @@ interface RoomService {
     suspend fun leaveRoom(roomId: String, reason: String? = null)
 
     /**
-     * Get a room from a roomId
+     * Get a room from a roomId.
      * @param roomId the roomId to look for.
      * @return a room with roomId or null
      */
     fun getRoom(roomId: String): Room?
 
     /**
-     * Get a roomSummary from a roomId or a room alias
+     * Get a roomSummary from a roomId or a room alias.
      * @param roomIdOrAlias the roomId or the alias of a room to look for.
      * @return a matching room summary or null
      */
@@ -112,14 +112,14 @@ interface RoomService {
                              sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData>
 
     /**
-     * Get a snapshot list of Breadcrumbs
+     * Get a snapshot list of Breadcrumbs.
      * @param queryParams parameters to query the room summaries. It can be use to keep only joined rooms, for instance.
      * @return the immutable list of [RoomSummary]
      */
     fun getBreadcrumbs(queryParams: RoomSummaryQueryParams): List
 
     /**
-     * Get a live list of Breadcrumbs
+     * Get a live list of Breadcrumbs.
      * @param queryParams parameters to query the room summaries. It can be use to keep only joined rooms, for instance.
      * @return the [LiveData] of [RoomSummary]
      */
@@ -132,7 +132,7 @@ interface RoomService {
     suspend fun onRoomDisplayed(roomId: String)
 
     /**
-     * Mark all rooms as read
+     * Mark all rooms as read.
      */
     suspend fun markAllAsRead(roomIds: List)
 
@@ -143,7 +143,7 @@ interface RoomService {
                                  searchOnServer: Boolean): Optional
 
     /**
-     * Delete a room alias
+     * Delete a room alias.
      */
     suspend fun deleteRoomAlias(roomAlias: String)
 
@@ -162,7 +162,7 @@ interface RoomService {
     fun getChangeMembershipsLive(): LiveData>
 
     /**
-     * Return the roomId of an existing DM with the other user, or null if such room does not exist
+     * Return the roomId of an existing DM with the other user, or null if such room does not exist.
      * A room is a DM if:
      *  - it is listed in the `m.direct` account data
      *  - the current user has joined the room
@@ -175,7 +175,7 @@ interface RoomService {
     fun getExistingDirectRoomWithUser(otherUserId: String): String?
 
     /**
-     * Get a room member for the tuple {userId,roomId}
+     * Get a room member for the tuple {userId,roomId}.
      * @param userId the userId to look for.
      * @param roomId the roomId to look for.
      * @return the room member or null
@@ -183,7 +183,7 @@ interface RoomService {
     fun getRoomMember(userId: String, roomId: String): RoomMemberSummary?
 
     /**
-     * Observe a live room member for the tuple {userId,roomId}
+     * Observe a live room member for the tuple {userId,roomId}.
      * @param userId the userId to look for.
      * @param roomId the roomId to look for.
      * @return a LiveData of the optional found room member
@@ -191,39 +191,39 @@ interface RoomService {
     fun getRoomMemberLive(userId: String, roomId: String): LiveData>
 
     /**
-     * Get some state events about a room
+     * Get some state events about a room.
      */
     suspend fun getRoomState(roomId: String): List
 
     /**
-     * Use this if you want to get information from a room that you are not yet in (or invited)
-     * It might be possible to get some information on this room if it is public or if guest access is allowed
-     * This call will try to gather some information on this room, but it could fail and get nothing more
+     * Use this if you want to get information from a room that you are not yet in (or invited).
+     * It might be possible to get some information on this room if it is public or if guest access is allowed.
+     * This call will try to gather some information on this room, but it could fail and get nothing more.
      */
     suspend fun peekRoom(roomIdOrAlias: String): PeekResult
 
     /**
-     * TODO Doc
+     * TODO Doc.
      */
     fun getPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams,
                                   pagedListConfig: PagedList.Config = defaultPagedListConfig,
                                   sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): LiveData>
 
     /**
-     * TODO Doc
+     * TODO Doc.
      */
     fun getFilteredPagedRoomSummariesLive(queryParams: RoomSummaryQueryParams,
                                           pagedListConfig: PagedList.Config = defaultPagedListConfig,
                                           sortOrder: RoomSortOrder = RoomSortOrder.ACTIVITY): UpdatableLivePageResult
 
     /**
-     * Return a LiveData on the number of rooms
+     * Return a LiveData on the number of rooms.
      * @param queryParams parameters to query the room summaries. It can be use to keep only joined rooms, for instance.
      */
     fun getRoomCountLive(queryParams: RoomSummaryQueryParams): LiveData
 
     /**
-     * TODO Doc
+     * TODO Doc.
      */
     fun getNotificationCountForRooms(queryParams: RoomSummaryQueryParams): RoomAggregateNotificationCount
 
@@ -238,16 +238,16 @@ interface RoomService {
     fun getFlattenRoomSummaryChildrenOf(spaceId: String?, memberships: List = Membership.activeMemberships()): List
 
     /**
-     * Returns all the children of this space, as LiveData
+     * Returns all the children of this space, as LiveData.
      */
     fun getFlattenRoomSummaryChildrenOfLive(spaceId: String?,
                                             memberships: List = Membership.activeMemberships()): LiveData>
 
     /**
-     * Refreshes the RoomSummary LatestPreviewContent for the given @param roomId
-     * If the roomId is null, all rooms are updated
+     * Refreshes the RoomSummary LatestPreviewContent for the given @param roomId.
+     * If the roomId is null, all rooms are updated.
      *
-     * This is useful for refreshing summary content with encrypted messages after receiving new room keys
+     * This is useful for refreshing summary content with encrypted messages after receiving new room keys.
      */
     fun refreshJoinedRoomSummaryPreviews(roomId: String?)
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomSummaryQueryParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomSummaryQueryParams.kt
index b440857518..5c74dcced1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomSummaryQueryParams.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/RoomSummaryQueryParams.kt
@@ -41,7 +41,7 @@ fun spaceSummaryQueryParams(init: (RoomSummaryQueryParams.Builder.() -> Unit) =
 
 /**
  * This class can be used to filter room summaries to use with:
- * [org.matrix.android.sdk.api.session.room.Room] and [org.matrix.android.sdk.api.session.room.RoomService]
+ * [org.matrix.android.sdk.api.session.room.Room] and [org.matrix.android.sdk.api.session.room.RoomService].
  */
 data class RoomSummaryQueryParams(
         val roomId: QueryStringValue,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/accountdata/RoomAccountDataService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/accountdata/RoomAccountDataService.kt
index 190749c85c..b6925dd4a3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/accountdata/RoomAccountDataService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/accountdata/RoomAccountDataService.kt
@@ -25,29 +25,29 @@ import org.matrix.android.sdk.api.util.Optional
  */
 interface RoomAccountDataService {
     /**
-     * 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 getAccountDataEvent(type: String): RoomAccountDataEvent?
 
     /**
-     * Observe the account data with the provided type
+     * Observe the account data with the provided type.
      */
     fun getLiveAccountDataEvent(type: String): LiveData>
 
     /**
      * Retrieve the account data with the provided types. The return list can have a different size that
      * the size of the types set, because some AccountData may not exist.
-     * If an empty set is provided, all the AccountData are retrieved
+     * If an empty set is provided, all the AccountData are retrieved.
      */
     fun getAccountDataEvents(types: Set): List
 
     /**
-     * Observe the account data with the provided types. If an empty set is provided, all the AccountData are observed
+     * Observe the account data with the provided types. If an empty set is provided, all the AccountData are observed.
      */
     fun getLiveAccountDataEvents(types: Set): LiveData>
 
     /**
-     * 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 updateAccountData(type: String, content: Content)
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/alias/AliasService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/alias/AliasService.kt
index 5fe7e99425..2073db15b3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/alias/AliasService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/alias/AliasService.kt
@@ -18,13 +18,13 @@ package org.matrix.android.sdk.api.session.room.alias
 
 interface AliasService {
     /**
-     * Get list of local alias of the room
+     * Get list of local alias of the room.
      * @return the list of the aliases (full aliases, not only the local part)
      */
     suspend fun getRoomAliases(): List
 
     /**
-     * Add local alias to the room
+     * Add local alias to the room.
      * @param aliasLocalPart the local part of the alias.
      * Ex: for the alias "#my_alias:example.org", the local part is "my_alias"
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/call/RoomCallService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/call/RoomCallService.kt
index cac5217dd6..4439253a57 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/call/RoomCallService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/call/RoomCallService.kt
@@ -21,7 +21,7 @@ package org.matrix.android.sdk.api.session.room.call
  */
 interface RoomCallService {
     /**
-     * Return true if calls (audio or video) can be performed on this Room
+     * Return true if calls (audio or video) can be performed on this Room.
      */
     fun canStartCall(): Boolean
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/MembershipService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/MembershipService.kt
index 6c8e2d310c..e7ac69be74 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/MembershipService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/MembershipService.kt
@@ -39,14 +39,14 @@ interface MembershipService {
     fun getRoomMember(userId: String): RoomMemberSummary?
 
     /**
-     * Return all the roomMembers of the room with params
+     * Return all the roomMembers of the room with params.
      * @param queryParams the params to query for
      * @return a roomMember list.
      */
     fun getRoomMembers(queryParams: RoomMemberQueryParams): List
 
     /**
-     * Return all the roomMembers of the room filtered by memberships
+     * Return all the roomMembers of the room filtered by memberships.
      * @param queryParams the params to query for
      * @return a [LiveData] of roomMember list.
      */
@@ -55,27 +55,27 @@ interface MembershipService {
     fun getNumberOfJoinedMembers(): Int
 
     /**
-     * Invite a user in the room
+     * Invite a user in the room.
      */
     suspend fun invite(userId: String, reason: String? = null)
 
     /**
-     * Invite a user with email or phone number in the room
+     * Invite a user with email or phone number in the room.
      */
     suspend fun invite3pid(threePid: ThreePid)
 
     /**
-     * Ban a user from the room
+     * Ban a user from the room.
      */
     suspend fun ban(userId: String, reason: String? = null)
 
     /**
-     * Unban a user from the room
+     * Unban a user from the room.
      */
     suspend fun unban(userId: String, reason: String? = null)
 
     /**
-     * Remove a user from the room
+     * Remove a user from the room.
      */
     suspend fun remove(userId: String, reason: String? = null)
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/RoomMemberQueryParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/RoomMemberQueryParams.kt
index c2c5a7f804..dd83066dbb 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/RoomMemberQueryParams.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/members/RoomMemberQueryParams.kt
@@ -24,7 +24,7 @@ fun roomMemberQueryParams(init: (RoomMemberQueryParams.Builder.() -> Unit) = {})
 }
 
 /**
- * This class can be used to filter room members
+ * This class can be used to filter room members.
  */
 data class RoomMemberQueryParams(
         val displayName: QueryStringValue,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Invite.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Invite.kt
index 2841da35d1..f3c83c223a 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Invite.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Invite.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Subclass representing a search API response
+ * Subclass representing a search API response.
  */
 @JsonClass(generateAdapter = true)
 data class Invite(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Membership.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Membership.kt
index a5d0f63722..c0325d87ec 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Membership.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/Membership.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Represents the membership of a user on a room
+ * Represents the membership of a user on a room.
  */
 @JsonClass(generateAdapter = false)
 enum class Membership {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt
index 5c46db7166..8ef94b2896 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/PowerLevelsContent.kt
@@ -67,7 +67,7 @@ data class PowerLevelsContent(
         @Json(name = "notifications") val notifications: Map? = null
 ) {
     /**
-     * Return a copy of this content with a new power level for the specified user
+     * Return a copy of this content with a new power level for the specified user.
      *
      * @param userId the userId to alter the power level of
      * @param powerLevel the new power level, or null to set the default value.
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/ReferencesAggregatedSummary.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/ReferencesAggregatedSummary.kt
index 49ba2d5ab6..0bc87c9bf1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/ReferencesAggregatedSummary.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/ReferencesAggregatedSummary.kt
@@ -19,7 +19,7 @@ import org.matrix.android.sdk.api.session.events.model.Content
 
 /**
  * Events can relates to other events, this object keeps a summary
- * of all events that are referencing the 'eventId' event via the RelationType.REFERENCE
+ * of all events that are referencing the 'eventId' event via the RelationType.REFERENCE.
  */
 data class ReferencesAggregatedSummary(
         val content: Content?,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomAvatarContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomAvatarContent.kt
index 8c1c9e6b12..b6567fcf21 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomAvatarContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomAvatarContent.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class representing the EventType.STATE_ROOM_AVATAR state event content
+ * Class representing the EventType.STATE_ROOM_AVATAR state event content.
  */
 @JsonClass(generateAdapter = true)
 data class RoomAvatarContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomCanonicalAliasContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomCanonicalAliasContent.kt
index 4e8bd2e71b..1e76bef6f3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomCanonicalAliasContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomCanonicalAliasContent.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class representing the EventType.STATE_ROOM_CANONICAL_ALIAS state event content
+ * Class representing the EventType.STATE_ROOM_CANONICAL_ALIAS state event content.
  */
 @JsonClass(generateAdapter = true)
 data class RoomCanonicalAliasContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt
index 020e7ed39e..ba274325bc 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomGuestAccessContent.kt
@@ -27,13 +27,13 @@ import timber.log.Timber
 @JsonClass(generateAdapter = true)
 data class RoomGuestAccessContent(
         // Required. Whether guests can join the room. One of: ["can_join", "forbidden"]
-        @Json(name = "guest_access") val _guestAccess: String? = null
+        @Json(name = "guest_access") val guestAccessStr: String? = null
 ) {
-    val guestAccess: GuestAccess? = when (_guestAccess) {
+    val guestAccess: GuestAccess? = when (guestAccessStr) {
         "can_join"  -> GuestAccess.CanJoin
         "forbidden" -> GuestAccess.Forbidden
         else        -> {
-            Timber.w("Invalid value for GuestAccess: `$_guestAccess`")
+            Timber.w("Invalid value for GuestAccess: `$guestAccessStr`")
             null
         }
     }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt
index 3ac14e48de..da5c90ff05 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomHistoryVisibilityContent.kt
@@ -22,15 +22,15 @@ import timber.log.Timber
 
 @JsonClass(generateAdapter = true)
 data class RoomHistoryVisibilityContent(
-        @Json(name = "history_visibility") val _historyVisibility: String? = null
+        @Json(name = "history_visibility") val historyVisibilityStr: String? = null
 ) {
-    val historyVisibility: RoomHistoryVisibility? = when (_historyVisibility) {
+    val historyVisibility: RoomHistoryVisibility? = when (historyVisibilityStr) {
         "world_readable" -> RoomHistoryVisibility.WORLD_READABLE
         "shared"         -> RoomHistoryVisibility.SHARED
         "invited"        -> RoomHistoryVisibility.INVITED
         "joined"         -> RoomHistoryVisibility.JOINED
         else             -> {
-            Timber.w("Invalid value for RoomHistoryVisibility: `$_historyVisibility`")
+            Timber.w("Invalid value for RoomHistoryVisibility: `$historyVisibilityStr`")
             null
         }
     }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt
index 5237b10d52..3b338a36cd 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomJoinRulesContent.kt
@@ -23,11 +23,11 @@ import com.squareup.moshi.JsonClass
 import timber.log.Timber
 
 /**
- * Class representing the EventType.STATE_ROOM_JOIN_RULES state event content
+ * Class representing the EventType.STATE_ROOM_JOIN_RULES state event content.
  */
 @JsonClass(generateAdapter = true)
 data class RoomJoinRulesContent(
-        @Json(name = "join_rule") val _joinRules: String? = null,
+        @Json(name = "join_rule") val joinRulesStr: String? = null,
         /**
          * If the allow key is an empty list (or not a list at all),
          * then no users are allowed to join without an invite.
@@ -35,14 +35,14 @@ data class RoomJoinRulesContent(
          */
         @Json(name = "allow") val allowList: List? = null
 ) {
-    val joinRules: RoomJoinRules? = when (_joinRules) {
+    val joinRules: RoomJoinRules? = when (joinRulesStr) {
         "public"     -> RoomJoinRules.PUBLIC
         "invite"     -> RoomJoinRules.INVITE
         "knock"      -> RoomJoinRules.KNOCK
         "private"    -> RoomJoinRules.PRIVATE
         "restricted" -> RoomJoinRules.RESTRICTED
         else         -> {
-            Timber.w("Invalid value for RoomJoinRules: `$_joinRules`")
+            Timber.w("Invalid value for RoomJoinRules: `$joinRulesStr`")
             null
         }
     }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberContent.kt
index f29dd6a3e5..2529edbfdd 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberContent.kt
@@ -21,7 +21,7 @@ import com.squareup.moshi.JsonClass
 import org.matrix.android.sdk.api.session.events.model.UnsignedData
 
 /**
- * Class representing the EventType.STATE_ROOM_MEMBER state event content
+ * Class representing the EventType.STATE_ROOM_MEMBER state event content.
  */
 @JsonClass(generateAdapter = true)
 data class RoomMemberContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberSummary.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberSummary.kt
index 39177a4296..8e7382190a 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberSummary.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomMemberSummary.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.api.session.room.model
 import org.matrix.android.sdk.api.session.presence.model.UserPresence
 
 /**
- * Class representing a simplified version of EventType.STATE_ROOM_MEMBER state event content
+ * Class representing a simplified version of EventType.STATE_ROOM_MEMBER state event content.
  */
 data class RoomMemberSummary constructor(
         val membership: Membership,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomNameContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomNameContent.kt
index a0b45e881b..2dbb5f9e57 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomNameContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomNameContent.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class representing the EventType.STATE_ROOM_NAME state event content
+ * Class representing the EventType.STATE_ROOM_NAME state event content.
  */
 @JsonClass(generateAdapter = true)
 data class RoomNameContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomStrippedState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomStrippedState.kt
index dc0c00b282..b4f663f801 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomStrippedState.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomStrippedState.kt
@@ -79,7 +79,7 @@ data class RoomStrippedState(
         val avatarUrl: String? = null,
 
         /**
-         * Undocumented item
+         * Undocumented item.
          */
         @Json(name = "m.federate")
         val isFederated: Boolean = false,
@@ -103,7 +103,7 @@ data class RoomStrippedState(
         val membership: String?
 ) {
     /**
-     * Return the canonical alias, or the first alias from the list of aliases, or null
+     * Return the canonical alias, or the first alias from the list of aliases, or null.
      */
     fun getPrimaryAlias(): String? {
         return canonicalAlias ?: aliases?.firstOrNull()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomTopicContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomTopicContent.kt
index b97ee44dee..18092f12ac 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomTopicContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/RoomTopicContent.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class representing the EventType.STATE_ROOM_TOPIC state event content
+ * Class representing the EventType.STATE_ROOM_TOPIC state event content.
  */
 @JsonClass(generateAdapter = true)
 data class RoomTopicContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallCapabilities.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallCapabilities.kt
index d911ca3b88..6937b2c2e4 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallCapabilities.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallCapabilities.kt
@@ -24,7 +24,7 @@ import org.matrix.android.sdk.api.extensions.orFalse
 data class CallCapabilities(
         /**
          * If set to true, states that the sender of the event supports the m.call.replaces event and therefore supports
-         * being transferred to another destination
+         * being transferred to another destination.
          */
         @Json(name = "m.call.transferee") val transferee: Boolean? = null
 )
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallInviteContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallInviteContent.kt
index 24c8152f3c..40038ab8ec 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallInviteContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallInviteContent.kt
@@ -47,7 +47,7 @@ data class CallInviteContent(
          */
         @Json(name = "lifetime") val lifetime: Int?,
         /**
-         * The field should be added for all invites where the target is a specific user
+         * The field should be added for all invites where the target is a specific user.
          */
         @Json(name = "invitee") val invitee: String? = null,
         /**
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallReplacesContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallReplacesContent.kt
index e480e013ea..849fa50537 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallReplacesContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/call/CallReplacesContent.kt
@@ -44,7 +44,7 @@ data class CallReplacesContent(
          */
         @Json(name = "target_room") val targetRoomId: String? = null,
         /**
-         * An object giving information about the transfer target
+         * An object giving information about the transfer target.
          */
         @Json(name = "target_user") val targetUser: TargetUser? = null,
         /**
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/CreateRoomParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/CreateRoomParams.kt
index ce1e0e0d14..b7b0cc890b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/CreateRoomParams.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/CreateRoomParams.kt
@@ -69,13 +69,13 @@ open class CreateRoomParams {
     val invite3pids = mutableListOf()
 
     /**
-     * Initial Guest Access
+     * Initial Guest Access.
      */
     var guestAccess: GuestAccess? = null
 
     /**
      * If set to true, when the room will be created, if cross-signing is enabled and we can get keys for every invited users,
-     * the encryption will be enabled on the created room
+     * the encryption will be enabled on the created room.
      */
     var enableEncryptionIfInvitedUsersSupportIt: Boolean = false
 
@@ -135,7 +135,7 @@ open class CreateRoomParams {
         }
 
     /**
-     * The power level content to override in the default power level event
+     * The power level content to override in the default power level event.
      */
     var powerLevelContentOverride: PowerLevelsContent? = null
 
@@ -148,7 +148,7 @@ open class CreateRoomParams {
     }
 
     /**
-     * Supported value: MXCRYPTO_ALGORITHM_MEGOLM
+     * Supported value: MXCRYPTO_ALGORITHM_MEGOLM.
      */
     var algorithm: String? = null
         private set
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/Predecessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/Predecessor.kt
index f48beb299a..99c829b0e2 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/Predecessor.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/Predecessor.kt
@@ -19,7 +19,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * A link to an old room in case of room versioning
+ * A link to an old room in case of room versioning.
  */
 @JsonClass(generateAdapter = true)
 data class Predecessor(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomCreateContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomCreateContent.kt
index 52e5c0e9c7..d73c941a86 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomCreateContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomCreateContent.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Content of a m.room.create type event
+ * Content of a m.room.create type event.
  */
 @JsonClass(generateAdapter = true)
 data class RoomCreateContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomFeaturePreset.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomFeaturePreset.kt
index f5f722d783..6487ad947f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomFeaturePreset.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/create/RoomFeaturePreset.kt
@@ -47,7 +47,7 @@ class RestrictedRoomPreset(val homeServerCapabilities: HomeServerCapabilities, v
                         type = EventType.STATE_ROOM_JOIN_RULES,
                         stateKey = "",
                         content = RoomJoinRulesContent(
-                                _joinRules = RoomJoinRules.RESTRICTED.value,
+                                joinRulesStr = RoomJoinRules.RESTRICTED.value,
                                 allowList = restrictedList
                         ).toContent()
                 )
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/FileInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/FileInfo.kt
index 132b72902f..ae786ff706 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/FileInfo.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/FileInfo.kt
@@ -49,7 +49,7 @@ data class FileInfo(
 )
 
 /**
- * Get the url of the encrypted thumbnail or of the thumbnail
+ * Get the url of the encrypted thumbnail or of the thumbnail.
  */
 fun FileInfo.getThumbnailUrl(): String? {
     return thumbnailFile?.url ?: thumbnailUrl
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/ImageInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/ImageInfo.kt
index bd99ea6900..ec6669d4ec 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/ImageInfo.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/ImageInfo.kt
@@ -59,7 +59,7 @@ data class ImageInfo(
 )
 
 /**
- * Get the url of the encrypted thumbnail or of the thumbnail
+ * Get the url of the encrypted thumbnail or of the thumbnail.
  */
 fun ImageInfo.getThumbnailUrl(): String? {
     return thumbnailFile?.url ?: thumbnailUrl
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconInfoContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconInfoContent.kt
index f75704a891..f8b627e497 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconInfoContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconInfoContent.kt
@@ -32,7 +32,7 @@ import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultCon
 @JsonClass(generateAdapter = true)
 data class MessageBeaconInfoContent(
         /**
-         * Local message type, not from server
+         * Local message type, not from server.
          */
         @Transient
         override val msgType: String = MessageType.MSGTYPE_BEACON_INFO,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconLocationDataContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconLocationDataContent.kt
index 4a4ef46bc8..e261ab5206 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconLocationDataContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageBeaconLocationDataContent.kt
@@ -32,7 +32,7 @@ import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultCon
 @JsonClass(generateAdapter = true)
 data class MessageBeaconLocationDataContent(
         /**
-         * Local message type, not from server
+         * Local message type, not from server.
          */
         @Transient
         override val msgType: String = MessageType.MSGTYPE_BEACON_LOCATION_DATA,
@@ -42,13 +42,13 @@ data class MessageBeaconLocationDataContent(
         @Json(name = "m.new_content") override val newContent: Content? = null,
 
         /**
-         * See [MSC3488](https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md)
+         * See [MSC3488](https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md).
          */
         @Json(name = "org.matrix.msc3488.location") val unstableLocationInfo: LocationInfo? = null,
         @Json(name = "m.location") val locationInfo: LocationInfo? = null,
 
         /**
-         * Exact time that the data in the event refers to (milliseconds since the UNIX epoch)
+         * Exact time that the data in the event refers to (milliseconds since the UNIX epoch).
          */
         @Json(name = "org.matrix.msc3488.ts") val unstableTimestampMillis: Long? = null,
         @Json(name = "m.ts") val timestampMillis: Long? = null
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageContentWithFormattedBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageContentWithFormattedBody.kt
index aabf6173d7..58ea8db02d 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageContentWithFormattedBody.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageContentWithFormattedBody.kt
@@ -28,7 +28,7 @@ interface MessageContentWithFormattedBody : MessageContent {
     val formattedBody: String?
 
     /**
-     * Get the formattedBody, only if not blank and if the format is equal to "org.matrix.custom.html"
+     * Get the formattedBody, only if not blank and if the format is equal to "org.matrix.custom.html".
      */
     val matrixFormattedBody: String?
         get() = formattedBody?.takeIf { it.isNotBlank() && format == MessageFormat.FORMAT_MATRIX_HTML }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageEndPollContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageEndPollContent.kt
index 491b71477e..f0511903d0 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageEndPollContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageEndPollContent.kt
@@ -21,7 +21,7 @@ import com.squareup.moshi.JsonClass
 import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultContent
 
 /**
- * Class representing the org.matrix.msc3381.poll.end event content
+ * Class representing the org.matrix.msc3381.poll.end event content.
  */
 @JsonClass(generateAdapter = true)
 data class MessageEndPollContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageImageInfoContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageImageInfoContent.kt
index 369a1a1a46..e2b69eff33 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageImageInfoContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageImageInfoContent.kt
@@ -18,7 +18,7 @@
 package org.matrix.android.sdk.api.session.room.model.message
 
 /**
- * A content with image information
+ * A content with image information.
  */
 interface MessageImageInfoContent : MessageWithAttachmentContent {
     val info: ImageInfo?
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageLocationContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageLocationContent.kt
index 19cb20430d..0a66a6e400 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageLocationContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageLocationContent.kt
@@ -42,12 +42,12 @@ data class MessageLocationContent(
         @Json(name = "m.relates_to") override val relatesTo: RelationDefaultContent? = null,
         @Json(name = "m.new_content") override val newContent: Content? = null,
         /**
-         * See [MSC3488](https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md)
+         * See [MSC3488](https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md).
          */
         @Json(name = "org.matrix.msc3488.location") val unstableLocationInfo: LocationInfo? = null,
         @Json(name = "m.location") val locationInfo: LocationInfo? = null,
         /**
-         * Exact time that the data in the event refers to (milliseconds since the UNIX epoch)
+         * Exact time that the data in the event refers to (milliseconds since the UNIX epoch).
          */
         @Json(name = "org.matrix.msc3488.ts") val unstableTimestampMillis: Long? = null,
         @Json(name = "m.ts") val timestampMillis: Long? = null,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollContent.kt
index 43c0c90068..f784f05283 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollContent.kt
@@ -24,7 +24,7 @@ import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultCon
 @JsonClass(generateAdapter = true)
 data class MessagePollContent(
         /**
-         * Local message type, not from server
+         * Local message type, not from server.
          */
         @Transient
         override val msgType: String = MessageType.MSGTYPE_POLL_START,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollResponseContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollResponseContent.kt
index 022915ed69..32bfb71090 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollResponseContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessagePollResponseContent.kt
@@ -24,7 +24,7 @@ import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultCon
 @JsonClass(generateAdapter = true)
 data class MessagePollResponseContent(
         /**
-         * Local message type, not from server
+         * Local message type, not from server.
          */
         @Transient
         override val msgType: String = MessageType.MSGTYPE_POLL_RESPONSE,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageStickerContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageStickerContent.kt
index 3d774cadb2..f8c1c0d798 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageStickerContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageStickerContent.kt
@@ -25,7 +25,7 @@ import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultCon
 @JsonClass(generateAdapter = true)
 data class MessageStickerContent(
         /**
-         * Set in local, not from server
+         * Set in local, not from server.
          */
         @Transient
         override val msgType: String = MessageType.MSGTYPE_STICKER_LOCAL,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationKeyContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationKeyContent.kt
index 1a15e056ab..a6b36ce6cb 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationKeyContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationKeyContent.kt
@@ -26,7 +26,7 @@ import org.matrix.android.sdk.internal.crypto.verification.VerificationInfoKeyFa
 @JsonClass(generateAdapter = true)
 internal data class MessageVerificationKeyContent(
         /**
-         * The device’s ephemeral public key, as an unpadded base64 string
+         * The device’s ephemeral public key, as an unpadded base64 string.
          */
         @Json(name = "key") override val key: String? = null,
         @Json(name = "m.relates_to") val relatesTo: RelationDefaultContent?
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageWithAttachmentContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageWithAttachmentContent.kt
index 95dfb6b864..8d9dbee6b3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageWithAttachmentContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageWithAttachmentContent.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.api.session.room.model.message
 import org.matrix.android.sdk.api.session.crypto.model.EncryptedFileInfo
 
 /**
- * Interface for message which can contains an encrypted file
+ * Interface for message which can contains an encrypted file.
  */
 interface MessageWithAttachmentContent : MessageContent {
     /**
@@ -36,7 +36,7 @@ interface MessageWithAttachmentContent : MessageContent {
 }
 
 /**
- * Get the url of the encrypted file or of the file
+ * Get the url of the encrypted file or of the file.
  */
 fun MessageWithAttachmentContent.getFileUrl() = encryptedFileInfo?.url ?: url
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/VideoInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/VideoInfo.kt
index b02b4d96ad..b9c2472197 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/VideoInfo.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/VideoInfo.kt
@@ -64,7 +64,7 @@ data class VideoInfo(
 )
 
 /**
- * Get the url of the encrypted thumbnail or of the thumbnail
+ * Get the url of the encrypted thumbnail or of the thumbnail.
  */
 fun VideoInfo.getThumbnailUrl(): String? {
     return thumbnailFile?.url ?: thumbnailUrl
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationContent.kt
index 53b1fea873..01f7425322 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationContent.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.api.session.room.model.relation
 import org.matrix.android.sdk.api.session.events.model.RelationType
 
 interface RelationContent {
-    /** See [RelationType] for known possible values */
+    /** See [RelationType] for known possible values. */
     val type: String?
     val eventId: String?
     val inReplyTo: ReplyToContent?
@@ -27,7 +27,7 @@ interface RelationContent {
 
     /**
      * This flag indicates that the message should be rendered as a reply
-     * fallback, when isFallingBack = false
+     * fallback, when isFallingBack = false.
      */
     val isFallingBack: Boolean?
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt
index 4409898908..0d094b835b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/relation/RelationService.kt
@@ -82,7 +82,7 @@ interface RelationService {
                  options: List): Cancelable
 
     /**
-     * Edit a text message body. Limited to "m.text" contentType
+     * Edit a text message body. Limited to "m.text" contentType.
      * @param targetEvent The event to edit
      * @param newBodyText The edited body
      * @param compatibilityBodyText The text that will appear on clients that don't support yet edition
@@ -107,7 +107,7 @@ interface RelationService {
                   compatibilityBodyText: String = "* $newBodyText"): Cancelable
 
     /**
-     * Get the edit history of the given event
+     * Get the edit history of the given event.
      * The return list will contain the original event and all the editions of this event, done by the
      * same sender, sorted in the reverse order (so the original event is the latest element, and the
      * latest edition is the first element of the list)
@@ -133,21 +133,21 @@ interface RelationService {
     ): Cancelable?
 
     /**
-     * Get the current EventAnnotationsSummary
+     * Get the current EventAnnotationsSummary.
      * @param eventId the eventId to look for EventAnnotationsSummary
      * @return the EventAnnotationsSummary found
      */
     fun getEventAnnotationsSummary(eventId: String): EventAnnotationsSummary?
 
     /**
-     * Get a LiveData of EventAnnotationsSummary for the specified eventId
+     * Get a LiveData of EventAnnotationsSummary for the specified eventId.
      * @param eventId the eventId to look for EventAnnotationsSummary
      * @return the LiveData of EventAnnotationsSummary
      */
     fun getEventAnnotationsSummaryLive(eventId: String): LiveData>
 
     /**
-     * Creates a thread reply for an existing timeline event
+     * Creates a thread reply for an existing timeline event.
      * The replyInThreadText can be a Spannable and contains special spans (MatrixItemSpan) that will be translated
      * by the sdk into pills.
      * @param rootThreadEventId the root thread eventId
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoom.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoom.kt
index 01f5d9cde8..2033f366ae 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoom.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoom.kt
@@ -79,13 +79,13 @@ data class PublicRoom(
         val avatarUrl: String? = null,
 
         /**
-         * Undocumented item
+         * Undocumented item.
          */
         @Json(name = "m.federate")
         val isFederated: Boolean = false
 ) {
     /**
-     * Return the canonical alias, or the first alias from the list of aliases, or null
+     * Return the canonical alias, or the first alias from the list of aliases, or null.
      */
     fun getPrimaryAlias(): String? {
         return canonicalAlias ?: aliases?.firstOrNull()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsFilter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsFilter.kt
index 66ebc59464..cc0ce669b9 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsFilter.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsFilter.kt
@@ -19,7 +19,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class to define a filter to retrieve public rooms
+ * Class to define a filter to retrieve public rooms.
  */
 @JsonClass(generateAdapter = true)
 data class PublicRoomsFilter(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsParams.kt
index 3af354a01d..c4227b5767 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsParams.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsParams.kt
@@ -19,7 +19,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class to pass parameters to get the public rooms list
+ * Class to pass parameters to get the public rooms list.
  */
 @JsonClass(generateAdapter = true)
 data class PublicRoomsParams(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsResponse.kt
index 82da8bc49b..5a33ba3cdf 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsResponse.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/roomdirectory/PublicRoomsResponse.kt
@@ -19,7 +19,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class representing the public rooms request response
+ * Class representing the public rooms request response.
  */
 @JsonClass(generateAdapter = true)
 data class PublicRoomsResponse(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/thirdparty/ThirdPartyProtocolInstance.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/thirdparty/ThirdPartyProtocolInstance.kt
index 0ca0444589..6a2dc47650 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/thirdparty/ThirdPartyProtocolInstance.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/thirdparty/ThirdPartyProtocolInstance.kt
@@ -46,13 +46,13 @@ data class ThirdPartyProtocolInstance(
         val networkId: String? = null,
 
         /**
-         * FIXDOC Not documented on matrix.org doc
+         * FIXDOC Not documented on matrix.org doc.
          */
         @Json(name = "instance_id")
         val instanceId: String? = null,
 
         /**
-         * FIXDOC Not documented on matrix.org doc
+         * FIXDOC Not documented on matrix.org doc.
          */
         @Json(name = "bot_user_id")
         val botUserId: String? = null
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/tombstone/RoomTombstoneContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/tombstone/RoomTombstoneContent.kt
index 9b607aa712..d0a976cd97 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/tombstone/RoomTombstoneContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/tombstone/RoomTombstoneContent.kt
@@ -19,7 +19,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Class to contains Tombstone information
+ * Class to contains Tombstone information.
  */
 @JsonClass(generateAdapter = true)
 data class RoomTombstoneContent(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/notification/RoomNotificationState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/notification/RoomNotificationState.kt
index ea59ff4d48..919aed63eb 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/notification/RoomNotificationState.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/notification/RoomNotificationState.kt
@@ -17,26 +17,26 @@
 package org.matrix.android.sdk.api.session.room.notification
 
 /**
- * Defines the room notification state
+ * Defines the room notification state.
  */
 enum class RoomNotificationState {
     /**
-     * All the messages will trigger a noisy notification
+     * All the messages will trigger a noisy notification.
      */
     ALL_MESSAGES_NOISY,
 
     /**
-     * All the messages will trigger a notification
+     * All the messages will trigger a notification.
      */
     ALL_MESSAGES,
 
     /**
-     * Only the messages with user display name / user name will trigger notifications
+     * Only the messages with user display name / user name will trigger notifications.
      */
     MENTIONS_ONLY,
 
     /**
-     * No notifications
+     * No notifications.
      */
     MUTE
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/PowerLevelsHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/PowerLevelsHelper.kt
index 99139723a8..165a912b7f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/PowerLevelsHelper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/powerlevels/PowerLevelsHelper.kt
@@ -32,7 +32,7 @@ import org.matrix.android.sdk.api.session.room.model.usersDefaultOrDefault
 class PowerLevelsHelper(private val powerLevelsContent: PowerLevelsContent) {
 
     /**
-     * Returns the user power level of a dedicated user Id
+     * Returns the user power level of a dedicated user Id.
      *
      * @param userId the user id
      * @return the power level
@@ -44,7 +44,7 @@ class PowerLevelsHelper(private val powerLevelsContent: PowerLevelsContent) {
     }
 
     /**
-     * Returns the user power level of a dedicated user Id
+     * Returns the user power level of a dedicated user Id.
      *
      * @param userId the user id
      * @return the power level
@@ -56,7 +56,7 @@ class PowerLevelsHelper(private val powerLevelsContent: PowerLevelsContent) {
     }
 
     /**
-     * Tell if an user can send an event of a certain type
+     * Tell if an user can send an event of a certain type.
      *
      * @param userId  the id of the user to check for.
      * @param isState true if the event is a state event (ie. state key is not null)
@@ -77,7 +77,7 @@ class PowerLevelsHelper(private val powerLevelsContent: PowerLevelsContent) {
     }
 
     /**
-     * Check if the user have the necessary power level to invite
+     * Check if the user have the necessary power level to invite.
      * @param userId the id of the user to check for.
      * @return true if able to invite
      */
@@ -87,7 +87,7 @@ class PowerLevelsHelper(private val powerLevelsContent: PowerLevelsContent) {
     }
 
     /**
-     * Check if the user have the necessary power level to ban
+     * Check if the user have the necessary power level to ban.
      * @param userId the id of the user to check for.
      * @return true if able to ban
      */
@@ -97,7 +97,7 @@ class PowerLevelsHelper(private val powerLevelsContent: PowerLevelsContent) {
     }
 
     /**
-     * Check if the user have the necessary power level to kick
+     * Check if the user have the necessary power level to kick (remove).
      * @param userId the id of the user to check for.
      * @return true if able to kick
      */
@@ -107,7 +107,7 @@ class PowerLevelsHelper(private val powerLevelsContent: PowerLevelsContent) {
     }
 
     /**
-     * Check if the user have the necessary power level to redact
+     * Check if the user have the necessary power level to redact.
      * @param userId the id of the user to check for.
      * @return true if able to redact
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/read/ReadService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/read/ReadService.kt
index b037a3f366..036628c02f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/read/ReadService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/read/ReadService.kt
@@ -62,7 +62,7 @@ interface ReadService {
     fun getMyReadReceiptLive(): LiveData>
 
     /**
-     * Get the eventId where the read receipt for the provided user is
+     * Get the eventId where the read receipt for the provided user is.
      * @param userId the id of the user to look for
      *
      * @return the eventId where the read receipt for the provided user is attached, or null if not found
@@ -70,7 +70,7 @@ interface ReadService {
     fun getUserReadReceipt(userId: String): String?
 
     /**
-     * Returns a live list of read receipts for a given event
+     * Returns a live list of read receipts for a given event.
      * @param eventId: the event
      */
     fun getEventReadReceiptsLive(eventId: String): LiveData>
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/DraftService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/DraftService.kt
index a9481d71a2..e03c89a12a 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/DraftService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/DraftService.kt
@@ -22,22 +22,22 @@ import org.matrix.android.sdk.api.util.Optional
 interface DraftService {
 
     /**
-     * Save or update a draft to the room
+     * Save or update a draft to the room.
      */
     suspend fun saveDraft(draft: UserDraft)
 
     /**
-     * Delete the last draft, basically just after sending the message
+     * Delete the last draft, basically just after sending the message.
      */
     suspend fun deleteDraft()
 
     /**
-     * Return the current draft or null
+     * Return the current draft or null.
      */
     fun getDraft(): UserDraft?
 
     /**
-     * Return the current draft if any, as a live data
+     * Return the current draft if any, as a live data.
      */
     fun getDraftLive(): LiveData>
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt
index af7ab11df1..4bb8abef8a 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/SendService.kt
@@ -126,19 +126,19 @@ interface SendService {
     fun redactEvent(event: Event, reason: String?): Cancelable
 
     /**
-     * Schedule this message to be resent
+     * Schedule this message to be resent.
      * @param localEcho the unsent local echo
      */
     fun resendTextMessage(localEcho: TimelineEvent): Cancelable
 
     /**
-     * Schedule this message to be resent
+     * Schedule this message to be resent.
      * @param localEcho the unsent local echo
      */
     fun resendMediaMessage(localEcho: TimelineEvent): Cancelable
 
     /**
-     * Send a location event to the room
+     * Send a location event to the room.
      * @param latitude required latitude of the location
      * @param longitude required longitude of the location
      * @param uncertainty Accuracy of the location in meters
@@ -156,23 +156,23 @@ interface SendService {
     fun sendLiveLocation(beaconInfoEventId: String, latitude: Double, longitude: Double, uncertainty: Double?): Cancelable
 
     /**
-     * Remove this failed message from the timeline
+     * Remove this failed message from the timeline.
      * @param localEcho the unsent local echo
      */
     fun deleteFailedEcho(localEcho: TimelineEvent)
 
     /**
-     * Cancel sending a specific event. It has to be in one of the sending states
+     * Cancel sending a specific event. It has to be in one of the sending states.
      */
     fun cancelSend(eventId: String)
 
     /**
-     * Resend all failed messages one by one (and keep order)
+     * Resend all failed messages one by one (and keep order).
      */
     fun resendAllFailedMessages()
 
     /**
-     * Cancel all failed messages
+     * Cancel all failed messages.
      */
     fun cancelAllFailedMessages()
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt
index a8c0de2fa5..4ede1a66fc 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/send/UserDraft.kt
@@ -21,7 +21,7 @@ package org.matrix.android.sdk.api.session.room.send
  * REGULAR: draft of a classical message
  * QUOTE: draft of a message which quotes another message
  * EDIT: draft of an edition of a message
- * REPLY: draft of a reply of another message
+ * REPLY: draft of a reply of another message.
  */
 sealed interface UserDraft {
     data class Regular(val content: String) : UserDraft
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt
index 9b73136fc3..4c308c355a 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/sender/SenderInfo.kt
@@ -21,7 +21,7 @@ import org.matrix.android.sdk.internal.util.replaceSpaceChars
 data class SenderInfo(
         val userId: String,
         /**
-         * Consider using [disambiguatedDisplayName]
+         * Consider using [disambiguatedDisplayName].
          */
         val displayName: String?,
         val isUniqueDisplayName: Boolean,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateService.kt
index 98171795e2..f6b56128d3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateService.kt
@@ -30,57 +30,57 @@ import org.matrix.android.sdk.api.util.Optional
 interface StateService {
 
     /**
-     * Update the topic of the room
+     * Update the topic of the room.
      */
     suspend fun updateTopic(topic: String)
 
     /**
-     * Update the name of the room
+     * Update the name of the room.
      */
     suspend fun updateName(name: String)
 
     /**
-     * Update the canonical alias of the room
+     * Update the canonical alias of the room.
      * @param alias the canonical alias, or null to reset the canonical alias of this room
      * @param altAliases the alternative aliases for this room. It should include the canonical alias if any.
      */
     suspend fun updateCanonicalAlias(alias: String?, altAliases: List)
 
     /**
-     * Update the history readability of the room
+     * Update the history readability of the room.
      */
     suspend fun updateHistoryReadability(readability: RoomHistoryVisibility)
 
     /**
-     * Update the join rule and/or the guest access
+     * Update the join rule and/or the guest access.
      */
     suspend fun updateJoinRule(joinRules: RoomJoinRules?, guestAccess: GuestAccess?, allowList: List? = null)
 
     /**
-     * Update the avatar of the room
+     * Update the avatar of the room.
      */
     suspend fun updateAvatar(avatarUri: Uri, fileName: String)
 
     /**
-     * Delete the avatar of the room
+     * Delete the avatar of the room.
      */
     suspend fun deleteAvatar()
 
     /**
-     * Stops sharing live location in the room
+     * Stops sharing live location in the room.
      * @param userId user id
      */
     suspend fun stopLiveLocation(userId: String)
 
     /**
-     * Returns beacon info state event of a user
+     * Returns beacon info state event of a user.
      * @param userId user id who is sharing location
      * @param filterOnlyLive filters only ongoing live location sharing beacons if true else ended event is included
      */
     suspend fun getLiveLocationBeaconInfo(userId: String, filterOnlyLive: Boolean): Event?
 
     /**
-     * Send a state event to the room
+     * Send a state event to the room.
      * @param eventType The type of event to send.
      * @param stateKey The state_key for the state to send. Can be an empty string.
      * @param body The content object of the event; the fields in this object will vary depending on the type of event
@@ -89,23 +89,23 @@ interface StateService {
     suspend fun sendStateEvent(eventType: String, stateKey: String, body: JsonDict): String
 
     /**
-     * Get a state event of the room
+     * Get a state event of the room.
      */
     fun getStateEvent(eventType: String, stateKey: QueryStringValue = QueryStringValue.NoCondition): Event?
 
     /**
-     * Get a live state event of the room
+     * Get a live state event of the room.
      */
     fun getStateEventLive(eventType: String, stateKey: QueryStringValue = QueryStringValue.NoCondition): LiveData>
 
     /**
-     * Get state events of the room
+     * Get state events of the room.
      * @param eventTypes Set of eventType. If empty, all state events will be returned
      */
     fun getStateEvents(eventTypes: Set, stateKey: QueryStringValue = QueryStringValue.NoCondition): List
 
     /**
-     * Get live state events of the room
+     * Get live state events of the room.
      * @param eventTypes Set of eventType to observe. If empty, all state events will be observed
      */
     fun getStateEventsLive(eventTypes: Set, stateKey: QueryStringValue = QueryStringValue.NoCondition): LiveData>
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateServiceExtension.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateServiceExtension.kt
index c625a7f088..9e45fc126d 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateServiceExtension.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/state/StateServiceExtension.kt
@@ -23,7 +23,7 @@ import org.matrix.android.sdk.api.session.room.model.RoomJoinRules
 import org.matrix.android.sdk.api.session.room.model.RoomJoinRulesContent
 
 /**
- * Return true if a room can be joined by anyone (RoomJoinRules.PUBLIC)
+ * Return true if a room can be joined by anyone (RoomJoinRules.PUBLIC).
  */
 fun StateService.isPublic(): Boolean {
     return getStateEvent(EventType.STATE_ROOM_JOIN_RULES, QueryStringValue.NoCondition)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/tags/TagsService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/tags/TagsService.kt
index 69fde61f90..b6b82d8404 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/tags/TagsService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/tags/TagsService.kt
@@ -21,12 +21,12 @@ package org.matrix.android.sdk.api.session.room.tags
  */
 interface TagsService {
     /**
-     * Add a tag to a room
+     * Add a tag to a room.
      */
     suspend fun addTag(tag: String, order: Double?)
 
     /**
-     * Remove tag from a room
+     * Remove tag from a room.
      */
     suspend fun deleteTag(tag: String)
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/ThreadsService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/ThreadsService.kt
index 839cdff63b..9587be68f1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/ThreadsService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/ThreadsService.kt
@@ -28,24 +28,24 @@ import org.matrix.android.sdk.api.session.room.threads.model.ThreadSummary
 interface ThreadsService {
 
     /**
-     * Returns a [LiveData] list of all the [ThreadSummary] that exists at the room level
+     * Returns a [LiveData] list of all the [ThreadSummary] that exists at the room level.
      */
     fun getAllThreadSummariesLive(): LiveData>
 
     /**
-     * Returns a list of all the [ThreadSummary] that exists at the room level
+     * Returns a list of all the [ThreadSummary] that exists at the room level.
      */
     fun getAllThreadSummaries(): List
 
     /**
      * Enhance the provided ThreadSummary[List] by adding the latest
-     * message edition for that thread
+     * message edition for that thread.
      * @return the enhanced [List] with edited updates
      */
     fun enhanceThreadWithEditions(threads: List): List
 
     /**
-     * Fetch all thread replies for the specified thread using the /relations api
+     * Fetch all thread replies for the specified thread using the /relations api.
      * @param rootThreadEventId the root thread eventId
      * @param from defines the token that will fetch from that position
      * @param limit defines the number of max results the api will respond with
@@ -53,7 +53,7 @@ interface ThreadsService {
     suspend fun fetchThreadTimeline(rootThreadEventId: String, from: String, limit: Int)
 
     /**
-     * Fetch all thread summaries for the current room using the enhanced /messages api
+     * Fetch all thread summaries for the current room using the enhanced /messages api.
      */
     suspend fun fetchThreadSummaries()
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/local/ThreadsLocalService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/local/ThreadsLocalService.kt
index f7b379e382..b5cef3c62b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/local/ThreadsLocalService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/local/ThreadsLocalService.kt
@@ -27,34 +27,34 @@ import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent
 interface ThreadsLocalService {
 
     /**
-     * Returns a [LiveData] list of all the thread root TimelineEvents that exists at the room level
+     * Returns a [LiveData] list of all the thread root TimelineEvents that exists at the room level.
      */
     fun getAllThreadsLive(): LiveData>
 
     /**
-     * Returns a list of all the thread root TimelineEvents that exists at the room level
+     * Returns a list of all the thread root TimelineEvents that exists at the room level.
      */
     fun getAllThreads(): List
 
     /**
-     * Returns a [LiveData] list of all the marked unread threads that exists at the room level
+     * Returns a [LiveData] list of all the marked unread threads that exists at the room level.
      */
     fun getMarkedThreadNotificationsLive(): LiveData>
 
     /**
-     * Returns a list of all the marked unread threads that exists at the room level
+     * Returns a list of all the marked unread threads that exists at the room level.
      */
     fun getMarkedThreadNotifications(): List
 
     /**
-     * Returns whether or not the current user is participating in the thread
-     * @param rootThreadEventId the eventId of the current thread
+     * Returns whether or not the current user is participating in the thread.
+     * @param rootThreadEventId the eventId of the current thread.
      */
     fun isUserParticipatingInThread(rootThreadEventId: String): Boolean
 
     /**
      * Enhance the provided root thread TimelineEvent [List] by adding the latest
-     * message edition for that thread
+     * message edition for that thread.
      * @return the enhanced [List] with edited updates
      */
     fun mapEventsWithEdition(threads: List): List
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt
index 017afba1ba..1ef972e889 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/threads/model/ThreadSummary.kt
@@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.room.sender.SenderInfo
 
 /**
- * The main thread Summary model, mainly used to display the thread list
+ * The main thread Summary model, mainly used to display the thread list.
  */
 data class ThreadSummary(val roomId: String,
                          val rootEvent: Event?,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/Timeline.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/Timeline.kt
index d47a656798..1824d5dc6c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/Timeline.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/Timeline.kt
@@ -100,23 +100,23 @@ interface Timeline {
         fun onTimelineUpdated(snapshot: List) = Unit
 
         /**
-         * Called whenever an error we can't recover from occurred
+         * Called whenever an error we can't recover from occurred.
          */
         fun onTimelineFailure(throwable: Throwable) = Unit
 
         /**
-         * Called when new events come through the sync
+         * Called when new events come through the sync.
          */
         fun onNewTimelineEvents(eventIds: List) = Unit
 
         /**
-         * Called when the pagination state has changed in one direction
+         * Called when the pagination state has changed in one direction.
          */
         fun onStateUpdated(direction: Direction, state: PaginationState) = Unit
     }
 
     /**
-     * Pagination state
+     * Pagination state.
      */
     data class PaginationState(
             val hasMoreToLoad: Boolean = true,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt
index adbc8ab12a..d05fdb951f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEvent.kt
@@ -30,6 +30,7 @@ import org.matrix.android.sdk.api.session.events.model.toModel
 import org.matrix.android.sdk.api.session.room.model.EventAnnotationsSummary
 import org.matrix.android.sdk.api.session.room.model.ReadReceipt
 import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconInfoContent
+import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconLocationDataContent
 import org.matrix.android.sdk.api.session.room.model.message.MessageContent
 import org.matrix.android.sdk.api.session.room.model.message.MessagePollContent
 import org.matrix.android.sdk.api.session.room.model.message.MessageStickerContent
@@ -47,7 +48,7 @@ import org.matrix.android.sdk.api.util.ContentUtils.extractUsefulTextFromReply
 data class TimelineEvent(
         val root: Event,
         /**
-         * Uniquely identify an event, computed locally by the sdk
+         * Uniquely identify an event, computed locally by the sdk.
          */
         val localId: Long,
         val eventId: String,
@@ -103,12 +104,12 @@ data class TimelineEvent(
 }
 
 /**
- * Tells if the event has been edited
+ * Tells if the event has been edited.
  */
 fun TimelineEvent.hasBeenEdited() = annotations?.editSummary != null
 
 /**
- * Get the latest known eventId for an edited event, or the eventId for an Event which has not been edited
+ * Get the latest known eventId for an edited event, or the eventId for an Event which has not been edited.
  */
 fun TimelineEvent.getLatestEventId(): String {
     return annotations
@@ -119,33 +120,34 @@ fun TimelineEvent.getLatestEventId(): String {
 }
 
 /**
- * Get the relation content if any
+ * Get the relation content if any.
  */
 fun TimelineEvent.getRelationContent(): RelationDefaultContent? {
     return root.getRelationContent()
 }
 
 /**
- * Get the eventId which was edited by this event if any
+ * Get the eventId which was edited by this event if any.
  */
 fun TimelineEvent.getEditedEventId(): String? {
     return getRelationContent()?.takeIf { it.type == RelationType.REPLACE }?.eventId
 }
 
 /**
- * Get last MessageContent, after a possible edition
+ * Get last MessageContent, after a possible edition.
  */
 fun TimelineEvent.getLastMessageContent(): MessageContent? {
     return when (root.getClearType()) {
         EventType.STICKER                   -> root.getClearContent().toModel()
         in EventType.POLL_START             -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel()
         in EventType.STATE_ROOM_BEACON_INFO -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel()
+        in EventType.BEACON_LOCATION_DATA   -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel()
         else                                -> (annotations?.editSummary?.latestContent ?: root.getClearContent()).toModel()
     }
 }
 
 /**
- * Returns true if it's a reply
+ * Returns true if it's a reply.
  */
 fun TimelineEvent.isReply(): Boolean {
     return root.isReply()
@@ -163,14 +165,14 @@ fun TimelineEvent.isSticker(): Boolean {
 }
 
 /**
- * Returns whether or not the event is a root thread event
+ * Returns whether or not the event is a root thread event.
  */
 fun TimelineEvent.isRootThread(): Boolean {
     return root.threadDetails?.isRootThread.orFalse()
 }
 
 /**
- * Get the latest message body, after a possible edition, stripping the reply prefix if necessary
+ * Get the latest message body, after a possible edition, stripping the reply prefix if necessary.
  */
 fun TimelineEvent.getTextEditableContent(): String {
     val lastContentBody = getLastMessageContent()?.body ?: return ""
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEventFilters.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEventFilters.kt
index a35a291d9b..0f0c15b613 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEventFilters.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineEventFilters.kt
@@ -19,19 +19,19 @@ package org.matrix.android.sdk.api.session.room.timeline
 // TODO Move to internal, strange?
 data class TimelineEventFilters(
         /**
-         * A flag to filter edit events
+         * A flag to filter edit events.
          */
         val filterEdits: Boolean = false,
         /**
-         * A flag to filter redacted events
+         * A flag to filter redacted events.
          */
         val filterRedacted: Boolean = false,
         /**
-         * A flag to filter useless events, such as membership events without any change
+         * A flag to filter useless events, such as membership events without any change.
          */
         val filterUseless: Boolean = false,
         /**
-         * A flag to filter by types. It should be used with [allowedTypes] field
+         * A flag to filter by types. It should be used with [allowedTypes] field.
          */
         val filterTypes: Boolean = false,
         /**
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineSettings.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineSettings.kt
index b45f3ecb71..fd6732d0d1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineSettings.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/timeline/TimelineSettings.kt
@@ -29,13 +29,17 @@ data class TimelineSettings(
          */
         val buildReadReceipts: Boolean = true,
         /**
-         * The root thread eventId if this is a thread timeline, or null if this is NOT a thread timeline
+         * The root thread eventId if this is a thread timeline, or null if this is NOT a thread timeline.
          */
         val rootThreadEventId: String? = null,
+        /**
+         * If true Sender Info shown in room will get the latest data information (avatar + displayName).
+         */
+        val useLiveSenderInfo: Boolean = false,
 ) {
 
     /**
-     * Returns true if this is a thread timeline or false otherwise
+     * Returns true if this is a thread timeline or false otherwise.
      */
     fun isThreadTimeline() = rootThreadEventId != null
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/typing/TypingService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/typing/TypingService.kt
index e69afa4fc8..a462d5cba7 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/typing/TypingService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/typing/TypingService.kt
@@ -22,7 +22,7 @@ package org.matrix.android.sdk.api.session.room.typing
 interface TypingService {
 
     /**
-     * To call when user is typing a message in the room
+     * To call when user is typing a message in the room.
      * The SDK will handle the requests scheduling to the homeserver:
      * - No more than one typing request per 10s
      * - If not called after 10s, the SDK will notify the homeserver that the user is not typing anymore
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/uploads/UploadsService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/uploads/UploadsService.kt
index e2462d007d..b6fec9cd51 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/uploads/UploadsService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/uploads/UploadsService.kt
@@ -22,7 +22,7 @@ package org.matrix.android.sdk.api.session.room.uploads
 interface UploadsService {
 
     /**
-     * Get a list of events containing URL sent to a room, from most recent to oldest one
+     * Get a list of events containing URL sent to a room, from most recent to oldest one.
      * @param numberOfEvents the expected number of events to retrieve. The result can contain less events.
      * @param since token to get next page, or null to get the first page
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/version/RoomVersionService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/version/RoomVersionService.kt
index d806e6007e..4b6c907af0 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/version/RoomVersionService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/version/RoomVersionService.kt
@@ -18,28 +18,28 @@ package org.matrix.android.sdk.api.session.room.version
 
 interface RoomVersionService {
     /**
-     * Return the room version of this room
+     * Return the room version of this room.
      */
     fun getRoomVersion(): String
 
     /**
-     * Upgrade to the given room version
+     * Upgrade to the given room version.
      * @return the replacement room id
      */
     suspend fun upgradeToVersion(version: String): String
 
     /**
-     * Get the recommended room version for the current homeserver
+     * Get the recommended room version for the current homeserver.
      */
     fun getRecommendedVersion(): String
 
     /**
-     * Ask if the user has enough power level to upgrade the room
+     * Ask if the user has enough power level to upgrade the room.
      */
     fun userMayUpgradeRoom(userId: String): Boolean
 
     /**
-     * Return true if the current room version is declared unstable by the homeserver
+     * Return true if the current room version is declared unstable by the homeserver.
      */
     fun isUsingUnstableRoomVersion(): Boolean
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/EncryptedSecretContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/EncryptedSecretContent.kt
index 42682efb12..ddcecb466c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/EncryptedSecretContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/EncryptedSecretContent.kt
@@ -29,7 +29,7 @@ import org.matrix.android.sdk.internal.session.user.accountdata.AccountDataConte
  */
 @JsonClass(generateAdapter = true)
 data class EncryptedSecretContent(
-        /** unpadded base64-encoded ciphertext */
+        /** unpadded base64-encoded ciphertext. */
         @Json(name = "ciphertext") val ciphertext: String? = null,
         @Json(name = "mac") val mac: String? = null,
         @Json(name = "ephemeral") val ephemeral: String? = null,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SecretStorageKeyContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SecretStorageKeyContent.kt
index f7725be007..e7f872e400 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SecretStorageKeyContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SecretStorageKeyContent.kt
@@ -51,7 +51,7 @@ data class KeyInfo(
 
 @JsonClass(generateAdapter = true)
 data class SecretStorageKeyContent(
-        /** Currently support m.secret_storage.v1.curve25519-aes-sha2 */
+        /** Currently support m.secret_storage.v1.curve25519-aes-sha2. */
         @Json(name = "algorithm") val algorithm: String? = null,
         @Json(name = "name") val name: String? = null,
         @Json(name = "passphrase") val passphrase: SsssPassphrase? = null,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt
index 721a2bc8af..528e071966 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SharedSecretStorageService.kt
@@ -98,12 +98,12 @@ interface SharedSecretStorageService {
     suspend fun storeSecret(name: String, secretBase64: String, keys: List)
 
     /**
-     * Use this call to determine which SSSSKeySpec to use for requesting secret
+     * Use this call to determine which SSSSKeySpec to use for requesting secret.
      */
     fun getAlgorithmsForSecret(name: String): List
 
     /**
-     * Get an encrypted secret from the shared storage
+     * Get an encrypted secret from the shared storage.
      *
      * @param name The name of the secret
      * @param keyId The id of the key that should be used to decrypt (null for default key)
@@ -113,7 +113,7 @@ interface SharedSecretStorageService {
     suspend fun getSecret(name: String, keyId: String?, secretKey: SsssKeySpec): String
 
     /**
-     * Return true if SSSS is configured
+     * Return true if SSSS is configured.
      */
     fun isRecoverySetup(): Boolean {
         return checkShouldBeAbleToAccessSecrets(
@@ -131,7 +131,7 @@ interface SharedSecretStorageService {
 
     fun checkShouldBeAbleToAccessSecrets(secretNames: List, keyId: String?): IntegrityResult
 
-    fun requestSecret(name: String, myOtherDeviceId: String)
+    suspend fun requestSecret(name: String, myOtherDeviceId: String)
 
     data class KeyRef(
             val keyId: String?,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SsssKeySpec.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SsssKeySpec.kt
index 03efb9b3db..35a67b0865 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SsssKeySpec.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/securestorage/SsssKeySpec.kt
@@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.listeners.ProgressListener
 import org.matrix.android.sdk.api.session.crypto.keysbackup.extractCurveKeyFromRecoveryKey
 import org.matrix.android.sdk.internal.crypto.keysbackup.deriveKey
 
-/** Tag class */
+/** Tag class. */
 interface SsssKeySpec
 
 data class RawBytesKeySpec(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/signout/SignOutService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/signout/SignOutService.kt
index 4e4eba274e..d64b2e6e92 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/signout/SignOutService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/signout/SignOutService.kt
@@ -30,12 +30,12 @@ interface SignOutService {
     suspend fun signInAgain(password: String)
 
     /**
-     * Update the session with credentials received after SSO
+     * Update the session with credentials received after SSO.
      */
     suspend fun updateCredentials(credentials: Credentials)
 
     /**
-     * Sign out, and release the session, clear all the session data, including crypto data
+     * Sign out, and release the session, clear all the session data, including crypto data.
      * @param signOutFromHomeserver true if the sign out request has to be done
      */
     suspend fun signOut(signOutFromHomeserver: Boolean)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/JoinSpaceResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/JoinSpaceResult.kt
index e8c69977c6..a8a7ec61d7 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/JoinSpaceResult.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/JoinSpaceResult.kt
@@ -20,7 +20,7 @@ sealed class JoinSpaceResult {
     object Success : JoinSpaceResult()
     data class Fail(val error: Throwable) : JoinSpaceResult()
 
-    /** Success fully joined the space, but failed to join all or some of it's rooms */
+    /** Success fully joined the space, but failed to join all or some of it's rooms. */
     data class PartialSuccess(val failedRooms: Map) : JoinSpaceResult()
 
     fun isSuccess() = this is Success || this is PartialSuccess
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt
index f0ed9daac5..c990388628 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/Space.kt
@@ -27,7 +27,7 @@ interface Space {
     val spaceId: String
 
     /**
-     * A current snapshot of [RoomSummary] associated with the space
+     * A current snapshot of [RoomSummary] associated with the space.
      */
     fun spaceSummary(): RoomSummary?
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt
index afd26f7be5..8f16b3b9c3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/SpaceService.kt
@@ -29,13 +29,13 @@ typealias SpaceSummaryQueryParams = RoomSummaryQueryParams
 interface SpaceService {
 
     /**
-     * Create a space asynchronously
+     * Create a space asynchronously.
      * @return the spaceId of the created space
      */
     suspend fun createSpace(params: CreateSpaceParams): String
 
     /**
-     * Just a shortcut for space creation for ease of use
+     * Just a shortcut for space creation for ease of use.
      */
     suspend fun createSpace(name: String,
                             topic: String?,
@@ -44,7 +44,7 @@ interface SpaceService {
                             roomAliasLocalPart: String? = null): String
 
     /**
-     * Get a space from a roomId
+     * Get a space from a roomId.
      * @param spaceId the roomId to look for.
      * @return a space with spaceId or null if room type is not space
      */
@@ -58,7 +58,7 @@ interface SpaceService {
     suspend fun peekSpace(spaceId: String): SpacePeekResult
 
     /**
-     * Get's information of a space by querying the server
+     * Get's information of a space by querying the server.
      * @param suggestedOnly If true, return only child events and rooms where the m.space.child event has suggested: true.
      * @param limit a client-defined limit to the maximum number of rooms to return per page. Must be a non-negative integer.
      * @param from: Optional. Pagination token given to retrieve the next set of rooms. Note that if a pagination token is provided,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceChildContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceChildContent.kt
index b55f90cef0..215fcd9a54 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceChildContent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceChildContent.kt
@@ -20,11 +20,14 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
+ * Example:
+ * 
  *  "content": {
  *      "via": ["example.com"],
  *      "order": "abcd",
  *      "default": true
  *  }
+ * 
. */ @JsonClass(generateAdapter = true) data class SpaceChildContent( @@ -56,7 +59,7 @@ data class SpaceChildContent( ) { /** * Orders which are not strings, or do not consist solely of ascii characters in the range \x20 (space) to \x7F (~), - * or consist of more than 50 characters, are forbidden and should be ignored if received.) + * or consist of more than 50 characters, are forbidden and should be ignored if received.). */ fun validOrder(): String? { return order diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceOrderContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceOrderContent.kt index a8578347c8..47e276414e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceOrderContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/space/model/SpaceOrderContent.kt @@ -20,12 +20,15 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.api.MatrixPatterns /** + * Example: + *
  * {
  * "type": "m.space_order",
  *   "content": {
  *       "order": "..."
  *   }
  * }
+ * 
. */ @JsonClass(generateAdapter = true) data class SpaceOrderContent( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt index 946792d31e..76755517ce 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/statistics/StatisticEvent.kt @@ -17,11 +17,11 @@ package org.matrix.android.sdk.api.session.statistics /** - * Statistic Events. You can subscribe to received such events using [Session.Listener] + * Statistic Events. You can subscribe to received such events using [Session.Listener]. */ sealed interface StatisticEvent { /** - * Initial sync request, response downloading, and treatment (parsing and storage) of response + * Initial sync request, response downloading, and treatment (parsing and storage) of response. */ data class InitialSyncRequest(val requestDurationMs: Int, val downloadDurationMs: Int, @@ -29,7 +29,7 @@ sealed interface StatisticEvent { val nbOfJoinedRooms: Int) : StatisticEvent /** - * Incremental sync event + * Incremental sync event. */ data class SyncTreatment(val durationMs: Int, val afterPause: Boolean, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/FilterService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/FilterService.kt index 6d1d12f1bc..bc592df474 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/FilterService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/FilterService.kt @@ -22,13 +22,13 @@ interface FilterService { NoFilter, /** - * Filter for Element, will include only known event type + * Filter for Element, will include only known event type. */ ElementFilter } /** - * Configure the filter for the sync + * Configure the filter for the sync. */ fun setFilter(filterPreset: FilterPreset) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/InitialSyncStrategy.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/InitialSyncStrategy.kt index 461d816ea7..11f1093393 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/InitialSyncStrategy.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/InitialSyncStrategy.kt @@ -20,7 +20,7 @@ var initialSyncStrategy: InitialSyncStrategy = InitialSyncStrategy.Optimized() sealed class InitialSyncStrategy { /** - * Parse the result in its entirety + * Parse the result in its entirety. * Pros: * - Faster to handle parsed data * Cons: @@ -32,21 +32,21 @@ sealed class InitialSyncStrategy { /** * Optimized. - * First store the request result in a file, to avoid doing it again in case of crash + * First store the request result in a file, to avoid doing it again in case of crash. */ data class Optimized( /** - * Limit to reach to decide to split the init sync response into smaller files - * Empiric value: 1 megabytes + * Limit to reach to decide to split the init sync response into smaller files. + * Empiric value: 1 megabytes. */ val minSizeToSplit: Long = 1_048_576, // 1024 * 1024 /** - * Limit per room to reach to decide to store a join room ephemeral Events into a file - * Empiric value: 1 kilobytes + * Limit per room to reach to decide to store a join room ephemeral Events into a file. + * Empiric value: 1 kilobytes. */ val minSizeToStoreInFile: Long = 1024, /** - * Max number of rooms to insert at a time in database (to avoid too much RAM usage) + * Max number of rooms to insert at a time in database (to avoid too much RAM usage). */ val maxRoomsToInsert: Int = 100 ) : InitialSyncStrategy() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/DeviceListResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/DeviceListResponse.kt index c05e1e5187..929343e45d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/DeviceListResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/DeviceListResponse.kt @@ -19,7 +19,7 @@ package org.matrix.android.sdk.api.session.sync.model import com.squareup.moshi.JsonClass /** - * This class describes the device list response from a sync request + * This class describes the device list response from a sync request. */ @JsonClass(generateAdapter = true) data class DeviceListResponse( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/LazyRoomSyncEphemeral.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/LazyRoomSyncEphemeral.kt index 087a5f52dc..5bd7719d01 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/LazyRoomSyncEphemeral.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/LazyRoomSyncEphemeral.kt @@ -20,6 +20,6 @@ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = false) sealed class LazyRoomSyncEphemeral { - data class Parsed(val _roomSyncEphemeral: RoomSyncEphemeral) : LazyRoomSyncEphemeral() + data class Parsed(val roomSyncEphemeral: RoomSyncEphemeral) : LazyRoomSyncEphemeral() object Stored : LazyRoomSyncEphemeral() } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSync.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSync.kt index e3d07602c7..e5ac0a39b2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSync.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSync.kt @@ -48,7 +48,7 @@ data class RoomSync( @Json(name = "unread_notifications") val unreadNotifications: RoomSyncUnreadNotifications? = null, /** - * The room summary + * The room summary. */ @Json(name = "summary") val summary: RoomSyncSummary? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncSummary.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncSummary.kt index 7216a0c992..050fa119bb 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncSummary.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncSummary.kt @@ -36,12 +36,12 @@ data class RoomSyncSummary( @Json(name = "m.heroes") val heroes: List = emptyList(), /** - * The number of m.room.members in state 'joined' (including the syncing user) (can be null) + * The number of m.room.members in state 'joined' (including the syncing user) (can be null). */ @Json(name = "m.joined_member_count") val joinedMembersCount: Int? = null, /** - * The number of m.room.members in state 'invited' (can be null) + * The number of m.room.members in state 'invited' (can be null). */ @Json(name = "m.invited_member_count") val invitedMembersCount: Int? = null ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncTimeline.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncTimeline.kt index 82d29a52e2..4fc8adb769 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncTimeline.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/RoomSyncTimeline.kt @@ -30,12 +30,12 @@ data class RoomSyncTimeline( @Json(name = "events") val events: List? = null, /** - * Boolean which tells whether there are more events on the server + * Boolean which tells whether there are more events on the server. */ @Json(name = "limited") val limited: Boolean = false, /** - * If the batch was limited then this is a token that can be supplied to the server to retrieve more events + * If the batch was limited then this is a token that can be supplied to the server to retrieve more events. */ @Json(name = "prev_batch") val prevToken: String? = null ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/SyncResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/SyncResponse.kt index d7dff72288..c70964a513 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/SyncResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/sync/model/SyncResponse.kt @@ -48,12 +48,12 @@ data class SyncResponse( @Json(name = "rooms") val rooms: RoomsSyncResponse? = null, /** - * Devices list update + * Devices list update. */ @Json(name = "device_lists") val deviceLists: DeviceListResponse? = null, /** - * One time keys management + * One time keys management. */ @Json(name = "device_one_time_keys_count") val deviceOneTimeKeysCount: DeviceOneTimeKeysCountSyncResponse? = null, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationBadgeState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationBadgeState.kt index 8e861e73de..f3e92ad843 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationBadgeState.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationBadgeState.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.api.session.threads /** - * This class defines the state of a thread notification badge + * This class defines the state of a thread notification badge. */ data class ThreadNotificationBadgeState( val numberOfLocalUnreadThreads: Int = 0, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationState.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationState.kt index 8566d68aa5..c110802d23 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationState.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadNotificationState.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.api.session.threads /** - * This class defines the state of a thread notification + * This class defines the state of a thread notification. */ enum class ThreadNotificationState { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadTimelineEvent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadTimelineEvent.kt index 7b433566b8..53f89cefab 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadTimelineEvent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/threads/ThreadTimelineEvent.kt @@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent /** * This class contains a thread TimelineEvent along with a boolean that - * determines if the current user has participated in that event + * determines if the current user has participated in that event. */ data class ThreadTimelineEvent( val timelineEvent: TimelineEvent, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/UserService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/UserService.kt index 063abdb5a0..0c5465e12a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/UserService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/UserService.kt @@ -27,14 +27,14 @@ import org.matrix.android.sdk.api.util.Optional interface UserService { /** - * Get a user from a userId + * Get a user from a userId. * @param userId the userId to look for. * @return a user with userId or null */ fun getUser(userId: String): User? /** - * Try to resolve user from known users, or using profile api + * Try to resolve user from known users, or using profile api. */ suspend fun resolveUser(userId: String): User @@ -48,14 +48,14 @@ interface UserService { suspend fun searchUsersDirectory(search: String, limit: Int, excludedUserIds: Set): List /** - * Observe a live user from a userId + * Observe a live user from a userId. * @param userId the userId to look for. * @return a LiveData of user with userId */ fun getUserLive(userId: String): LiveData> /** - * Observe a live list of users sorted alphabetically + * Observe a live list of users sorted alphabetically. * @return a Livedata of users */ fun getUsersLive(): LiveData> @@ -69,19 +69,19 @@ interface UserService { fun getPagedUsersLive(filter: String? = null, excludedUserIds: Set? = null): LiveData> /** - * Get list of ignored users + * Get list of ignored users. */ fun getIgnoredUsersLive(): LiveData> /** - * Ignore users + * Ignore users. * Note: once done, for the change to take effect, you have to request an initial sync. - * This may be improved in the future + * This may be improved in the future. */ suspend fun ignoreUserIds(userIds: List) /** - * Un-ignore some users + * Un-ignore some users. * Note: once done, for the change to take effect, you have to request an initial sync. */ suspend fun unIgnoreUserIds(userIds: List) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/model/User.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/model/User.kt index 79c86f3f23..f231e88de0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/model/User.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/user/model/User.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.util.JsonDict data class User( val userId: String, /** - * For usage in UI, consider converting to MatrixItem and call getBestName() + * For usage in UI, consider converting to MatrixItem and call getBestName(). */ val displayName: String? = null, val avatarUrl: String? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetPostAPIMediator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetPostAPIMediator.kt index d8fd00d9e1..edb49f4797 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetPostAPIMediator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetPostAPIMediator.kt @@ -47,7 +47,7 @@ interface WidgetPostAPIMediator { fun injectAPI() /** - * Send a boolean response + * Send a boolean response. * * @param response the response * @param eventData the modular data @@ -55,7 +55,7 @@ interface WidgetPostAPIMediator { fun sendBoolResponse(response: Boolean, eventData: JsonDict) /** - * Send an integer response + * Send an integer response. * * @param response the response * @param eventData the modular data @@ -63,7 +63,7 @@ interface WidgetPostAPIMediator { fun sendIntegerResponse(response: Int, eventData: JsonDict) /** - * Send an object response + * Send an object response. * * @param klass the class of the response * @param response the response @@ -72,14 +72,14 @@ interface WidgetPostAPIMediator { fun sendObjectResponse(type: Type, response: T?, eventData: JsonDict) /** - * Send success + * Send success. * * @param eventData the modular data */ fun sendSuccess(eventData: JsonDict) /** - * Send an error + * Send an error. * * @param message the error message * @param eventData the modular data @@ -88,7 +88,7 @@ interface WidgetPostAPIMediator { interface Handler { /** - * Triggered when a widget is posting + * Triggered when a widget is posting. */ fun handleWidgetRequest(mediator: WidgetPostAPIMediator, eventData: JsonDict): Boolean } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetService.kt index 8f35ff0e4a..b06f8f7bc6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/widgets/WidgetService.kt @@ -55,7 +55,7 @@ interface WidgetService { ): List /** - * Return the computed URL of a widget + * Return the computed URL of a widget. */ fun getWidgetComputedUrl(widget: Widget, isLightTheme: Boolean): String? diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/Hash.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/Hash.kt index 7465eed3ae..22fdd1c610 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/Hash.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/Hash.kt @@ -20,7 +20,7 @@ import java.security.MessageDigest import java.util.Locale /** - * Compute a Hash of a String, using md5 algorithm + * Compute a Hash of a String, using md5 algorithm. */ fun String.md5() = try { val digest = MessageDigest.getInstance("md5") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt index 4f5f4f82d9..8a29d00380 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixItem.kt @@ -121,7 +121,7 @@ sealed class MatrixItem( abstract fun updateAvatar(newAvatar: String?): MatrixItem /** - * Return the prefix as defined in the matrix spec (and not extracted from the id) + * Return the prefix as defined in the matrix spec (and not extracted from the id). */ private fun getIdPrefix() = when (this) { is UserItem -> '@' diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixJsonParser.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixJsonParser.kt index 48a41667b2..9927dffa46 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixJsonParser.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/MatrixJsonParser.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Moshi import org.matrix.android.sdk.internal.di.MoshiProvider /** - * Entry point to get a Json parser + * Entry point to get a Json parser. */ object MatrixJsonParser { /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/TextContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/TextContent.kt index fe12d7b1cf..2aa548e289 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/TextContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/util/TextContent.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.api.util /** - * Contains a text and eventually a formatted text + * Contains a text and eventually a formatted text. */ data class TextContent( val text: String, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt index ebad859b05..46fa63334c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/AuthAPI.kt @@ -45,26 +45,26 @@ import retrofit2.http.Url */ internal interface AuthAPI { /** - * Get a Web client config file, using the name including the domain + * Get a Web client config file, using the name including the domain. */ @GET("config.{domain}.json") suspend fun getWebClientConfigDomain(@Path("domain") domain: String): WebClientConfig /** - * Get a Web client default config file + * Get a Web client default config file. */ @GET("config.json") suspend fun getWebClientConfig(): WebClientConfig /** - * Get the version information of the homeserver + * Get the version information of the homeserver. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_ + "versions") suspend fun versions(): Versions /** - * Register to the homeserver, or get error 401 with a RegistrationFlowResponse object if registration is incomplete - * Ref: https://matrix.org/docs/spec/client_server/latest#account-registration-and-management + * Register to the homeserver, or get error 401 with a RegistrationFlowResponse object if registration is incomplete. + * Ref: https://matrix.org/docs/spec/client_server/latest#account-registration-and-management. */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "register") suspend fun register(@Body registrationParams: RegistrationParams): Credentials @@ -102,14 +102,14 @@ internal interface AuthAPI { @Body params: AddThreePidRegistrationParams): AddThreePidRegistrationResponse /** - * Validate 3pid + * Validate 3pid. */ @POST suspend fun validate3Pid(@Url url: String, @Body params: ValidationCodeBody): SuccessResult /** - * Get the supported login flow + * Get the supported login flow. * Ref: https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-login */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "login") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/Constants.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/Constants.kt index 3742a429d2..97f8a9d512 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/Constants.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/Constants.kt @@ -23,13 +23,13 @@ package org.matrix.android.sdk.internal.auth internal const val LOGIN_FALLBACK_PATH = "/_matrix/static/client/login/" /** - * Path to use when the client does not supported any or all registration flows - * Not documented + * Path to use when the client does not supported any or all registration flows. + * Not documented. */ internal const val REGISTER_FALLBACK_PATH = "/_matrix/static/client/register/" /** - * Path to use when the client want to connect using SSO + * Path to use when the client want to connect using SSO. * Ref: https://matrix.org/docs/spec/client_server/latest#sso-client-login */ internal const val SSO_REDIRECT_PATH = "/_matrix/client/r0/login/sso/redirect" diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt index f1cfe3fee5..02dfce04b5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/DefaultAuthenticationService.kt @@ -20,7 +20,7 @@ import android.net.Uri import dagger.Lazy import okhttp3.OkHttpClient import org.matrix.android.sdk.api.MatrixPatterns -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.auth.AuthenticationService import org.matrix.android.sdk.api.auth.data.Credentials import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig @@ -381,7 +381,7 @@ internal class DefaultAuthenticationService @Inject constructor( return getWellknownTask.execute( GetWellknownTask.Params( - domain = matrixId.getDomain(), + domain = matrixId.getServerName().substringBeforeLast(":"), homeServerConnectionConfig = homeServerConnectionConfig.orWellKnownDefaults() ) ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/PendingSessionStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/PendingSessionStore.kt index 06954fa5c2..7483e2c7d9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/PendingSessionStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/PendingSessionStore.kt @@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.auth import org.matrix.android.sdk.internal.auth.db.PendingSessionData /** - * Store for elements when doing login or registration + * Store for elements when doing login or registration. */ internal interface PendingSessionStore { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt index cc00c963ea..ba01146a4a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/SessionCreator.kt @@ -39,7 +39,7 @@ internal class DefaultSessionCreator @Inject constructor( /** * Credentials can affect the homeServerConnectionConfig, override homeserver url and/or - * identity server url if provided in the credentials + * identity server url if provided in the credentials. */ override suspend fun createSession(credentials: Credentials, homeServerConnectionConfig: HomeServerConnectionConfig): Session { // We can cleanup the pending session params diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/LoginFlowResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/LoginFlowResponse.kt index c718fae390..df10e110d1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/LoginFlowResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/LoginFlowResponse.kt @@ -23,7 +23,7 @@ import org.matrix.android.sdk.api.auth.data.SsoIdentityProvider @JsonClass(generateAdapter = true) internal data class LoginFlowResponse( /** - * The homeserver's supported login types + * The homeserver's supported login types. */ @Json(name = "flows") val flows: List? @@ -39,7 +39,7 @@ internal data class LoginFlow( /** * Augments m.login.sso flow discovery definition to include metadata on the supported IDPs - * the client can show a button for each of the supported providers + * the client can show a button for each of the supported providers. * See MSC #2858 */ @Json(name = "identity_providers") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/WebClientConfig.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/WebClientConfig.kt index 65c3dc64a6..a993124a7e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/WebClientConfig.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/data/WebClientConfig.kt @@ -22,7 +22,7 @@ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) internal data class WebClientConfig( /** - * This is now deprecated, but still used first, rather than value from "default_server_config" + * This is now deprecated, but still used first, rather than value from "default_server_config". */ @Json(name = "default_hs_url") val defaultHomeServerUrl: String?, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt index 59b6471a05..88c6d04ee6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmMigration.kt @@ -27,8 +27,8 @@ import javax.inject.Inject internal class AuthRealmMigration @Inject constructor() : RealmMigration { /** - * Forces all AuthRealmMigration instances to be equal - * Avoids Realm throwing when multiple instances of the migration are set + * Forces all AuthRealmMigration instances to be equal. + * Avoids Realm throwing when multiple instances of the migration are set. */ override fun equals(other: Any?) = other is AuthRealmMigration override fun hashCode() = 4000 diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmModule.kt index 08d683af7f..dbf1977602 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/AuthRealmModule.kt @@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.auth.db import io.realm.annotations.RealmModule /** - * Realm module for authentication classes + * Realm module for authentication classes. */ @RealmModule( library = true, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/PendingSessionData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/PendingSessionData.kt index 6e13e947f4..835070d4b7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/PendingSessionData.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/db/PendingSessionData.kt @@ -22,7 +22,7 @@ import org.matrix.android.sdk.internal.auth.registration.ThreePidData import java.util.UUID /** - * This class holds all pending data when creating a session, either by login or by register + * This class holds all pending data when creating a session, either by login or by register. */ internal data class PendingSessionData( val homeServerConnectionConfig: HomeServerConnectionConfig, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt index 06fcacd514..a65ec38d6d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/login/ResetPasswordData.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.internal.auth.registration.AddThreePidRegistrationResponse /** - * Container to store the data when a reset password is in the email validation step + * Container to store the data when a reset password is in the email validation step. */ @JsonClass(generateAdapter = true) internal data class ResetPasswordData( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt index f8d17b406a..2f05864d3b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AddThreePidRegistrationParams.kt @@ -21,7 +21,7 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.api.auth.registration.RegisterThreePid /** - * Add a three Pid during authentication + * Add a three Pid during authentication. */ @JsonClass(generateAdapter = true) internal data class AddThreePidRegistrationParams( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AuthParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AuthParams.kt index cb17207741..6337a6e5c5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AuthParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/AuthParams.kt @@ -21,7 +21,7 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.api.auth.data.LoginFlowTypes /** - * Open class, parent to all possible authentication parameters + * Open class, parent to all possible authentication parameters. */ @JsonClass(generateAdapter = true) internal data class AuthParams( @@ -29,19 +29,19 @@ internal data class AuthParams( val type: String, /** - * Note: session can be null for reset password request + * Note: session can be null for reset password request. */ @Json(name = "session") val session: String?, /** - * parameter for "m.login.recaptcha" type + * parameter for "m.login.recaptcha" type. */ @Json(name = "response") val captchaResponse: String? = null, /** - * parameter for "m.login.email.identity" type + * parameter for "m.login.email.identity" type. */ @Json(name = "threepid_creds") val threePidCredentials: ThreePidCredentials? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt index 890cb68aad..8f00f3440c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/DefaultRegistrationWizard.kt @@ -33,7 +33,7 @@ import org.matrix.android.sdk.internal.auth.SessionCreator import org.matrix.android.sdk.internal.auth.db.PendingSessionData /** - * This class execute the registration request and is responsible to keep the session of interactive authentication + * This class execute the registration request and is responsible to keep the session of interactive authentication. */ internal class DefaultRegistrationWizard( authAPI: AuthAPI, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt index 43167062d5..c8f71af306 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ThreePidData.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.api.auth.registration.RegisterThreePid /** - * Container to store the data when a three pid is in validation step + * Container to store the data when a three pid is in validation step. */ @JsonClass(generateAdapter = true) internal data class ThreePidData( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt index 7dafacb3c0..9b135c347d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/UIAExt.kt @@ -26,7 +26,7 @@ import timber.log.Timber import kotlin.coroutines.suspendCoroutine /** - * Handle a UIA challenge + * Handle a UIA challenge. * * @param failure the failure to handle * @param interceptor see doc in [UserInteractiveAuthInterceptor] diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ValidationCodeBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ValidationCodeBody.kt index ae71ae3a08..72b3dc6103 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ValidationCodeBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/registration/ValidationCodeBody.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * This object is used to send a code received by SMS to validate Msisdn ownership + * This object is used to send a code received by SMS to validate Msisdn ownership. */ @JsonClass(generateAdapter = true) internal data class ValidationCodeBody( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/Versions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/Versions.kt index d07d5ecd64..cee4b12138 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/Versions.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/auth/version/Versions.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Model for https://matrix.org/docs/spec/client_server/latest#get-matrix-client-versions + * Model for https://matrix.org/docs/spec/client_server/latest#get-matrix-client-versions. * * Ex: *
@@ -55,14 +55,14 @@ private const val FEATURE_THREADS_MSC3440 = "org.matrix.msc3440"
 private const val FEATURE_THREADS_MSC3440_STABLE = "org.matrix.msc3440.stable"
 
 /**
- * Return true if the SDK supports this homeserver version
+ * Return true if the SDK supports this homeserver version.
  */
 internal fun Versions.isSupportedBySdk(): Boolean {
     return supportLazyLoadMembers()
 }
 
 /**
- * Return true if the SDK supports this homeserver version for login and registration
+ * Return true if the SDK supports this homeserver version for login and registration.
  */
 internal fun Versions.isLoginAndRegistrationSupportedBySdk(): Boolean {
     return !doesServerRequireIdentityServerParam() &&
@@ -71,15 +71,15 @@ internal fun Versions.isLoginAndRegistrationSupportedBySdk(): Boolean {
 }
 
 /**
- * Indicate if the homeserver support MSC3440 for threads
+ * Indicate if the homeserver support MSC3440 for threads.
  */
 internal fun Versions.doesServerSupportThreads(): Boolean {
-    return getMaxVersion() >= HomeServerVersion.v1_3_0 ||
-            unstableFeatures?.get(FEATURE_THREADS_MSC3440_STABLE) ?: false
+    // TODO Check for v1.3 or whichever spec version formally specifies MSC3440.
+    return unstableFeatures?.get(FEATURE_THREADS_MSC3440_STABLE) ?: false
 }
 
 /**
- * Return true if the server support the lazy loading of room members
+ * Return true if the server support the lazy loading of room members.
  *
  * @return true if the server support the lazy loading of room members
  */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CancelGossipRequestWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CancelGossipRequestWorker.kt
deleted file mode 100644
index aaf23d17b3..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CancelGossipRequestWorker.kt
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto
-
-import android.content.Context
-import androidx.work.WorkerParameters
-import com.squareup.moshi.JsonClass
-import org.matrix.android.sdk.api.auth.data.Credentials
-import org.matrix.android.sdk.api.failure.shouldBeRetried
-import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState
-import org.matrix.android.sdk.api.session.events.model.Event
-import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.api.session.events.model.toContent
-import org.matrix.android.sdk.internal.SessionManager
-import org.matrix.android.sdk.internal.crypto.model.rest.ShareRequestCancellation
-import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
-import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
-import org.matrix.android.sdk.internal.crypto.tasks.createUniqueTxnId
-import org.matrix.android.sdk.internal.session.SessionComponent
-import org.matrix.android.sdk.internal.util.time.Clock
-import org.matrix.android.sdk.internal.worker.SessionSafeCoroutineWorker
-import org.matrix.android.sdk.internal.worker.SessionWorkerParams
-import javax.inject.Inject
-
-internal class CancelGossipRequestWorker(context: Context, params: WorkerParameters, sessionManager: SessionManager) :
-        SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) {
-
-    @JsonClass(generateAdapter = true)
-    internal data class Params(
-            override val sessionId: String,
-            val requestId: String,
-            val recipients: Map>,
-            // The txnId for the sendToDevice request. Nullable for compatibility reasons, but MUST always be provided
-            // to use the same value if this worker is retried.
-            val txnId: String? = null,
-            override val lastFailureMessage: String? = null
-    ) : SessionWorkerParams {
-        companion object {
-            fun fromRequest(sessionId: String, request: OutgoingGossipingRequest): Params {
-                return Params(
-                        sessionId = sessionId,
-                        requestId = request.requestId,
-                        recipients = request.recipients,
-                        txnId = createUniqueTxnId(),
-                        lastFailureMessage = null
-                )
-            }
-        }
-    }
-
-    @Inject lateinit var sendToDeviceTask: SendToDeviceTask
-    @Inject lateinit var cryptoStore: IMXCryptoStore
-    @Inject lateinit var credentials: Credentials
-    @Inject lateinit var clock: Clock
-
-    override fun injectWith(injector: SessionComponent) {
-        injector.inject(this)
-    }
-
-    override suspend fun doSafeWork(params: Params): Result {
-        // params.txnId should be provided in all cases now. But Params can be deserialized by
-        // the WorkManager from data serialized in a previous version of the application, so without the txnId field.
-        // So if not present, we create a txnId
-        val txnId = params.txnId ?: createUniqueTxnId()
-        val contentMap = MXUsersDevicesMap()
-        val toDeviceContent = ShareRequestCancellation(
-                requestingDeviceId = credentials.deviceId,
-                requestId = params.requestId
-        )
-        cryptoStore.saveGossipingEvent(Event(
-                type = EventType.ROOM_KEY_REQUEST,
-                content = toDeviceContent.toContent(),
-                senderId = credentials.userId
-        ).also {
-            it.ageLocalTs = clock.epochMillis()
-        })
-
-        params.recipients.forEach { userToDeviceMap ->
-            userToDeviceMap.value.forEach { deviceId ->
-                contentMap.setObject(userToDeviceMap.key, deviceId, toDeviceContent)
-            }
-        }
-
-        try {
-            cryptoStore.updateOutgoingGossipingRequestState(params.requestId, OutgoingGossipingRequestState.CANCELLING)
-            sendToDeviceTask.execute(
-                    SendToDeviceTask.Params(
-                            eventType = EventType.ROOM_KEY_REQUEST,
-                            contentMap = contentMap,
-                            transactionId = txnId
-                    )
-            )
-            cryptoStore.updateOutgoingGossipingRequestState(params.requestId, OutgoingGossipingRequestState.CANCELLED)
-            return Result.success()
-        } catch (throwable: Throwable) {
-            return if (throwable.shouldBeRetried()) {
-                Result.retry()
-            } else {
-                cryptoStore.updateOutgoingGossipingRequestState(params.requestId, OutgoingGossipingRequestState.FAILED_TO_CANCEL)
-                buildErrorResult(params, throwable.localizedMessage ?: "error")
-            }
-        }
-    }
-
-    override fun buildErrorParams(params: Params, message: String): Params {
-        return params.copy(lastFailureMessage = params.lastFailureMessage ?: message)
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoSessionInfoProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoSessionInfoProvider.kt
index 73dfc468d9..b3e9eab988 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoSessionInfoProvider.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/CryptoSessionInfoProvider.kt
@@ -28,7 +28,7 @@ import javax.inject.Inject
 
 /**
  * The crypto module needs some information regarding rooms that are stored
- * in the session DB, this class encapsulate this functionality
+ * in the session DB, this class encapsulate this functionality.
  */
 internal class CryptoSessionInfoProvider @Inject constructor(
         @SessionDatabase private val monarchy: Monarchy
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt
index 8c09da72de..11fa93dbe0 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DefaultCryptoService.kt
@@ -42,12 +42,14 @@ import org.matrix.android.sdk.api.logger.LoggerTag
 import org.matrix.android.sdk.api.session.crypto.CryptoService
 import org.matrix.android.sdk.api.session.crypto.MXCryptoError
 import org.matrix.android.sdk.api.session.crypto.NewSessionListener
+import org.matrix.android.sdk.api.session.crypto.OutgoingKeyRequest
 import org.matrix.android.sdk.api.session.crypto.crosssigning.DeviceTrustLevel
 import org.matrix.android.sdk.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME
 import org.matrix.android.sdk.api.session.crypto.crosssigning.MASTER_KEY_SSSS_NAME
 import org.matrix.android.sdk.api.session.crypto.crosssigning.SELF_SIGNING_KEY_SSSS_NAME
 import org.matrix.android.sdk.api.session.crypto.crosssigning.USER_SIGNING_KEY_SSSS_NAME
 import org.matrix.android.sdk.api.session.crypto.keyshare.GossipingRequestListener
+import org.matrix.android.sdk.api.session.crypto.model.AuditTrail
 import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
 import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo
 import org.matrix.android.sdk.api.session.crypto.model.DevicesListResponse
@@ -57,15 +59,13 @@ import org.matrix.android.sdk.api.session.crypto.model.MXDeviceInfo
 import org.matrix.android.sdk.api.session.crypto.model.MXEncryptEventContentResult
 import org.matrix.android.sdk.api.session.crypto.model.MXEventDecryptionResult
 import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
+import org.matrix.android.sdk.api.session.crypto.model.RoomKeyShareRequest
+import org.matrix.android.sdk.api.session.crypto.model.TrailType
 import org.matrix.android.sdk.api.session.events.model.Content
 import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
 import org.matrix.android.sdk.api.session.events.model.content.RoomKeyContent
 import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
-import org.matrix.android.sdk.api.session.events.model.content.SecretSendEventContent
 import org.matrix.android.sdk.api.session.events.model.toModel
 import org.matrix.android.sdk.api.session.room.model.Membership
 import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility
@@ -76,7 +76,6 @@ import org.matrix.android.sdk.internal.crypto.actions.MegolmSessionDataImporter
 import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction
 import org.matrix.android.sdk.internal.crypto.algorithms.IMXEncrypting
 import org.matrix.android.sdk.internal.crypto.algorithms.IMXGroupEncryption
-import org.matrix.android.sdk.internal.crypto.algorithms.IMXWithHeldExtension
 import org.matrix.android.sdk.internal.crypto.algorithms.megolm.MXMegolmEncryptionFactory
 import org.matrix.android.sdk.internal.crypto.algorithms.olm.MXOlmEncryptionFactory
 import org.matrix.android.sdk.internal.crypto.crosssigning.DefaultCrossSigningService
@@ -91,6 +90,7 @@ import org.matrix.android.sdk.internal.crypto.tasks.GetDevicesTask
 import org.matrix.android.sdk.internal.crypto.tasks.SetDeviceNameTask
 import org.matrix.android.sdk.internal.crypto.tasks.UploadKeysTask
 import org.matrix.android.sdk.internal.crypto.verification.DefaultVerificationService
+import org.matrix.android.sdk.internal.crypto.verification.VerificationMessageProcessor
 import org.matrix.android.sdk.internal.di.DeviceId
 import org.matrix.android.sdk.internal.di.MoshiProvider
 import org.matrix.android.sdk.internal.di.UserId
@@ -156,9 +156,10 @@ internal class DefaultCryptoService @Inject constructor(
 
         private val crossSigningService: DefaultCrossSigningService,
         //
-        private val incomingGossipingRequestManager: IncomingGossipingRequestManager,
+        private val incomingKeyRequestManager: IncomingKeyRequestManager,
+        private val secretShareManager: SecretShareManager,
         //
-        private val outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
+        private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
         // Actions
         private val setDeviceVerificationAction: SetDeviceVerificationAction,
         private val megolmSessionDataImporter: MegolmSessionDataImporter,
@@ -178,6 +179,7 @@ internal class DefaultCryptoService @Inject constructor(
         private val taskExecutor: TaskExecutor,
         private val cryptoCoroutineScope: CoroutineScope,
         private val eventDecryptor: EventDecryptor,
+        private val verificationMessageProcessor: VerificationMessageProcessor,
         private val liveEventManager: Lazy
 ) : CryptoService {
 
@@ -192,7 +194,7 @@ internal class DefaultCryptoService @Inject constructor(
         }
     }
 
-    fun onLiveEvent(roomId: String, event: Event) {
+    fun onLiveEvent(roomId: String, event: Event, isInitialSync: Boolean) {
         // handle state events
         if (event.isStateEvent()) {
             when (event.type) {
@@ -201,9 +203,18 @@ internal class DefaultCryptoService @Inject constructor(
                 EventType.STATE_ROOM_HISTORY_VISIBILITY -> onRoomHistoryVisibilityEvent(roomId, event)
             }
         }
+
+        // handle verification
+        if (!isInitialSync) {
+            if (event.type != null && verificationMessageProcessor.shouldProcess(event.type)) {
+                cryptoCoroutineScope.launch(coroutineDispatchers.dmVerif) {
+                    verificationMessageProcessor.process(event)
+                }
+            }
+        }
     }
 
-    val gossipingBuffer = mutableListOf()
+//    val gossipingBuffer = mutableListOf()
 
     override fun setDeviceName(deviceId: String, deviceName: String, callback: MatrixCallback) {
         setDeviceNameTask
@@ -282,7 +293,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Provides the tracking status
+     * Provides the tracking status.
      *
      * @param userId the user id
      * @return the tracking status
@@ -292,7 +303,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Tell if the MXCrypto is started
+     * Tell if the MXCrypto is started.
      *
      * @return true if the crypto is started
      */
@@ -379,35 +390,17 @@ internal class DefaultCryptoService @Inject constructor(
         // Open the store
         cryptoStore.open()
 
-        runCatching {
-//            if (isInitialSync) {
-//                // refresh the devices list for each known room members
-//                deviceListManager.invalidateAllDeviceLists()
-//                deviceListManager.refreshOutdatedDeviceLists()
-//            } else {
-
-            // Why would we do that? it will be called at end of syn
-            incomingGossipingRequestManager.processReceivedGossipingRequests()
-//            }
-        }.fold(
-                {
-                    isStarting.set(false)
-                    isStarted.set(true)
-                },
-                {
-                    isStarting.set(false)
-                    isStarted.set(false)
-                    Timber.tag(loggerTag.value).e(it, "Start failed")
-                }
-        )
+        isStarting.set(false)
+        isStarted.set(true)
     }
 
     /**
-     * Close the crypto
+     * Close the crypto.
      */
     fun close() = runBlocking(coroutineDispatchers.crypto) {
         cryptoCoroutineScope.coroutineContext.cancelChildren(CancellationException("Closing crypto module"))
-        incomingGossipingRequestManager.close()
+        incomingKeyRequestManager.close()
+        outgoingKeyRequestManager.close()
         olmDevice.release()
         cryptoStore.close()
     }
@@ -428,7 +421,7 @@ internal class DefaultCryptoService @Inject constructor(
     override fun crossSigningService() = crossSigningService
 
     /**
-     * A sync response has been received
+     * A sync response has been received.
      *
      * @param syncResponse the syncResponse
      */
@@ -472,21 +465,34 @@ internal class DefaultCryptoService @Inject constructor(
                     }
 
                     oneTimeKeysUploader.maybeUploadOneTimeKeys()
-                    incomingGossipingRequestManager.processReceivedGossipingRequests()
                 }
-            }
 
-            tryOrNull {
-                gossipingBuffer.toList().let {
-                    cryptoStore.saveGossipingEvents(it)
+                // Process pending key requests
+                try {
+                    if (toDevices.isEmpty()) {
+                        // this is not blocking
+                        outgoingKeyRequestManager.requireProcessAllPendingKeyRequests()
+                    } else {
+                        Timber.tag(loggerTag.value)
+                                .w("Don't process key requests yet as there might be more to_device to catchup")
+                    }
+                } catch (failure: Throwable) {
+                    // just for safety but should not throw
+                    Timber.tag(loggerTag.value).w("failed to process pending request")
+                }
+
+                try {
+                    incomingKeyRequestManager.processIncomingRequests()
+                } catch (failure: Throwable) {
+                    // just for safety but should not throw
+                    Timber.tag(loggerTag.value).w("failed to process incoming room key requests")
                 }
-                gossipingBuffer.clear()
             }
         }
     }
 
     /**
-     * Find a device by curve25519 identity key
+     * Find a device by curve25519 identity key.
      *
      * @param senderKey the curve25519 key to match.
      * @param algorithm the encryption algorithm.
@@ -500,7 +506,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Provides the device information for a user id and a device Id
+     * Provides the device information for a user id and a device Id.
      *
      * @param userId   the user id
      * @param deviceId the device id
@@ -530,7 +536,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Set the devices as known
+     * Set the devices as known.
      *
      * @param devices  the devices. Note that the verified member of the devices in this list will not be updated by this method.
      * @param callback the asynchronous callback
@@ -594,7 +600,7 @@ internal class DefaultCryptoService @Inject constructor(
         // (for now at least. Maybe we should alert the user somehow?)
         val existingAlgorithm = cryptoStore.getRoomAlgorithm(roomId)
 
-        if (existingAlgorithm == algorithm && roomEncryptorsStore.get(roomId) != null) {
+        if (existingAlgorithm == algorithm) {
             // ignore
             Timber.tag(loggerTag.value).e("setEncryptionInRoom() : Ignoring m.room.encryption for same alg ($algorithm) in  $roomId")
             return false
@@ -641,7 +647,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Tells if a room is encrypted with MXCRYPTO_ALGORITHM_MEGOLM
+     * Tells if a room is encrypted with MXCRYPTO_ALGORITHM_MEGOLM.
      *
      * @param roomId the room id
      * @return true if the room is encrypted with algorithm MXCRYPTO_ALGORITHM_MEGOLM
@@ -734,7 +740,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Decrypt an event
+     * Decrypt an event.
      *
      * @param event    the raw event.
      * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack.
@@ -746,7 +752,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Decrypt an event asynchronously
+     * Decrypt an event asynchronously.
      *
      * @param event    the raw event.
      * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack.
@@ -757,7 +763,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Decrypt an event
+     * Decrypt an event.
      *
      * @param event    the raw event.
      * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack.
@@ -778,7 +784,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Handle the 'toDevice' event
+     * Handle the 'toDevice' event.
      *
      * @param event the event
      */
@@ -787,19 +793,25 @@ internal class DefaultCryptoService @Inject constructor(
         cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
             when (event.getClearType()) {
                 EventType.ROOM_KEY, EventType.FORWARDED_ROOM_KEY -> {
-                    gossipingBuffer.add(event)
                     // Keys are imported directly, not waiting for end of sync
                     onRoomKeyEvent(event)
                 }
-                EventType.REQUEST_SECRET,
+                EventType.REQUEST_SECRET                         -> {
+                    secretShareManager.handleSecretRequest(event)
+                }
                 EventType.ROOM_KEY_REQUEST                       -> {
-                    // save audit trail
-                    gossipingBuffer.add(event)
-                    // Requests are stacked, and will be handled one by one at the end of the sync (onSyncComplete)
-                    incomingGossipingRequestManager.onGossipingRequestEvent(event)
+                    event.getClearContent().toModel()?.let { req ->
+                        // We'll always get these because we send room key requests to
+                        // '*' (ie. 'all devices') which includes the sending device,
+                        // so ignore requests from ourself because apart from it being
+                        // very silly, it won't work because an Olm session cannot send
+                        // messages to itself.
+                        if (req.requestingDeviceId != deviceId) { // ignore self requests
+                            event.senderId?.let { incomingKeyRequestManager.addNewIncomingRequest(it, req) }
+                        }
+                    }
                 }
                 EventType.SEND_SECRET                            -> {
-                    gossipingBuffer.add(event)
                     onSecretSendReceived(event)
                 }
                 EventType.ROOM_KEY_WITHHELD                      -> {
@@ -837,50 +849,38 @@ internal class DefaultCryptoService @Inject constructor(
         val withHeldContent = event.getClearContent().toModel() ?: return Unit.also {
             Timber.tag(loggerTag.value).i("Malformed onKeyWithHeldReceived() : missing fields")
         }
-        Timber.tag(loggerTag.value).i("onKeyWithHeldReceived() received from:${event.senderId}, content <$withHeldContent>")
-        val alg = roomDecryptorProvider.getOrCreateRoomDecryptor(withHeldContent.roomId, withHeldContent.algorithm)
-        if (alg is IMXWithHeldExtension) {
-            alg.onRoomKeyWithHeldEvent(withHeldContent)
-        } else {
-            Timber.tag(loggerTag.value).e("onKeyWithHeldReceived() from:${event.senderId}: Unable to handle WithHeldContent for ${withHeldContent.algorithm}")
-            return
+        val senderId = event.senderId ?: return Unit.also {
+            Timber.tag(loggerTag.value).i("Malformed onKeyWithHeldReceived() : missing fields")
         }
+        withHeldContent.sessionId ?: return
+        withHeldContent.algorithm ?: return
+        withHeldContent.roomId ?: return
+        withHeldContent.senderKey ?: return
+        outgoingKeyRequestManager.onRoomKeyWithHeld(
+                sessionId = withHeldContent.sessionId,
+                algorithm = withHeldContent.algorithm,
+                roomId = withHeldContent.roomId,
+                senderKey = withHeldContent.senderKey,
+                fromDevice = withHeldContent.fromDevice,
+                event = Event(
+                        type = EventType.ROOM_KEY_WITHHELD,
+                        senderId = senderId,
+                        content = event.getClearContent()
+                )
+        )
     }
 
-    private fun onSecretSendReceived(event: Event) {
-        Timber.tag(loggerTag.value).i("GOSSIP onSecretSend() from ${event.senderId} : onSecretSendReceived ${event.content?.get("sender_key")}")
-        if (!event.isEncrypted()) {
-            // secret send messages must be encrypted
-            Timber.tag(loggerTag.value).e("GOSSIP onSecretSend() :Received unencrypted secret send event")
-            return
-        }
-
-        // Was that sent by us?
-        if (event.senderId != userId) {
-            Timber.tag(loggerTag.value).e("GOSSIP onSecretSend() : Ignore secret from other user ${event.senderId}")
-            return
-        }
-
-        val secretContent = event.getClearContent().toModel() ?: return
-
-        val existingRequest = cryptoStore
-                .getOutgoingSecretKeyRequests().firstOrNull { it.requestId == secretContent.requestId }
-
-        if (existingRequest == null) {
-            Timber.tag(loggerTag.value).i("GOSSIP onSecretSend() : Ignore secret that was not requested: ${secretContent.requestId}")
-            return
-        }
-
-        if (!handleSDKLevelGossip(existingRequest.secretName, secretContent.secretValue)) {
-            // TODO Ask to application layer?
-            Timber.tag(loggerTag.value).v("onSecretSend() : secret not handled by SDK")
+    private suspend fun onSecretSendReceived(event: Event) {
+        secretShareManager.onSecretSendReceived(event) { secretName, secretValue ->
+            handleSDKLevelGossip(secretName, secretValue)
         }
     }
 
     /**
-     * Returns true if handled by SDK, otherwise should be sent to application layer
+     * Returns true if handled by SDK, otherwise should be sent to application layer.
      */
-    private fun handleSDKLevelGossip(secretName: String?, secretValue: String): Boolean {
+    private fun handleSDKLevelGossip(secretName: String?,
+                                     secretValue: String): Boolean {
         return when (secretName) {
             MASTER_KEY_SSSS_NAME       -> {
                 crossSigningService.onSecretMSKGossip(secretValue)
@@ -984,7 +984,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Export the crypto keys
+     * Export the crypto keys.
      *
      * @param password the password
      * @return the exported keys
@@ -994,7 +994,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Export the crypto keys
+     * Export the crypto keys.
      *
      * @param password         the password
      * @param anIterationCount the encryption iteration count (0 means no encryption)
@@ -1013,7 +1013,7 @@ internal class DefaultCryptoService @Inject constructor(
     }
 
     /**
-     * Import the room keys
+     * Import the room keys.
      *
      * @param roomKeysAsArray  the room keys as array.
      * @param password         the password
@@ -1095,6 +1095,12 @@ internal class DefaultCryptoService @Inject constructor(
         cryptoStore.setGlobalBlacklistUnverifiedDevices(block)
     }
 
+    override fun enableKeyGossiping(enable: Boolean) {
+        cryptoStore.enableKeyGossiping(enable)
+    }
+
+    override fun isKeyGossipingEnabled() = cryptoStore.isKeyGossipingEnabled()
+
     /**
      * Tells whether the client should ever send encrypted messages to unverified devices.
      * The default value is false.
@@ -1158,52 +1164,17 @@ internal class DefaultCryptoService @Inject constructor(
         setRoomBlacklistUnverifiedDevices(roomId, false)
     }
 
-// TODO Check if this method is still necessary
-    /**
-     * Cancel any earlier room key request
-     *
-     * @param requestBody requestBody
-     */
-    override fun cancelRoomKeyRequest(requestBody: RoomKeyRequestBody) {
-        outgoingGossipingRequestManager.cancelRoomKeyRequest(requestBody)
-    }
-
     /**
      * Re request the encryption keys required to decrypt an event.
      *
      * @param event the event to decrypt again.
      */
     override fun reRequestRoomKeyForEvent(event: Event) {
-        val wireContent = event.content.toModel() ?: return Unit.also {
-            Timber.tag(loggerTag.value).e("reRequestRoomKeyForEvent Failed to re-request key, null content")
-        }
-
-        val requestBody = RoomKeyRequestBody(
-                algorithm = wireContent.algorithm,
-                roomId = event.roomId,
-                senderKey = wireContent.senderKey,
-                sessionId = wireContent.sessionId
-        )
-
-        outgoingGossipingRequestManager.resendRoomKeyRequest(requestBody)
+        outgoingKeyRequestManager.requestKeyForEvent(event, true)
     }
 
     override fun requestRoomKeyForEvent(event: Event) {
-        val wireContent = event.content.toModel() ?: return Unit.also {
-            Timber.tag(loggerTag.value).e("requestRoomKeyForEvent Failed to request key, null content eventId: ${event.eventId}")
-        }
-
-        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-//            if (!isStarted()) {
-//                Timber.v("## CRYPTO | requestRoomKeyForEvent() : wait after e2e init")
-//                internalStart(false)
-//            }
-            roomDecryptorProvider
-                    .getOrCreateRoomDecryptor(event.roomId, wireContent.algorithm)
-                    ?.requestKeysForEvent(event, false) ?: run {
-                Timber.tag(loggerTag.value).v("requestRoomKeyForEvent() : No room decryptor for roomId:${event.roomId} algorithm:${wireContent.algorithm}")
-            }
-        }
+        outgoingKeyRequestManager.requestKeyForEvent(event, false)
     }
 
     /**
@@ -1212,7 +1183,8 @@ internal class DefaultCryptoService @Inject constructor(
      * @param listener listener
      */
     override fun addRoomKeysRequestListener(listener: GossipingRequestListener) {
-        incomingGossipingRequestManager.addRoomKeysRequestListener(listener)
+        incomingKeyRequestManager.addRoomKeysRequestListener(listener)
+        secretShareManager.addListener(listener)
     }
 
     /**
@@ -1221,44 +1193,12 @@ internal class DefaultCryptoService @Inject constructor(
      * @param listener listener
      */
     override fun removeRoomKeysRequestListener(listener: GossipingRequestListener) {
-        incomingGossipingRequestManager.removeRoomKeysRequestListener(listener)
+        incomingKeyRequestManager.removeRoomKeysRequestListener(listener)
+        secretShareManager.removeListener(listener)
     }
 
-//    private fun markOlmSessionForUnwedging(senderId: String, deviceInfo: CryptoDeviceInfo) {
-//        val deviceKey = deviceInfo.identityKey()
-//
-//        val lastForcedDate = lastNewSessionForcedDates.getObject(senderId, deviceKey) ?: 0
-//        val now = clock.epochMillis()
-//        if (now - lastForcedDate < CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS) {
-//            Timber.d("## CRYPTO | markOlmSessionForUnwedging: New session already forced with device at $lastForcedDate. Not forcing another")
-//            return
-//        }
-//
-//        Timber.d("## CRYPTO | markOlmSessionForUnwedging from $senderId:${deviceInfo.deviceId}")
-//        lastNewSessionForcedDates.setObject(senderId, deviceKey, now)
-//
-//        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-//            ensureOlmSessionsForDevicesAction.handle(mapOf(senderId to listOf(deviceInfo)), force = true)
-//
-//            // Now send a blank message on that session so the other side knows about it.
-//            // (The keyshare request is sent in the clear so that won't do)
-//            // We send this first such that, as long as the toDevice messages arrive in the
-//            // same order we sent them, the other end will get this first, set up the new session,
-//            // then get the keyshare request and send the key over this new session (because it
-//            // is the session it has most recently received a message on).
-//            val payloadJson = mapOf("type" to EventType.DUMMY)
-//
-//            val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo))
-//            val sendToDeviceMap = MXUsersDevicesMap()
-//            sendToDeviceMap.setObject(senderId, deviceInfo.deviceId, encodedPayload)
-//            Timber.v("## CRYPTO | markOlmSessionForUnwedging() : sending to $senderId:${deviceInfo.deviceId}")
-//            val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap)
-//            sendToDeviceTask.execute(sendToDeviceParams)
-//        }
-//    }
-
     /**
-     * Provides the list of unknown devices
+     * Provides the list of unknown devices.
      *
      * @param devicesInRoom the devices map
      * @return the unknown devices map
@@ -1302,27 +1242,41 @@ internal class DefaultCryptoService @Inject constructor(
         return "DefaultCryptoService of $userId ($deviceId)"
     }
 
-    override fun getOutgoingRoomKeyRequests(): List {
+    override fun getOutgoingRoomKeyRequests(): List {
         return cryptoStore.getOutgoingRoomKeyRequests()
     }
 
-    override fun getOutgoingRoomKeyRequestsPaged(): LiveData> {
+    override fun getOutgoingRoomKeyRequestsPaged(): LiveData> {
         return cryptoStore.getOutgoingRoomKeyRequestsPaged()
     }
 
-    override fun getIncomingRoomKeyRequestsPaged(): LiveData> {
-        return cryptoStore.getIncomingRoomKeyRequestsPaged()
-    }
-
     override fun getIncomingRoomKeyRequests(): List {
-        return cryptoStore.getIncomingRoomKeyRequests()
+        return cryptoStore.getGossipingEvents()
+                .mapNotNull {
+                    IncomingRoomKeyRequest.fromEvent(it)
+                }
     }
 
-    override fun getGossipingEventsTrail(): LiveData> {
+    override fun getIncomingRoomKeyRequestsPaged(): LiveData> {
+        return cryptoStore.getGossipingEventsTrail(TrailType.IncomingKeyRequest) {
+            IncomingRoomKeyRequest.fromEvent(it)
+                    ?: IncomingRoomKeyRequest(localCreationTimestamp = 0L)
+        }
+    }
+
+    /**
+     * If you registered a `GossipingRequestListener`, you will be notified of key request
+     * that was not accepted by the SDK. You can call back this manually to accept anyhow.
+     */
+    override suspend fun manuallyAcceptRoomKeyRequest(request: IncomingRoomKeyRequest) {
+        incomingKeyRequestManager.manuallyAcceptRoomKeyRequest(request)
+    }
+
+    override fun getGossipingEventsTrail(): LiveData> {
         return cryptoStore.getGossipingEventsTrail()
     }
 
-    override fun getGossipingEvents(): List {
+    override fun getGossipingEvents(): List {
         return cryptoStore.getGossipingEvents()
     }
 
@@ -1346,8 +1300,8 @@ internal class DefaultCryptoService @Inject constructor(
                 loadRoomMembersTask.execute(LoadRoomMembersTask.Params(roomId))
             } catch (failure: Throwable) {
                 Timber.tag(loggerTag.value).e("prepareToEncrypt() : Failed to load room members")
-                callback.onFailure(failure)
-                return@launch
+                // we probably shouldn't block sending on that (but questionable)
+                // but some members won't be able to decrypt
             }
 
             val userIds = getRoomUserIds(roomId)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt
index 535999373b..cd4e2a6d52 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/DeviceListManager.kt
@@ -102,7 +102,7 @@ internal class DeviceListManager @Inject constructor(
     }
 
     /**
-     * Tells if the key downloads should be tried
+     * Tells if the key downloads should be tried.
      *
      * @param userId the userId
      * @return true if the keys download can be retrieved
@@ -124,7 +124,7 @@ internal class DeviceListManager @Inject constructor(
     }
 
     /**
-     * Clear the unavailable server lists
+     * Clear the unavailable server lists.
      */
     private fun clearUnavailableServersList() {
         synchronized(notReadyToRetryHS) {
@@ -167,7 +167,7 @@ internal class DeviceListManager @Inject constructor(
     }
 
     /**
-     * Update the devices list statuses
+     * Update the devices list statuses.
      *
      * @param changed the user ids list which have new devices
      * @param left    the user ids list which left a room
@@ -203,15 +203,14 @@ internal class DeviceListManager @Inject constructor(
     }
 
     /**
-     * This will flag each user whose devices we are tracking as in need of an
-     * + update
+     * This will flag each user whose devices we are tracking as in need of an update.
      */
     fun invalidateAllDeviceLists() {
         handleDeviceListsChanges(cryptoStore.getDeviceTrackingStatuses().keys, emptyList())
     }
 
     /**
-     * The keys download failed
+     * The keys download failed.
      *
      * @param userIds the user ids list
      */
@@ -315,10 +314,19 @@ internal class DeviceListManager @Inject constructor(
         } else {
             Timber.v("## CRYPTO | downloadKeys() : starts")
             val t0 = clock.epochMillis()
-            val result = doKeyDownloadForUsers(downloadUsers)
-            Timber.v("## CRYPTO | downloadKeys() : doKeyDownloadForUsers succeeds after ${clock.epochMillis() - t0} ms")
-            result.also {
-                it.addEntriesFromMap(stored)
+            try {
+                val result = doKeyDownloadForUsers(downloadUsers)
+                Timber.v("## CRYPTO | downloadKeys() : doKeyDownloadForUsers succeeds after ${clock.epochMillis() - t0} ms")
+                result.also {
+                    it.addEntriesFromMap(stored)
+                }
+            } catch (failure: Throwable) {
+                Timber.w(failure, "## CRYPTO | downloadKeys() : doKeyDownloadForUsers failed after ${clock.epochMillis() - t0} ms")
+                if (forceDownload) {
+                    throw failure
+                } else {
+                    stored
+                }
             }
         }
     }
@@ -543,7 +551,7 @@ internal class DeviceListManager @Inject constructor(
     companion object {
 
         /**
-         * State transition diagram for DeviceList.deviceTrackingStatus
+         * State transition diagram for DeviceList.deviceTrackingStatus.
          * 
          *
          *                                   |
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/EventDecryptor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/EventDecryptor.kt
index a094189645..d6f881211c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/EventDecryptor.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/EventDecryptor.kt
@@ -70,7 +70,7 @@ internal class EventDecryptor @Inject constructor(
     private val wedgedDevices = mutableListOf()
 
     /**
-     * Decrypt an event
+     * Decrypt an event.
      *
      * @param event    the raw event.
      * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack.
@@ -82,7 +82,7 @@ internal class EventDecryptor @Inject constructor(
     }
 
     /**
-     * Decrypt an event asynchronously
+     * Decrypt an event asynchronously.
      *
      * @param event    the raw event.
      * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack.
@@ -98,7 +98,7 @@ internal class EventDecryptor @Inject constructor(
     }
 
     /**
-     * Decrypt an event
+     * Decrypt an event.
      *
      * @param event    the raw event.
      * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack.
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/GossipingWorkManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/GossipingWorkManager.kt
deleted file mode 100644
index a2c85e5ceb..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/GossipingWorkManager.kt
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto
-
-import androidx.work.BackoffPolicy
-import androidx.work.Data
-import androidx.work.ExistingWorkPolicy
-import androidx.work.ListenableWorker
-import androidx.work.OneTimeWorkRequest
-import org.matrix.android.sdk.api.util.Cancelable
-import org.matrix.android.sdk.internal.di.WorkManagerProvider
-import org.matrix.android.sdk.internal.session.SessionScope
-import org.matrix.android.sdk.internal.util.CancelableWork
-import org.matrix.android.sdk.internal.worker.startChain
-import java.util.UUID
-import java.util.concurrent.TimeUnit
-import javax.inject.Inject
-
-@SessionScope
-internal class GossipingWorkManager @Inject constructor(
-        private val workManagerProvider: WorkManagerProvider
-) {
-
-    inline fun  createWork(data: Data, startChain: Boolean): OneTimeWorkRequest {
-        return workManagerProvider.matrixOneTimeWorkRequestBuilder()
-                .setConstraints(WorkManagerProvider.workConstraints)
-                .startChain(startChain)
-                .setInputData(data)
-                .setBackoffCriteria(BackoffPolicy.LINEAR, WorkManagerProvider.BACKOFF_DELAY_MILLIS, TimeUnit.MILLISECONDS)
-                .build()
-    }
-
-    // Prevent sending queue to stay broken after app restart
-    // The unique queue id will stay the same as long as this object is instantiated
-    private val queueSuffixApp = UUID.randomUUID()
-
-    fun postWork(workRequest: OneTimeWorkRequest, policy: ExistingWorkPolicy = ExistingWorkPolicy.APPEND): Cancelable {
-        workManagerProvider.workManager
-                .beginUniqueWork(this::class.java.name + "_$queueSuffixApp", policy, workRequest)
-                .enqueue()
-
-        return CancelableWork(workManagerProvider.workManager, workRequest.id)
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingGossipingRequestManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingGossipingRequestManager.kt
deleted file mode 100644
index 1612caba9f..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingGossipingRequestManager.kt
+++ /dev/null
@@ -1,475 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto
-
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.launch
-import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
-import org.matrix.android.sdk.api.auth.data.Credentials
-import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
-import org.matrix.android.sdk.api.crypto.MXCryptoConfig
-import org.matrix.android.sdk.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME
-import org.matrix.android.sdk.api.session.crypto.crosssigning.MASTER_KEY_SSSS_NAME
-import org.matrix.android.sdk.api.session.crypto.crosssigning.SELF_SIGNING_KEY_SSSS_NAME
-import org.matrix.android.sdk.api.session.crypto.crosssigning.USER_SIGNING_KEY_SSSS_NAME
-import org.matrix.android.sdk.api.session.crypto.keysbackup.extractCurveKeyFromRecoveryKey
-import org.matrix.android.sdk.api.session.crypto.keyshare.GossipingRequestListener
-import org.matrix.android.sdk.api.session.crypto.model.GossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.GossipingToDeviceObject
-import org.matrix.android.sdk.api.session.crypto.model.IncomingRequestCancellation
-import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.IncomingSecretShareRequest
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
-import org.matrix.android.sdk.api.session.events.model.Event
-import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.api.session.events.model.toModel
-import org.matrix.android.sdk.api.util.toBase64NoPadding
-import org.matrix.android.sdk.internal.crypto.algorithms.IMXGroupEncryption
-import org.matrix.android.sdk.internal.crypto.model.rest.GossipingDefaultContent
-import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
-import org.matrix.android.sdk.internal.crypto.tasks.createUniqueTxnId
-import org.matrix.android.sdk.internal.di.SessionId
-import org.matrix.android.sdk.internal.session.SessionScope
-import org.matrix.android.sdk.internal.util.time.Clock
-import org.matrix.android.sdk.internal.worker.WorkerParamsFactory
-import timber.log.Timber
-import java.util.concurrent.Executors
-import javax.inject.Inject
-
-@SessionScope
-internal class IncomingGossipingRequestManager @Inject constructor(
-        @SessionId private val sessionId: String,
-        private val credentials: Credentials,
-        private val cryptoStore: IMXCryptoStore,
-        private val cryptoConfig: MXCryptoConfig,
-        private val gossipingWorkManager: GossipingWorkManager,
-        private val roomEncryptorsStore: RoomEncryptorsStore,
-        private val roomDecryptorProvider: RoomDecryptorProvider,
-        private val coroutineDispatchers: MatrixCoroutineDispatchers,
-        private val cryptoCoroutineScope: CoroutineScope,
-        private val clock: Clock,
-) {
-
-    private val executor = Executors.newSingleThreadExecutor()
-
-    // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations
-    // we received in the current sync.
-    private val receivedGossipingRequests = ArrayList()
-    private val receivedRequestCancellations = ArrayList()
-
-    // the listeners
-    private val gossipingRequestListeners: MutableSet = HashSet()
-
-    init {
-        receivedGossipingRequests.addAll(cryptoStore.getPendingIncomingGossipingRequests())
-    }
-
-    fun close() {
-        executor.shutdownNow()
-    }
-
-    // Recently verified devices (map of deviceId and timestamp)
-    private val recentlyVerifiedDevices = HashMap()
-
-    /**
-     * Called when a session has been verified.
-     * This information can be used by the manager to decide whether or not to fullfil gossiping requests
-     */
-    fun onVerificationCompleteForDevice(deviceId: String) {
-        // For now we just keep an in memory cache
-        synchronized(recentlyVerifiedDevices) {
-            recentlyVerifiedDevices[deviceId] = clock.epochMillis()
-        }
-    }
-
-    private fun hasBeenVerifiedLessThanFiveMinutesFromNow(deviceId: String): Boolean {
-        val verifTimestamp: Long?
-        synchronized(recentlyVerifiedDevices) {
-            verifTimestamp = recentlyVerifiedDevices[deviceId]
-        }
-        if (verifTimestamp == null) return false
-
-        val age = clock.epochMillis() - verifTimestamp
-
-        return age < FIVE_MINUTES_IN_MILLIS
-    }
-
-    /**
-     * Called when we get an m.room_key_request event
-     * It must be called on CryptoThread
-     *
-     * @param event the announcement event.
-     */
-    fun onGossipingRequestEvent(event: Event) {
-        val roomKeyShare = event.getClearContent().toModel()
-        Timber.i("## CRYPTO | GOSSIP onGossipingRequestEvent received type ${event.type} from user:${event.senderId}, content:$roomKeyShare")
-        // val ageLocalTs = event.unsignedData?.age?.let { clock.epochMillis() - it }
-        when (roomKeyShare?.action) {
-            GossipingToDeviceObject.ACTION_SHARE_REQUEST      -> {
-                if (event.getClearType() == EventType.REQUEST_SECRET) {
-                    IncomingSecretShareRequest.fromEvent(event, clock.epochMillis())?.let {
-                        if (event.senderId == credentials.userId && it.deviceId == credentials.deviceId) {
-                            // ignore, it was sent by me as *
-                            Timber.v("## GOSSIP onGossipingRequestEvent type ${event.type} ignore remote echo")
-                        } else {
-//                            // save in DB
-//                            cryptoStore.storeIncomingGossipingRequest(it, ageLocalTs)
-                            receivedGossipingRequests.add(it)
-                        }
-                    }
-                } else if (event.getClearType() == EventType.ROOM_KEY_REQUEST) {
-                    IncomingRoomKeyRequest.fromEvent(event, clock.epochMillis())?.let {
-                        if (event.senderId == credentials.userId && it.deviceId == credentials.deviceId) {
-                            // ignore, it was sent by me as *
-                            Timber.v("## GOSSIP onGossipingRequestEvent type ${event.type} ignore remote echo")
-                        } else {
-//                            cryptoStore.storeIncomingGossipingRequest(it, ageLocalTs)
-                            receivedGossipingRequests.add(it)
-                        }
-                    }
-                }
-            }
-            GossipingToDeviceObject.ACTION_SHARE_CANCELLATION -> {
-                IncomingRequestCancellation.fromEvent(event, clock.epochMillis())?.let {
-                    receivedRequestCancellations.add(it)
-                }
-            }
-            else                                              -> {
-                Timber.e("## GOSSIP onGossipingRequestEvent() : unsupported action ${roomKeyShare?.action}")
-            }
-        }
-    }
-
-    /**
-     * Process any m.room_key_request or m.secret.request events which were queued up during the
-     * current sync.
-     * It must be called on CryptoThread
-     */
-    fun processReceivedGossipingRequests() {
-        val roomKeyRequestsToProcess = receivedGossipingRequests.toList()
-        receivedGossipingRequests.clear()
-
-        Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : ${roomKeyRequestsToProcess.size} request to process")
-
-        var receivedRequestCancellations: List? = null
-
-        synchronized(this.receivedRequestCancellations) {
-            if (this.receivedRequestCancellations.isNotEmpty()) {
-                receivedRequestCancellations = this.receivedRequestCancellations.toList()
-                this.receivedRequestCancellations.clear()
-            }
-        }
-
-        executor.execute {
-            cryptoStore.storeIncomingGossipingRequests(roomKeyRequestsToProcess)
-            for (request in roomKeyRequestsToProcess) {
-                if (request is IncomingRoomKeyRequest) {
-                    processIncomingRoomKeyRequest(request)
-                } else if (request is IncomingSecretShareRequest) {
-                    processIncomingSecretShareRequest(request)
-                }
-            }
-
-            receivedRequestCancellations?.forEach { request ->
-                Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : m.room_key_request cancellation $request")
-                // we should probably only notify the app of cancellations we told it
-                // about, but we don't currently have a record of that, so we just pass
-                // everything through.
-                if (request.userId == credentials.userId && request.deviceId == credentials.deviceId) {
-                    // ignore remote echo
-                    return@forEach
-                }
-                val matchingIncoming = cryptoStore.getIncomingRoomKeyRequest(request.userId ?: "", request.deviceId ?: "", request.requestId ?: "")
-                if (matchingIncoming == null) {
-                    // ignore that?
-                    return@forEach
-                } else {
-                    // If it was accepted from this device, keep the information, do not mark as cancelled
-                    if (matchingIncoming.state != GossipingRequestState.ACCEPTED) {
-                        onRoomKeyRequestCancellation(request)
-                        cryptoStore.updateGossipingRequestState(request, GossipingRequestState.CANCELLED_BY_REQUESTER)
-                    }
-                }
-            }
-        }
-    }
-
-    private fun processIncomingRoomKeyRequest(request: IncomingRoomKeyRequest) {
-        val userId = request.userId ?: return
-        val deviceId = request.deviceId ?: return
-        val body = request.requestBody ?: return
-        val roomId = body.roomId ?: return
-        val alg = body.algorithm ?: return
-
-        Timber.v("## CRYPTO | GOSSIP processIncomingRoomKeyRequest from $userId:$deviceId for $roomId / ${body.sessionId} id ${request.requestId}")
-        if (credentials.userId != userId) {
-            handleKeyRequestFromOtherUser(body, request, alg, roomId, userId, deviceId)
-            return
-        }
-        // TODO: should we queue up requests we don't yet have keys for, in case they turn up later?
-        // if we don't have a decryptor for this room/alg, we don't have
-        // the keys for the requested events, and can drop the requests.
-        val decryptor = roomDecryptorProvider.getRoomDecryptor(roomId, alg)
-        if (null == decryptor) {
-            Timber.w("## CRYPTO | GOSSIP processReceivedGossipingRequests() : room key request for unknown $alg in room $roomId")
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            return
-        }
-        if (!decryptor.hasKeysForKeyRequest(request)) {
-            Timber.w("## CRYPTO | GOSSIP processReceivedGossipingRequests() : room key request for unknown session ${body.sessionId!!}")
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            return
-        }
-
-        if (credentials.deviceId == deviceId && credentials.userId == userId) {
-            Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : oneself device - ignored")
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            return
-        }
-        request.share = Runnable {
-            decryptor.shareKeysWithDevice(request)
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.ACCEPTED)
-        }
-        request.ignore = Runnable {
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-        }
-        // if the device is verified already, share the keys
-        val device = cryptoStore.getUserDevice(userId, deviceId)
-        if (device != null) {
-            if (device.isVerified) {
-                Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : device is already verified: sharing keys")
-                request.share?.run()
-                return
-            }
-
-            if (device.isBlocked) {
-                Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : device is blocked -> ignored")
-                cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-                return
-            }
-        }
-
-        // As per config we automatically discard untrusted devices request
-        if (cryptoConfig.discardRoomKeyRequestsFromUntrustedDevices) {
-            Timber.v("## CRYPTO | processReceivedGossipingRequests() : discardRoomKeyRequestsFromUntrustedDevices")
-            // At this point the device is unknown, we don't want to bother user with that
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            return
-        }
-
-        // Pass to application layer to decide what to do
-        onRoomKeyRequest(request)
-    }
-
-    private fun handleKeyRequestFromOtherUser(body: RoomKeyRequestBody,
-                                              request: IncomingRoomKeyRequest,
-                                              alg: String,
-                                              roomId: String,
-                                              userId: String,
-                                              deviceId: String) {
-        Timber.w("## CRYPTO | GOSSIP processReceivedGossipingRequests() : room key request from other user")
-        val senderKey = body.senderKey ?: return Unit
-                .also { Timber.w("missing senderKey") }
-                .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) }
-        val sessionId = body.sessionId ?: return Unit
-                .also { Timber.w("missing sessionId") }
-                .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) }
-
-        if (alg != MXCRYPTO_ALGORITHM_MEGOLM) {
-            return Unit
-                    .also { Timber.w("Only megolm is accepted here") }
-                    .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) }
-        }
-
-        val roomEncryptor = roomEncryptorsStore.get(roomId) ?: return Unit
-                .also { Timber.w("no room Encryptor") }
-                .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) }
-
-        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-            if (roomEncryptor is IMXGroupEncryption) {
-                val isSuccess = roomEncryptor.reshareKey(sessionId, userId, deviceId, senderKey)
-
-                if (isSuccess) {
-                    cryptoStore.updateGossipingRequestState(request, GossipingRequestState.ACCEPTED)
-                } else {
-                    cryptoStore.updateGossipingRequestState(request, GossipingRequestState.UNABLE_TO_PROCESS)
-                }
-            } else {
-                Timber.e("## CRYPTO | handleKeyRequestFromOtherUser() from:$userId: Unable to handle IMXGroupEncryption.reshareKey for $alg")
-            }
-        }
-        cryptoStore.updateGossipingRequestState(request, GossipingRequestState.RE_REQUESTED)
-    }
-
-    private fun processIncomingSecretShareRequest(request: IncomingSecretShareRequest) {
-        val secretName = request.secretName ?: return Unit.also {
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Missing secret name")
-        }
-
-        val userId = request.userId
-        if (userId == null || credentials.userId != userId) {
-            Timber.e("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Ignoring secret share request from other users")
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            return
-        }
-
-        val deviceId = request.deviceId
-                ?: return Unit.also {
-                    Timber.e("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Malformed request, no ")
-                    cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-                }
-
-        val device = cryptoStore.getUserDevice(userId, deviceId)
-                ?: return Unit.also {
-                    Timber.e("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Received secret share request from unknown device ${request.deviceId}")
-                    cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-                }
-
-        if (!device.isVerified || device.isBlocked) {
-            Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Ignoring secret share request from untrusted/blocked session $device")
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            return
-        }
-
-        val isDeviceLocallyVerified = cryptoStore.getUserDevice(userId, deviceId)?.trustLevel?.isLocallyVerified()
-
-        when (secretName) {
-            MASTER_KEY_SSSS_NAME       -> cryptoStore.getCrossSigningPrivateKeys()?.master
-            SELF_SIGNING_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.selfSigned
-            USER_SIGNING_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.user
-            KEYBACKUP_SECRET_SSSS_NAME -> cryptoStore.getKeyBackupRecoveryKeyInfo()?.recoveryKey
-                    ?.let {
-                        extractCurveKeyFromRecoveryKey(it)?.toBase64NoPadding()
-                    }
-            else                       -> null
-        }?.let { secretValue ->
-            Timber.i("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Sharing secret $secretName with $device locally trusted")
-            if (isDeviceLocallyVerified == true && hasBeenVerifiedLessThanFiveMinutesFromNow(deviceId)) {
-                val params = SendGossipWorker.Params(
-                        sessionId = sessionId,
-                        secretValue = secretValue,
-                        requestUserId = request.userId,
-                        requestDeviceId = request.deviceId,
-                        requestId = request.requestId,
-                        txnId = createUniqueTxnId()
-                )
-
-                cryptoStore.updateGossipingRequestState(request, GossipingRequestState.ACCEPTING)
-                val workRequest = gossipingWorkManager.createWork(WorkerParamsFactory.toData(params), true)
-                gossipingWorkManager.postWork(workRequest)
-            } else {
-                Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Can't share secret $secretName with $device, verification too old")
-                cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-            }
-            return
-        }
-
-        Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : $secretName unknown at SDK level, asking to app layer")
-
-        request.ignore = Runnable {
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED)
-        }
-
-        request.share = { secretValue ->
-            val params = SendGossipWorker.Params(
-                    sessionId = userId,
-                    secretValue = secretValue,
-                    requestUserId = request.userId,
-                    requestDeviceId = request.deviceId,
-                    requestId = request.requestId,
-                    txnId = createUniqueTxnId()
-            )
-
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.ACCEPTING)
-            val workRequest = gossipingWorkManager.createWork(WorkerParamsFactory.toData(params), true)
-            gossipingWorkManager.postWork(workRequest)
-            cryptoStore.updateGossipingRequestState(request, GossipingRequestState.ACCEPTED)
-        }
-
-        onShareRequest(request)
-    }
-
-    /**
-     * Dispatch onRoomKeyRequest
-     *
-     * @param request the request
-     */
-    private fun onRoomKeyRequest(request: IncomingRoomKeyRequest) {
-        synchronized(gossipingRequestListeners) {
-            for (listener in gossipingRequestListeners) {
-                try {
-                    listener.onRoomKeyRequest(request)
-                } catch (e: Exception) {
-                    Timber.e(e, "## CRYPTO | onRoomKeyRequest() failed")
-                }
-            }
-        }
-    }
-
-    /**
-     * Ask for a value to the listeners, and take the first one
-     */
-    private fun onShareRequest(request: IncomingSecretShareRequest) {
-        synchronized(gossipingRequestListeners) {
-            for (listener in gossipingRequestListeners) {
-                try {
-                    if (listener.onSecretShareRequest(request)) {
-                        return
-                    }
-                } catch (e: Exception) {
-                    Timber.e(e, "## CRYPTO | GOSSIP onRoomKeyRequest() failed")
-                }
-            }
-        }
-        // Not handled, ignore
-        request.ignore?.run()
-    }
-
-    /**
-     * A room key request cancellation has been received.
-     *
-     * @param request the cancellation request
-     */
-    private fun onRoomKeyRequestCancellation(request: IncomingRequestCancellation) {
-        synchronized(gossipingRequestListeners) {
-            for (listener in gossipingRequestListeners) {
-                try {
-                    listener.onRoomKeyRequestCancellation(request)
-                } catch (e: Exception) {
-                    Timber.e(e, "## CRYPTO | GOSSIP onRoomKeyRequestCancellation() failed")
-                }
-            }
-        }
-    }
-
-    fun addRoomKeysRequestListener(listener: GossipingRequestListener) {
-        synchronized(gossipingRequestListeners) {
-            gossipingRequestListeners.add(listener)
-        }
-    }
-
-    fun removeRoomKeysRequestListener(listener: GossipingRequestListener) {
-        synchronized(gossipingRequestListeners) {
-            gossipingRequestListeners.remove(listener)
-        }
-    }
-
-    companion object {
-        private const val FIVE_MINUTES_IN_MILLIS = 5 * 60 * 1000
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingKeyRequestManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingKeyRequestManager.kt
new file mode 100644
index 0000000000..13f2fb861a
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingKeyRequestManager.kt
@@ -0,0 +1,463 @@
+/*
+ * Copyright 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.asCoroutineDispatcher
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
+import org.matrix.android.sdk.api.auth.data.Credentials
+import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
+import org.matrix.android.sdk.api.crypto.MXCryptoConfig
+import org.matrix.android.sdk.api.extensions.tryOrNull
+import org.matrix.android.sdk.api.logger.LoggerTag
+import org.matrix.android.sdk.api.session.crypto.keyshare.GossipingRequestListener
+import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
+import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
+import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
+import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
+import org.matrix.android.sdk.api.session.crypto.model.RoomKeyShareRequest
+import org.matrix.android.sdk.api.session.events.model.EventType
+import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
+import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode
+import org.matrix.android.sdk.internal.crypto.actions.EnsureOlmSessionsForDevicesAction
+import org.matrix.android.sdk.internal.crypto.actions.MessageEncrypter
+import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
+import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
+import org.matrix.android.sdk.internal.session.SessionScope
+import org.matrix.android.sdk.internal.task.SemaphoreCoroutineSequencer
+import org.matrix.android.sdk.internal.util.time.Clock
+import timber.log.Timber
+import java.util.concurrent.Executors
+import javax.inject.Inject
+import kotlin.system.measureTimeMillis
+
+private val loggerTag = LoggerTag("IncomingKeyRequestManager", LoggerTag.CRYPTO)
+
+@SessionScope
+internal class IncomingKeyRequestManager @Inject constructor(
+        private val credentials: Credentials,
+        private val cryptoStore: IMXCryptoStore,
+        private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction,
+        private val olmDevice: MXOlmDevice,
+        private val cryptoConfig: MXCryptoConfig,
+        private val messageEncrypter: MessageEncrypter,
+        private val coroutineDispatchers: MatrixCoroutineDispatchers,
+        private val sendToDeviceTask: SendToDeviceTask,
+        private val clock: Clock,
+) {
+
+    private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
+    private val outgoingRequestScope = CoroutineScope(SupervisorJob() + dispatcher)
+    val sequencer = SemaphoreCoroutineSequencer()
+
+    private val incomingRequestBuffer = mutableListOf()
+
+    // the listeners
+    private val gossipingRequestListeners: MutableSet = HashSet()
+
+    enum class MegolmRequestAction {
+        Request, Cancel
+    }
+
+    data class ValidMegolmRequestBody(
+            val requestId: String,
+            val requestingUserId: String,
+            val requestingDeviceId: String,
+            val roomId: String,
+            val senderKey: String,
+            val sessionId: String,
+            val action: MegolmRequestAction
+    ) {
+        fun shortDbgString() = "Request from $requestingUserId|$requestingDeviceId for session $sessionId in room $roomId"
+    }
+
+    private fun RoomKeyShareRequest.toValidMegolmRequest(senderId: String): ValidMegolmRequestBody? {
+        val deviceId = requestingDeviceId ?: return null
+        val body = body ?: return null
+        val roomId = body.roomId ?: return null
+        val sessionId = body.sessionId ?: return null
+        val senderKey = body.senderKey ?: return null
+        val requestId = this.requestId ?: return null
+        if (body.algorithm != MXCRYPTO_ALGORITHM_MEGOLM) return null
+        val action = when (this.action) {
+            "request" -> MegolmRequestAction.Request
+            "request_cancellation" -> MegolmRequestAction.Cancel
+            else -> null
+        } ?: return null
+        return ValidMegolmRequestBody(
+                requestId = requestId,
+                requestingUserId = senderId,
+                requestingDeviceId = deviceId,
+                roomId = roomId,
+                senderKey = senderKey,
+                sessionId = sessionId,
+                action = action
+        )
+    }
+
+    fun addNewIncomingRequest(senderId: String, request: RoomKeyShareRequest) {
+        if (!cryptoStore.isKeyGossipingEnabled()) {
+            Timber.tag(loggerTag.value)
+                    .i("Ignore incoming key request as per crypto config in room ${request.body?.roomId}")
+            return
+        }
+        outgoingRequestScope.launch {
+            // It is important to handle requests in order
+            sequencer.post {
+                val validMegolmRequest = request.toValidMegolmRequest(senderId) ?: return@post Unit.also {
+                    Timber.tag(loggerTag.value).w("Received key request for unknown algorithm ${request.body?.algorithm}")
+                }
+
+                // is there already one like that?
+                val existing = incomingRequestBuffer.firstOrNull { it == validMegolmRequest }
+                if (existing == null) {
+                    when (validMegolmRequest.action) {
+                        MegolmRequestAction.Request -> {
+                            // just add to the buffer
+                            incomingRequestBuffer.add(validMegolmRequest)
+                        }
+                        MegolmRequestAction.Cancel  -> {
+                            // ignore, we can't cancel as it's not known (probably already processed)
+                            // still notify app layer if it was passed up previously
+                            IncomingRoomKeyRequest.fromRestRequest(senderId, request, clock)?.let { iReq ->
+                                outgoingRequestScope.launch(coroutineDispatchers.computation) {
+                                    val listenersCopy = synchronized(gossipingRequestListeners) {
+                                        gossipingRequestListeners.toList()
+                                    }
+                                    listenersCopy.onEach {
+                                        tryOrNull {
+                                            withContext(coroutineDispatchers.main) {
+                                                it.onRequestCancelled(iReq)
+                                            }
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    }
+                } else {
+                    when (validMegolmRequest.action) {
+                        MegolmRequestAction.Request -> {
+                            // it's already in buffer, nop keep existing
+                        }
+                        MegolmRequestAction.Cancel  -> {
+                            // discard the request in buffer
+                            incomingRequestBuffer.remove(existing)
+                            outgoingRequestScope.launch(coroutineDispatchers.computation) {
+                                val listenersCopy = synchronized(gossipingRequestListeners) {
+                                    gossipingRequestListeners.toList()
+                                }
+                                listenersCopy.onEach {
+                                    IncomingRoomKeyRequest.fromRestRequest(senderId, request, clock)?.let { iReq ->
+                                        withContext(coroutineDispatchers.main) {
+                                            tryOrNull { it.onRequestCancelled(iReq) }
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    fun processIncomingRequests() {
+        outgoingRequestScope.launch {
+            sequencer.post {
+                measureTimeMillis {
+                    Timber.tag(loggerTag.value).v("processIncomingKeyRequests : ${incomingRequestBuffer.size} request to process")
+                    incomingRequestBuffer.forEach {
+                        // should not happen, we only store requests
+                        if (it.action != MegolmRequestAction.Request) return@forEach
+                        try {
+                            handleIncomingRequest(it)
+                        } catch (failure: Throwable) {
+                            // ignore and continue, should not happen
+                            Timber.tag(loggerTag.value).w(failure, "processIncomingKeyRequests : failed to process request $it")
+                        }
+                    }
+                    incomingRequestBuffer.clear()
+                }.let { duration ->
+                    Timber.tag(loggerTag.value).v("Finish processing incoming key request in $duration ms")
+                }
+            }
+        }
+    }
+
+    private suspend fun handleIncomingRequest(request: ValidMegolmRequestBody) {
+        // We don't want to download keys, if we don't know the device yet we won't share any how?
+        val requestingDevice =
+                cryptoStore.getUserDevice(request.requestingUserId, request.requestingDeviceId)
+                        ?: return Unit.also {
+                            Timber.tag(loggerTag.value).d("Ignoring key request: ${request.shortDbgString()}")
+                        }
+
+        cryptoStore.saveIncomingKeyRequestAuditTrail(
+                request.requestId,
+                request.roomId,
+                request.sessionId,
+                request.senderKey,
+                MXCRYPTO_ALGORITHM_MEGOLM,
+                request.requestingUserId,
+                request.requestingDeviceId
+        )
+
+        val roomAlgorithm = // withContext(coroutineDispatchers.crypto) {
+                cryptoStore.getRoomAlgorithm(request.roomId)
+//        }
+        if (roomAlgorithm != MXCRYPTO_ALGORITHM_MEGOLM) {
+            // strange we received a request for a room that is not encrypted
+            // maybe a broken state?
+            Timber.tag(loggerTag.value).w("Received a key request in a room with unsupported alg:$roomAlgorithm , req:${request.shortDbgString()}")
+            return
+        }
+
+        // Is it for one of our sessions?
+        if (request.requestingUserId == credentials.userId) {
+            Timber.tag(loggerTag.value).v("handling request from own user: megolm session ${request.sessionId}")
+
+            if (request.requestingDeviceId == credentials.deviceId) {
+                // ignore it's a remote echo
+                return
+            }
+            // If it's verified we share from the early index we know
+            // if not we check if it was originaly shared or not
+            if (requestingDevice.isVerified) {
+                // we share from the earliest known chain index
+                shareMegolmKey(request, requestingDevice, null)
+            } else {
+                shareIfItWasPreviouslyShared(request, requestingDevice)
+            }
+        } else {
+            if (cryptoConfig.limitRoomKeyRequestsToMyDevices) {
+                Timber.tag(loggerTag.value).v("Ignore request from other user as per crypto config: ${request.shortDbgString()}")
+                return
+            }
+            Timber.tag(loggerTag.value).v("handling request from other user: megolm session ${request.sessionId}")
+            if (requestingDevice.isBlocked) {
+                // it's blocked, so send a withheld code
+                sendWithheldForRequest(request, WithHeldCode.BLACKLISTED)
+            } else {
+                shareIfItWasPreviouslyShared(request, requestingDevice)
+            }
+        }
+    }
+
+    private suspend fun shareIfItWasPreviouslyShared(request: ValidMegolmRequestBody, requestingDevice: CryptoDeviceInfo) {
+        // we don't reshare unless it was previously shared with
+        val wasSessionSharedWithUser = withContext(coroutineDispatchers.crypto) {
+            cryptoStore.getSharedSessionInfo(request.roomId, request.sessionId, requestingDevice)
+        }
+        if (wasSessionSharedWithUser.found && wasSessionSharedWithUser.chainIndex != null) {
+            // we share from the index it was previously shared with
+            shareMegolmKey(request, requestingDevice, wasSessionSharedWithUser.chainIndex.toLong())
+        } else {
+            val isOwnDevice = requestingDevice.userId == credentials.userId
+            sendWithheldForRequest(request, if (isOwnDevice) WithHeldCode.UNVERIFIED else WithHeldCode.UNAUTHORISED)
+            // if it's our device we could delegate to the app layer to decide
+            if (isOwnDevice) {
+                outgoingRequestScope.launch(coroutineDispatchers.computation) {
+                    val listenersCopy = synchronized(gossipingRequestListeners) {
+                        gossipingRequestListeners.toList()
+                    }
+                    val iReq = IncomingRoomKeyRequest(
+                            userId = requestingDevice.userId,
+                            deviceId = requestingDevice.deviceId,
+                            requestId = request.requestId,
+                            requestBody = RoomKeyRequestBody(
+                                    algorithm = MXCRYPTO_ALGORITHM_MEGOLM,
+                                    senderKey = request.senderKey,
+                                    sessionId = request.sessionId,
+                                    roomId = request.roomId
+                            ),
+                            localCreationTimestamp = clock.epochMillis()
+                    )
+                    listenersCopy.onEach {
+                        withContext(coroutineDispatchers.main) {
+                            tryOrNull { it.onRoomKeyRequest(iReq) }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    private suspend fun sendWithheldForRequest(request: ValidMegolmRequestBody, code: WithHeldCode) {
+        Timber.tag(loggerTag.value)
+                .w("Send withheld $code for req: ${request.shortDbgString()}")
+        val withHeldContent = RoomKeyWithHeldContent(
+                roomId = request.roomId,
+                senderKey = request.senderKey,
+                algorithm = MXCRYPTO_ALGORITHM_MEGOLM,
+                sessionId = request.sessionId,
+                codeString = code.value,
+                fromDevice = credentials.deviceId
+        )
+
+        val params = SendToDeviceTask.Params(
+                EventType.ROOM_KEY_WITHHELD,
+                MXUsersDevicesMap().apply {
+                    setObject(request.requestingUserId, request.requestingDeviceId, withHeldContent)
+                }
+        )
+        try {
+            withContext(coroutineDispatchers.io) {
+                sendToDeviceTask.execute(params)
+                Timber.tag(loggerTag.value)
+                        .d("Send withheld $code req: ${request.shortDbgString()}")
+            }
+
+            cryptoStore.saveWithheldAuditTrail(
+                    roomId = request.roomId,
+                    sessionId = request.sessionId,
+                    senderKey = request.senderKey,
+                    algorithm = MXCRYPTO_ALGORITHM_MEGOLM,
+                    code = code,
+                    userId = request.requestingUserId,
+                    deviceId = request.requestingDeviceId
+            )
+        } catch (failure: Throwable) {
+            // Ignore it's not that important?
+            // do we want to fallback to a worker?
+            Timber.tag(loggerTag.value)
+                    .w("Failed to send withheld $code req: ${request.shortDbgString()} reason:${failure.localizedMessage}")
+        }
+    }
+
+    suspend fun manuallyAcceptRoomKeyRequest(request: IncomingRoomKeyRequest) {
+        request.requestId ?: return
+        request.deviceId ?: return
+        request.userId ?: return
+        request.requestBody?.roomId ?: return
+        request.requestBody.senderKey ?: return
+        request.requestBody.sessionId ?: return
+        val validReq = ValidMegolmRequestBody(
+                requestId = request.requestId,
+                requestingDeviceId = request.deviceId,
+                requestingUserId = request.userId,
+                roomId = request.requestBody.roomId,
+                senderKey = request.requestBody.senderKey,
+                sessionId = request.requestBody.sessionId,
+                action = MegolmRequestAction.Request
+        )
+        val requestingDevice =
+                cryptoStore.getUserDevice(request.userId, request.deviceId)
+                        ?: return Unit.also {
+                            Timber.tag(loggerTag.value).d("Ignoring key request: ${validReq.shortDbgString()}")
+                        }
+
+        shareMegolmKey(validReq, requestingDevice, null)
+    }
+
+    private suspend fun shareMegolmKey(validRequest: ValidMegolmRequestBody,
+                                       requestingDevice: CryptoDeviceInfo,
+                                       chainIndex: Long?): Boolean {
+        Timber.tag(loggerTag.value)
+                .d("try to re-share Megolm Key at index $chainIndex for ${validRequest.shortDbgString()}")
+
+        val devicesByUser = mapOf(validRequest.requestingUserId to listOf(requestingDevice))
+        val usersDeviceMap = try {
+            ensureOlmSessionsForDevicesAction.handle(devicesByUser)
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value)
+                    .w("Failed to establish olm session")
+            sendWithheldForRequest(validRequest, WithHeldCode.NO_OLM)
+            return false
+        }
+
+        val olmSessionResult = usersDeviceMap.getObject(requestingDevice.userId, requestingDevice.deviceId)
+        if (olmSessionResult?.sessionId == null) {
+            Timber.tag(loggerTag.value)
+                    .w("reshareKey: no session with this device, probably because there were no one-time keys")
+            sendWithheldForRequest(validRequest, WithHeldCode.NO_OLM)
+            return false
+        }
+        val sessionHolder = try {
+            olmDevice.getInboundGroupSession(validRequest.sessionId, validRequest.senderKey, validRequest.roomId)
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value)
+                    .e(failure, "shareKeysWithDevice: failed to get session ${validRequest.requestingUserId}")
+            // It's unavailable
+            sendWithheldForRequest(validRequest, WithHeldCode.UNAVAILABLE)
+            return false
+        }
+
+        val export = sessionHolder.mutex.withLock {
+            sessionHolder.wrapper.exportKeys(chainIndex)
+        } ?: return false.also {
+            Timber.tag(loggerTag.value)
+                    .e("shareKeysWithDevice: failed to export group session ${validRequest.sessionId}")
+        }
+
+        val payloadJson = mapOf(
+                "type" to EventType.FORWARDED_ROOM_KEY,
+                "content" to export
+        )
+
+        val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(requestingDevice))
+        val sendToDeviceMap = MXUsersDevicesMap()
+        sendToDeviceMap.setObject(requestingDevice.userId, requestingDevice.deviceId, encodedPayload)
+        Timber.tag(loggerTag.value).d("reshareKey() : try sending session ${validRequest.sessionId} to ${requestingDevice.shortDebugString()}")
+        val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap)
+        return try {
+            sendToDeviceTask.execute(sendToDeviceParams)
+            Timber.tag(loggerTag.value)
+                    .i("successfully re-shared session ${validRequest.sessionId} to ${requestingDevice.shortDebugString()}")
+            cryptoStore.saveForwardKeyAuditTrail(
+                    validRequest.roomId,
+                    validRequest.sessionId,
+                    validRequest.senderKey,
+                    MXCRYPTO_ALGORITHM_MEGOLM,
+                    requestingDevice.userId,
+                    requestingDevice.deviceId,
+                    chainIndex
+            )
+            true
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value)
+                    .e(failure, "fail to re-share session ${validRequest.sessionId} to ${requestingDevice.shortDebugString()}")
+            false
+        }
+    }
+
+    fun addRoomKeysRequestListener(listener: GossipingRequestListener) {
+        synchronized(gossipingRequestListeners) {
+            gossipingRequestListeners.add(listener)
+        }
+    }
+
+    fun removeRoomKeysRequestListener(listener: GossipingRequestListener) {
+        synchronized(gossipingRequestListeners) {
+            gossipingRequestListeners.remove(listener)
+        }
+    }
+
+    fun close() {
+        try {
+            outgoingRequestScope.cancel("User Terminate")
+            incomingRequestBuffer.clear()
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value).w("Failed to shutDown request manager")
+        }
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXMegolmExportEncryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXMegolmExportEncryption.kt
index 89e38cb7cf..e4a0f0376e 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXMegolmExportEncryption.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXMegolmExportEncryption.kt
@@ -32,7 +32,7 @@ import kotlin.math.min
 import kotlin.system.measureTimeMillis
 
 /**
- * Utility class to import/export the crypto data
+ * Utility class to import/export the crypto data.
  */
 internal object MXMegolmExportEncryption {
     private const val HEADER_LINE = "-----BEGIN MEGOLM SESSION DATA-----"
@@ -66,7 +66,7 @@ internal object MXMegolmExportEncryption {
     }
 
     /**
-     * Decrypt a megolm key file
+     * Decrypt a megolm key file.
      *
      * @param data     the data to decrypt
      * @param password the password.
@@ -209,8 +209,8 @@ internal object MXMegolmExportEncryption {
     }
 
     /**
-     * Unbase64 an ascii-armoured megolm key file
-     * Strips the header and trailer lines, and unbase64s the content
+     * Unbase64 an ascii-armoured megolm key file.
+     * Strips the header and trailer lines, and unbase64s the content.
      *
      * @param data the input data
      * @return unbase64ed content
@@ -302,7 +302,7 @@ internal object MXMegolmExportEncryption {
     }
 
     /**
-     * Derive the AES and HMAC-SHA-256 keys for the file
+     * Derive the AES and HMAC-SHA-256 keys for the file.
      *
      * @param salt       salt for pbkdf
      * @param iterations number of pbkdf iterations
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt
index 7eec83abdd..5620cbf769 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MXOlmDevice.kt
@@ -43,7 +43,6 @@ import org.matrix.olm.OlmOutboundGroupSession
 import org.matrix.olm.OlmSession
 import org.matrix.olm.OlmUtility
 import timber.log.Timber
-import java.net.URLEncoder
 import javax.inject.Inject
 
 private val loggerTag = LoggerTag("MXOlmDevice", LoggerTag.CRYPTO)
@@ -149,9 +148,9 @@ internal class MXOlmDevice @Inject constructor(
     }
 
     /**
-     * Returns an unpublished fallback key
+     * Returns an unpublished fallback key.
      * A call to markKeysAsPublished will mark it as published and this
-     * call will return null (until a call to generateFallbackKey is made)
+     * call will return null (until a call to generateFallbackKey is made).
      */
     fun getFallbackKey(): MutableMap>? {
         try {
@@ -198,7 +197,7 @@ internal class MXOlmDevice @Inject constructor(
     }
 
     /**
-     * Release the instance
+     * Release the instance.
      */
     fun release() {
         olmUtility?.releaseUtility()
@@ -241,7 +240,7 @@ internal class MXOlmDevice @Inject constructor(
     }
 
     /**
-     * Generate some new one-time keys
+     * Generate some new one-time keys.
      *
      * @param numKeys number of keys to generate
      */
@@ -331,14 +330,6 @@ internal class MXOlmDevice @Inject constructor(
                 Timber.tag(loggerTag.value).e(e, "## createInboundSession() : removeOneTimeKeys failed")
             }
 
-            Timber.tag(loggerTag.value).v("## createInboundSession() : ciphertext: $ciphertext")
-            try {
-                val sha256 = olmUtility!!.sha256(URLEncoder.encode(ciphertext, "utf-8"))
-                Timber.tag(loggerTag.value).v("## createInboundSession() :ciphertext: SHA256: $sha256")
-            } catch (e: Exception) {
-                Timber.tag(loggerTag.value).e(e, "## createInboundSession() :ciphertext: cannot encode ciphertext")
-            }
-
             val olmMessage = OlmMessage()
             olmMessage.mCipherText = ciphertext
             olmMessage.mType = messageType.toLong()
@@ -589,6 +580,13 @@ internal class MXOlmDevice @Inject constructor(
 
     //  Inbound group session
 
+    sealed interface AddSessionResult {
+        data class Imported(val ratchetIndex: Int) : AddSessionResult
+        abstract class Failure : AddSessionResult
+        object NotImported : Failure()
+        data class NotImportedHigherIndex(val newIndex: Int) : Failure()
+    }
+
     /**
      * Add an inbound group session to the session store.
      *
@@ -607,7 +605,7 @@ internal class MXOlmDevice @Inject constructor(
                                senderKey: String,
                                forwardingCurve25519KeyChain: List,
                                keysClaimed: Map,
-                               exportFormat: Boolean): Boolean {
+                               exportFormat: Boolean): AddSessionResult {
         val candidateSession = OlmInboundGroupSessionWrapper2(sessionKey, exportFormat)
         val existingSessionHolder = tryOrNull { getInboundGroupSession(sessionId, senderKey, roomId) }
         val existingSession = existingSessionHolder?.wrapper
@@ -615,7 +613,7 @@ internal class MXOlmDevice @Inject constructor(
         if (existingSession != null) {
             Timber.tag(loggerTag.value).d("## addInboundGroupSession() check if known session is better than candidate session")
             try {
-                val existingFirstKnown = existingSession.firstKnownIndex ?: return false.also {
+                val existingFirstKnown = existingSession.firstKnownIndex ?: return AddSessionResult.NotImported.also {
                     // This is quite unexpected, could throw if native was released?
                     Timber.tag(loggerTag.value).e("## addInboundGroupSession() null firstKnownIndex on existing session")
                     candidateSession.olmInboundGroupSession?.releaseSession()
@@ -626,12 +624,12 @@ internal class MXOlmDevice @Inject constructor(
                 if (newKnownFirstIndex != null && existingFirstKnown <= newKnownFirstIndex) {
                     Timber.tag(loggerTag.value).d("## addInboundGroupSession() : ignore session our is better $senderKey/$sessionId")
                     candidateSession.olmInboundGroupSession?.releaseSession()
-                    return false
+                    return AddSessionResult.NotImportedHigherIndex(newKnownFirstIndex.toInt())
                 }
             } catch (failure: Throwable) {
                 Timber.tag(loggerTag.value).e("## addInboundGroupSession() Failed to add inbound: ${failure.localizedMessage}")
                 candidateSession.olmInboundGroupSession?.releaseSession()
-                return false
+                return AddSessionResult.NotImported
             }
         }
 
@@ -641,19 +639,19 @@ internal class MXOlmDevice @Inject constructor(
         val candidateOlmInboundSession = candidateSession.olmInboundGroupSession
         if (null == candidateOlmInboundSession) {
             Timber.tag(loggerTag.value).e("## addInboundGroupSession : invalid session ")
-            return false
+            return AddSessionResult.NotImported
         }
 
         try {
             if (candidateOlmInboundSession.sessionIdentifier() != sessionId) {
                 Timber.tag(loggerTag.value).e("## addInboundGroupSession : ERROR: Mismatched group session ID from senderKey: $senderKey")
                 candidateOlmInboundSession.releaseSession()
-                return false
+                return AddSessionResult.NotImported
             }
         } catch (e: Throwable) {
             candidateOlmInboundSession.releaseSession()
             Timber.tag(loggerTag.value).e(e, "## addInboundGroupSession : sessionIdentifier() failed")
-            return false
+            return AddSessionResult.NotImported
         }
 
         candidateSession.senderKey = senderKey
@@ -667,7 +665,7 @@ internal class MXOlmDevice @Inject constructor(
             inboundGroupSessionStore.storeInBoundGroupSession(InboundGroupSessionHolder(candidateSession), sessionId, senderKey)
         }
 
-        return true
+        return AddSessionResult.Imported(candidateSession.firstKnownIndex?.toInt() ?: 0)
     }
 
     /**
@@ -790,7 +788,7 @@ internal class MXOlmDevice @Inject constructor(
 
                 if (timelineSet.contains(messageIndexKey)) {
                     val reason = String.format(MXCryptoError.DUPLICATE_MESSAGE_INDEX_REASON, decryptResult.mIndex)
-                    Timber.tag(loggerTag.value).e("## decryptGroupMessage() : $reason")
+                    Timber.tag(loggerTag.value).e("## decryptGroupMessage() timelineId=$timeline: $reason")
                     throw MXCryptoError.Base(MXCryptoError.ErrorType.DUPLICATED_MESSAGE_INDEX, reason)
                 }
 
@@ -858,7 +856,7 @@ internal class MXOlmDevice @Inject constructor(
     }
 
     /**
-     * Search an OlmSession
+     * Search an OlmSession.
      *
      * @param theirDeviceIdentityKey the device key
      * @param sessionId              the session Id
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MyDeviceInfoHolder.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MyDeviceInfoHolder.kt
index 9798d21576..3d09c0469b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MyDeviceInfoHolder.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/MyDeviceInfoHolder.kt
@@ -34,7 +34,7 @@ internal class MyDeviceInfoHolder @Inject constructor(
 ) {
     // Our device keys
     /**
-     * my device info
+     * my device info.
      */
     val myDevice: CryptoDeviceInfo
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt
index 68dd17324b..ab562d954a 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/ObjectSigner.kt
@@ -23,7 +23,7 @@ internal class ObjectSigner @Inject constructor(private val credentials: Credent
                                                 private val olmDevice: MXOlmDevice) {
 
     /**
-     * Sign Object
+     * Sign Object.
      *
      * Example:
      * 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmSessionStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmSessionStore.kt
index aac6f67aea..fe280416ea 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmSessionStore.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OlmSessionStore.kt
@@ -26,12 +26,12 @@ import javax.inject.Inject
 private val loggerTag = LoggerTag("OlmSessionStore", LoggerTag.CRYPTO)
 
 /**
- * Keep the used olm session in memory and load them from the data layer when needed
- * Access is synchronized for thread safety
+ * Keep the used olm session in memory and load them from the data layer when needed.
+ * Access is synchronized for thread safety.
  */
 internal class OlmSessionStore @Inject constructor(private val store: IMXCryptoStore) {
     /**
-     * map of device key to list of olm sessions (it is possible to have several active sessions with a device)
+     * Map of device key to list of olm sessions (it is possible to have several active sessions with a device).
      */
     private val olmSessions = HashMap>()
 
@@ -89,7 +89,7 @@ internal class OlmSessionStore @Inject constructor(private val store: IMXCryptoS
     }
 
     /**
-     * Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist
+     * Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist.
      *
      * @param deviceKey the public key of the other device.
      * @return last used sessionId, or null if not found
@@ -110,7 +110,7 @@ internal class OlmSessionStore @Inject constructor(private val store: IMXCryptoS
     }
 
     /**
-     * Release all sessions and clear cache
+     * Release all sessions and clear cache.
      */
     @Synchronized
     fun clear() {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingGossipingRequestManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingGossipingRequestManager.kt
deleted file mode 100755
index e6f6ac5053..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingGossipingRequestManager.kt
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto
-
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
-import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
-import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
-import org.matrix.android.sdk.internal.crypto.tasks.createUniqueTxnId
-import org.matrix.android.sdk.internal.crypto.util.RequestIdHelper
-import org.matrix.android.sdk.internal.di.SessionId
-import org.matrix.android.sdk.internal.session.SessionScope
-import org.matrix.android.sdk.internal.worker.WorkerParamsFactory
-import timber.log.Timber
-import javax.inject.Inject
-
-@SessionScope
-internal class OutgoingGossipingRequestManager @Inject constructor(
-        @SessionId private val sessionId: String,
-        private val cryptoStore: IMXCryptoStore,
-        private val coroutineDispatchers: MatrixCoroutineDispatchers,
-        private val cryptoCoroutineScope: CoroutineScope,
-        private val gossipingWorkManager: GossipingWorkManager) {
-
-    /**
-     * Send off a room key request, if we haven't already done so.
-     *
-     *
-     * The `requestBody` is compared (with a deep-equality check) against
-     * previous queued or sent requests and if it matches, no change is made.
-     * Otherwise, a request is added to the pending list, and a job is started
-     * in the background to send it.
-     *
-     * @param requestBody requestBody
-     * @param recipients  recipients
-     */
-    fun sendRoomKeyRequest(requestBody: RoomKeyRequestBody, recipients: Map>) {
-        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-            cryptoStore.getOrAddOutgoingRoomKeyRequest(requestBody, recipients)?.let {
-                // Don't resend if it's already done, you need to cancel first (reRequest)
-                if (it.state == OutgoingGossipingRequestState.SENDING || it.state == OutgoingGossipingRequestState.SENT) {
-                    Timber.v("## CRYPTO - GOSSIP sendOutgoingRoomKeyRequest() : we already request for that session: $it")
-                    return@launch
-                }
-
-                sendOutgoingGossipingRequest(it)
-            }
-        }
-    }
-
-    fun sendSecretShareRequest(secretName: String, recipients: Map>) {
-        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-            // A bit dirty, but for better stability give other party some time to mark
-            // devices trusted :/
-            delay(1500)
-            cryptoStore.getOrAddOutgoingSecretShareRequest(secretName, recipients)?.let {
-                // TODO check if there is already one that is being sent?
-                if (it.state == OutgoingGossipingRequestState.SENDING
-                /**|| it.state == OutgoingGossipingRequestState.SENT*/
-                ) {
-                    Timber.v("## CRYPTO - GOSSIP sendSecretShareRequest() : we are already sending for that session: $it")
-                    return@launch
-                }
-
-                sendOutgoingGossipingRequest(it)
-            }
-        }
-    }
-
-    /**
-     * Cancel room key requests, if any match the given details
-     *
-     * @param requestBody requestBody
-     */
-    fun cancelRoomKeyRequest(requestBody: RoomKeyRequestBody) {
-        cryptoCoroutineScope.launch(coroutineDispatchers.computation) {
-            cancelRoomKeyRequest(requestBody, false)
-        }
-    }
-
-    /**
-     * Cancel room key requests, if any match the given details, and resend
-     *
-     * @param requestBody requestBody
-     */
-    fun resendRoomKeyRequest(requestBody: RoomKeyRequestBody) {
-        cryptoCoroutineScope.launch(coroutineDispatchers.computation) {
-            cancelRoomKeyRequest(requestBody, true)
-        }
-    }
-
-    /**
-     * Cancel room key requests, if any match the given details, and resend
-     *
-     * @param requestBody requestBody
-     * @param andResend   true to resend the key request
-     */
-    private fun cancelRoomKeyRequest(requestBody: RoomKeyRequestBody, andResend: Boolean) {
-        val req = cryptoStore.getOutgoingRoomKeyRequest(requestBody) // no request was made for this key
-                ?: return Unit.also {
-                    Timber.v("## CRYPTO - GOSSIP cancelRoomKeyRequest() Unknown request $requestBody")
-                }
-
-        sendOutgoingRoomKeyRequestCancellation(req, andResend)
-    }
-
-    /**
-     * Send the outgoing key request.
-     *
-     * @param request the request
-     */
-    private fun sendOutgoingGossipingRequest(request: OutgoingGossipingRequest) {
-        Timber.v("## CRYPTO - GOSSIP sendOutgoingGossipingRequest() : Requesting keys $request")
-
-        val params = SendGossipRequestWorker.Params(
-                sessionId = sessionId,
-                keyShareRequest = request as? OutgoingRoomKeyRequest,
-                secretShareRequest = request as? OutgoingSecretRequest,
-                txnId = createUniqueTxnId()
-        )
-        cryptoStore.updateOutgoingGossipingRequestState(request.requestId, OutgoingGossipingRequestState.SENDING)
-        val workRequest = gossipingWorkManager.createWork(WorkerParamsFactory.toData(params), true)
-        gossipingWorkManager.postWork(workRequest)
-    }
-
-    /**
-     * Given a OutgoingRoomKeyRequest, cancel it and delete the request record
-     *
-     * @param request the request
-     */
-    private fun sendOutgoingRoomKeyRequestCancellation(request: OutgoingRoomKeyRequest, resend: Boolean = false) {
-        Timber.v("## CRYPTO - sendOutgoingRoomKeyRequestCancellation $request")
-        val params = CancelGossipRequestWorker.Params.fromRequest(sessionId, request)
-        cryptoStore.updateOutgoingGossipingRequestState(request.requestId, OutgoingGossipingRequestState.CANCELLING)
-
-        val workRequest = gossipingWorkManager.createWork(WorkerParamsFactory.toData(params), true)
-        gossipingWorkManager.postWork(workRequest)
-
-        if (resend) {
-            val reSendParams = SendGossipRequestWorker.Params(
-                    sessionId = sessionId,
-                    keyShareRequest = request.copy(requestId = RequestIdHelper.createUniqueRequestId()),
-                    txnId = createUniqueTxnId()
-            )
-            val reSendWorkRequest = gossipingWorkManager.createWork(WorkerParamsFactory.toData(reSendParams), true)
-            gossipingWorkManager.postWork(reSendWorkRequest)
-        }
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingKeyRequestManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingKeyRequestManager.kt
new file mode 100755
index 0000000000..d7652d0771
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingKeyRequestManager.kt
@@ -0,0 +1,518 @@
+/*
+ * Copyright 2020 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.asCoroutineDispatcher
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
+import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
+import org.matrix.android.sdk.api.crypto.MXCryptoConfig
+import org.matrix.android.sdk.api.extensions.tryOrNull
+import org.matrix.android.sdk.api.logger.LoggerTag
+import org.matrix.android.sdk.api.session.crypto.OutgoingKeyRequest
+import org.matrix.android.sdk.api.session.crypto.OutgoingRoomKeyRequestState
+import org.matrix.android.sdk.api.session.crypto.model.GossipingToDeviceObject
+import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
+import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
+import org.matrix.android.sdk.api.session.crypto.model.RoomKeyShareRequest
+import org.matrix.android.sdk.api.session.events.model.Event
+import org.matrix.android.sdk.api.session.events.model.EventType
+import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
+import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
+import org.matrix.android.sdk.api.session.events.model.toModel
+import org.matrix.android.sdk.api.util.fromBase64
+import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
+import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
+import org.matrix.android.sdk.internal.di.SessionId
+import org.matrix.android.sdk.internal.di.UserId
+import org.matrix.android.sdk.internal.session.SessionScope
+import org.matrix.android.sdk.internal.task.SemaphoreCoroutineSequencer
+import timber.log.Timber
+import java.util.Stack
+import java.util.concurrent.Executors
+import javax.inject.Inject
+import kotlin.system.measureTimeMillis
+
+private val loggerTag = LoggerTag("OutgoingKeyRequestManager", LoggerTag.CRYPTO)
+
+/**
+ * This class is responsible for sending key requests to other devices when a message failed to decrypt.
+ * It's lifecycle is based on the sync pulse:
+ *    - You can post queries for session, or report when you got a session
+ *    - At the end of the sync (onSyncComplete) it will then process all the posted request and send to devices
+ * If a request failed it will be retried at the end of the next sync
+ */
+@SessionScope
+internal class OutgoingKeyRequestManager @Inject constructor(
+        @SessionId private val sessionId: String,
+        @UserId private val myUserId: String,
+        private val cryptoStore: IMXCryptoStore,
+        private val coroutineDispatchers: MatrixCoroutineDispatchers,
+        private val cryptoConfig: MXCryptoConfig,
+        private val inboundGroupSessionStore: InboundGroupSessionStore,
+        private val sendToDeviceTask: SendToDeviceTask,
+        private val deviceListManager: DeviceListManager,
+        private val perSessionBackupQueryRateLimiter: PerSessionBackupQueryRateLimiter) {
+
+    private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
+    private val outgoingRequestScope = CoroutineScope(SupervisorJob() + dispatcher)
+    private val sequencer = SemaphoreCoroutineSequencer()
+
+    // We only have one active key request per session, so we don't request if it's already requested
+    // But it could make sense to check more the backup, as it's evolving.
+    // We keep a stack as we consider that the key requested last is more likely to be on screen?
+    private val requestDiscardedBecauseAlreadySentThatCouldBeTriedWithBackup = Stack>()
+
+    fun requestKeyForEvent(event: Event, force: Boolean) {
+        val (targets, body) = getRoomKeyRequestTargetForEvent(event) ?: return
+        val index = ratchetIndexForMessage(event) ?: 0
+        postRoomKeyRequest(body, targets, index, force)
+    }
+
+    private fun getRoomKeyRequestTargetForEvent(event: Event): Pair>, RoomKeyRequestBody>? {
+        val sender = event.senderId ?: return null
+        val encryptedEventContent = event.content.toModel() ?: return null.also {
+            Timber.tag(loggerTag.value).e("getRoomKeyRequestTargetForEvent Failed to re-request key, null content")
+        }
+        if (encryptedEventContent.algorithm != MXCRYPTO_ALGORITHM_MEGOLM) return null
+
+        val senderDevice = encryptedEventContent.deviceId
+        val recipients = if (cryptoConfig.limitRoomKeyRequestsToMyDevices) {
+            mapOf(
+                    myUserId to listOf("*")
+            )
+        } else {
+            if (event.senderId == myUserId) {
+                mapOf(
+                        myUserId to listOf("*")
+                )
+            } else {
+                // for the case where you share the key with a device that has a broken olm session
+                // The other user might Re-shares a megolm session key with devices if the key has already been
+                // sent to them.
+                mapOf(
+                        myUserId to listOf("*"),
+
+                        // We might not have deviceId in the future due to https://github.com/matrix-org/matrix-spec-proposals/pull/3700
+                        // so in this case query to all
+                        sender to listOf(senderDevice ?: "*")
+                )
+            }
+        }
+
+        val requestBody = RoomKeyRequestBody(
+                roomId = event.roomId,
+                algorithm = encryptedEventContent.algorithm,
+                senderKey = encryptedEventContent.senderKey,
+                sessionId = encryptedEventContent.sessionId
+        )
+        return recipients to requestBody
+    }
+
+    private fun ratchetIndexForMessage(event: Event): Int? {
+        val encryptedContent = event.content.toModel() ?: return null
+        if (encryptedContent.algorithm != MXCRYPTO_ALGORITHM_MEGOLM) return null
+        return encryptedContent.ciphertext?.fromBase64()?.inputStream()?.reader()?.let {
+            tryOrNull {
+                val megolmVersion = it.read()
+                if (megolmVersion != 3) return@tryOrNull null
+                /** Int tag */
+                if (it.read() != 8) return@tryOrNull null
+                it.read()
+            }
+        }
+    }
+
+    fun postRoomKeyRequest(requestBody: RoomKeyRequestBody, recipients: Map>, fromIndex: Int, force: Boolean = false) {
+        outgoingRequestScope.launch {
+            sequencer.post {
+                internalQueueRequest(requestBody, recipients, fromIndex, force)
+            }
+        }
+    }
+
+    /**
+     * Typically called when we the session as been imported or received meanwhile.
+     */
+    fun postCancelRequestForSessionIfNeeded(sessionId: String, roomId: String, senderKey: String, fromIndex: Int) {
+        outgoingRequestScope.launch {
+            sequencer.post {
+                internalQueueCancelRequest(sessionId, roomId, senderKey, fromIndex)
+            }
+        }
+    }
+
+    fun onSelfCrossSigningTrustChanged(newTrust: Boolean) {
+        if (newTrust) {
+            // we were previously not cross signed, but we are now
+            // so there is now more chances to get better replies for existing request
+            // Let's forget about sent request so that next time we try to decrypt we will resend requests
+            // We don't resend all because we don't want to generate a bulk of traffic
+            outgoingRequestScope.launch {
+                sequencer.post {
+                    cryptoStore.deleteOutgoingRoomKeyRequestInState(OutgoingRoomKeyRequestState.SENT)
+                }
+
+                sequencer.post {
+                    delay(1000)
+                    perSessionBackupQueryRateLimiter.refreshBackupInfoIfNeeded(true)
+                }
+            }
+        }
+    }
+
+    fun onRoomKeyForwarded(sessionId: String,
+                           algorithm: String,
+                           roomId: String,
+                           senderKey: String,
+                           fromDevice: String?,
+                           fromIndex: Int,
+                           event: Event) {
+        Timber.tag(loggerTag.value).d("Key forwarded for $sessionId from ${event.senderId}|$fromDevice at index $fromIndex")
+        outgoingRequestScope.launch {
+            sequencer.post {
+                cryptoStore.updateOutgoingRoomKeyReply(
+                        roomId = roomId,
+                        sessionId = sessionId,
+                        algorithm = algorithm,
+                        senderKey = senderKey,
+                        fromDevice = fromDevice,
+                        // strip out encrypted stuff as it's just a trail?
+                        event = event.copy(
+                                type = event.getClearType(),
+                                content = mapOf(
+                                        "chain_index" to fromIndex
+                                )
+                        )
+                )
+            }
+        }
+    }
+
+    fun onRoomKeyWithHeld(sessionId: String,
+                          algorithm: String,
+                          roomId: String,
+                          senderKey: String,
+                          fromDevice: String?,
+                          event: Event) {
+        outgoingRequestScope.launch {
+            sequencer.post {
+                Timber.tag(loggerTag.value).d("Withheld received for $sessionId from ${event.senderId}|$fromDevice")
+                Timber.tag(loggerTag.value).v("Withheld content ${event.getClearContent()}")
+
+                // We want to store withheld code from the sender of the message (owner of the megolm session), not from
+                // other devices that might gossip the key. If not the initial reason might be overridden
+                // by a request to one of our session.
+                event.getClearContent().toModel()?.let { withheld ->
+                    withContext(coroutineDispatchers.crypto) {
+                        tryOrNull {
+                            deviceListManager.downloadKeys(listOf(event.senderId ?: ""), false)
+                        }
+                        cryptoStore.getUserDeviceList(event.senderId ?: "")
+                                .also { devices ->
+                                    Timber.tag(loggerTag.value)
+                                            .v("Withheld Devices for ${event.senderId} are ${devices.orEmpty().joinToString { it.identityKey() ?: "" }}")
+                                }
+                                ?.firstOrNull {
+                                    it.identityKey() == senderKey
+                                }
+                    }.also {
+                        Timber.tag(loggerTag.value).v("Withheld device for sender key $senderKey is from ${it?.shortDebugString()}")
+                    }?.let {
+                        if (it.userId == event.senderId) {
+                            if (fromDevice != null) {
+                                if (it.deviceId == fromDevice) {
+                                    Timber.tag(loggerTag.value).v("Storing sender Withheld code ${withheld.code} for ${withheld.sessionId}")
+                                    cryptoStore.addWithHeldMegolmSession(withheld)
+                                }
+                            } else {
+                                Timber.tag(loggerTag.value).v("Storing sender Withheld code ${withheld.code} for ${withheld.sessionId}")
+                                cryptoStore.addWithHeldMegolmSession(withheld)
+                            }
+                        }
+                    }
+                }
+
+                // Here we store the replies from a given request
+                cryptoStore.updateOutgoingRoomKeyReply(
+                        roomId = roomId,
+                        sessionId = sessionId,
+                        algorithm = algorithm,
+                        senderKey = senderKey,
+                        fromDevice = fromDevice,
+                        event = event
+                )
+            }
+        }
+    }
+
+    /**
+     * Should be called after a sync, ideally if no catchup sync needed (as keys might arrive in those).
+     */
+    fun requireProcessAllPendingKeyRequests() {
+        outgoingRequestScope.launch {
+            sequencer.post {
+                internalProcessPendingKeyRequests()
+            }
+        }
+    }
+
+    private fun internalQueueCancelRequest(sessionId: String, roomId: String, senderKey: String, localKnownChainIndex: Int) {
+        // do we have known requests for that session??
+        Timber.tag(loggerTag.value).v("Cancel Key Request if needed for $sessionId")
+        val knownRequest = cryptoStore.getOutgoingRoomKeyRequest(
+                algorithm = MXCRYPTO_ALGORITHM_MEGOLM,
+                roomId = roomId,
+                sessionId = sessionId,
+                senderKey = senderKey
+        )
+        if (knownRequest.isEmpty()) return Unit.also {
+            Timber.tag(loggerTag.value).v("Handle Cancel Key Request for $sessionId -- Was not currently requested")
+        }
+        if (knownRequest.size > 1) {
+            // It's worth logging, there should be only one
+            Timber.tag(loggerTag.value).w("Found multiple requests for same sessionId $sessionId")
+        }
+        knownRequest.forEach { request ->
+            when (request.state) {
+                OutgoingRoomKeyRequestState.UNSENT                               -> {
+                    if (request.fromIndex >= localKnownChainIndex) {
+                        // we have a good index we can cancel
+                        cryptoStore.deleteOutgoingRoomKeyRequest(request.requestId)
+                    }
+                }
+                OutgoingRoomKeyRequestState.SENT                                 -> {
+                    // It was already sent, and index satisfied we can cancel
+                    if (request.fromIndex >= localKnownChainIndex) {
+                        cryptoStore.updateOutgoingRoomKeyRequestState(request.requestId, OutgoingRoomKeyRequestState.CANCELLATION_PENDING)
+                    }
+                }
+                OutgoingRoomKeyRequestState.CANCELLATION_PENDING                 -> {
+                    // It is already marked to be cancelled
+                }
+                OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND -> {
+                    if (request.fromIndex >= localKnownChainIndex) {
+                        // we just want to cancel now
+                        cryptoStore.updateOutgoingRoomKeyRequestState(request.requestId, OutgoingRoomKeyRequestState.CANCELLATION_PENDING)
+                    }
+                }
+                OutgoingRoomKeyRequestState.SENT_THEN_CANCELED                   -> {
+                    // was already canceled
+                    // if we need a better index, should we resend?
+                }
+            }
+        }
+    }
+
+    fun close() {
+        try {
+            outgoingRequestScope.cancel("User Terminate")
+            requestDiscardedBecauseAlreadySentThatCouldBeTriedWithBackup.clear()
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value).w("Failed to shutDown request manager")
+        }
+    }
+
+    private fun internalQueueRequest(requestBody: RoomKeyRequestBody, recipients: Map>, fromIndex: Int, force: Boolean) {
+        if (!cryptoStore.isKeyGossipingEnabled()) {
+            // we might want to try backup?
+            if (requestBody.roomId != null && requestBody.sessionId != null) {
+                requestDiscardedBecauseAlreadySentThatCouldBeTriedWithBackup.push(requestBody.roomId to requestBody.sessionId)
+            }
+            Timber.tag(loggerTag.value).d("discarding request for ${requestBody.sessionId} as gossiping is disabled")
+            return
+        }
+
+        Timber.tag(loggerTag.value).d("Queueing key request for ${requestBody.sessionId} force:$force")
+        val existing = cryptoStore.getOutgoingRoomKeyRequest(requestBody)
+        Timber.tag(loggerTag.value).v("Queueing key request exiting is ${existing?.state}")
+        when (existing?.state) {
+            null                                                             -> {
+                // create a new one
+                cryptoStore.getOrAddOutgoingRoomKeyRequest(requestBody, recipients, fromIndex)
+            }
+            OutgoingRoomKeyRequestState.UNSENT                               -> {
+                // nothing it's new or not yet handled
+            }
+            OutgoingRoomKeyRequestState.SENT                                 -> {
+                // it was already requested
+                Timber.tag(loggerTag.value).d("The session ${requestBody.sessionId} is already requested")
+                if (force) {
+                    // update to UNSENT
+                    Timber.tag(loggerTag.value).d(".. force to request  ${requestBody.sessionId}")
+                    cryptoStore.updateOutgoingRoomKeyRequestState(existing.requestId, OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND)
+                } else {
+                    if (existing.roomId != null && existing.sessionId != null) {
+                        requestDiscardedBecauseAlreadySentThatCouldBeTriedWithBackup.push(existing.roomId to existing.sessionId)
+                    }
+                }
+            }
+            OutgoingRoomKeyRequestState.CANCELLATION_PENDING                 -> {
+                // request is canceled only if I got the keys so what to do here...
+                if (force) {
+                    cryptoStore.updateOutgoingRoomKeyRequestState(existing.requestId, OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND)
+                }
+            }
+            OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND -> {
+                // It's already going to resend
+            }
+            OutgoingRoomKeyRequestState.SENT_THEN_CANCELED                   -> {
+                if (force) {
+                    cryptoStore.deleteOutgoingRoomKeyRequest(existing.requestId)
+                    cryptoStore.getOrAddOutgoingRoomKeyRequest(requestBody, recipients, fromIndex)
+                }
+            }
+        }
+
+        if (existing != null && existing.fromIndex >= fromIndex) {
+            // update the required index
+            cryptoStore.updateOutgoingRoomKeyRequiredIndex(existing.requestId, fromIndex)
+        }
+    }
+
+    private suspend fun internalProcessPendingKeyRequests() {
+        val toProcess = cryptoStore.getOutgoingRoomKeyRequests(OutgoingRoomKeyRequestState.pendingStates())
+        Timber.tag(loggerTag.value).v("Processing all pending key requests (found ${toProcess.size} pending)")
+
+        measureTimeMillis {
+            toProcess.forEach {
+                when (it.state) {
+                    OutgoingRoomKeyRequestState.UNSENT                               -> handleUnsentRequest(it)
+                    OutgoingRoomKeyRequestState.CANCELLATION_PENDING                 -> handleRequestToCancel(it)
+                    OutgoingRoomKeyRequestState.CANCELLATION_PENDING_AND_WILL_RESEND -> handleRequestToCancelWillResend(it)
+                    OutgoingRoomKeyRequestState.SENT_THEN_CANCELED,
+                    OutgoingRoomKeyRequestState.SENT                                 -> {
+                        // these are filtered out
+                    }
+                }
+            }
+        }.let {
+            Timber.tag(loggerTag.value).v("Finish processing pending key request in $it ms")
+        }
+
+        val maxBackupCallsBySync = 60
+        var currentCalls = 0
+        measureTimeMillis {
+            while (requestDiscardedBecauseAlreadySentThatCouldBeTriedWithBackup.isNotEmpty() && currentCalls < maxBackupCallsBySync) {
+                requestDiscardedBecauseAlreadySentThatCouldBeTriedWithBackup.pop().let { (roomId, sessionId) ->
+                    // we want to rate limit that somehow :/
+                    perSessionBackupQueryRateLimiter.tryFromBackupIfPossible(sessionId, roomId)
+                }
+                currentCalls++
+            }
+        }.let {
+            Timber.tag(loggerTag.value).v("Finish querying backup in $it ms")
+        }
+    }
+
+    private suspend fun handleUnsentRequest(request: OutgoingKeyRequest) {
+        // In order to avoid generating to_device traffic, we can first check if the key is backed up
+        Timber.tag(loggerTag.value).v("Handling unsent request for megolm session ${request.sessionId} in ${request.roomId}")
+        val sessionId = request.sessionId ?: return
+        val roomId = request.roomId ?: return
+        if (perSessionBackupQueryRateLimiter.tryFromBackupIfPossible(sessionId, roomId)) {
+            // let's see what's the index
+            val knownIndex = tryOrNull {
+                inboundGroupSessionStore.getInboundGroupSession(sessionId, request.requestBody?.senderKey ?: "")?.wrapper?.firstKnownIndex
+            }
+            if (knownIndex != null && knownIndex <= request.fromIndex) {
+                // we found the key in backup with good enough index, so we can just mark as cancelled, no need to send request
+                Timber.tag(loggerTag.value).v("Megolm session $sessionId successfully restored from backup, do not send request")
+                cryptoStore.deleteOutgoingRoomKeyRequest(request.requestId)
+                return
+            }
+        }
+
+        // we need to send the request
+        val toDeviceContent = RoomKeyShareRequest(
+                requestingDeviceId = cryptoStore.getDeviceId(),
+                requestId = request.requestId,
+                action = GossipingToDeviceObject.ACTION_SHARE_REQUEST,
+                body = request.requestBody
+        )
+        val contentMap = MXUsersDevicesMap()
+        request.recipients.forEach { userToDeviceMap ->
+            userToDeviceMap.value.forEach { deviceId ->
+                contentMap.setObject(userToDeviceMap.key, deviceId, toDeviceContent)
+            }
+        }
+
+        val params = SendToDeviceTask.Params(
+                eventType = EventType.ROOM_KEY_REQUEST,
+                contentMap = contentMap,
+                transactionId = request.requestId
+        )
+        try {
+            withContext(coroutineDispatchers.io) {
+                sendToDeviceTask.executeRetry(params, 3)
+            }
+            Timber.tag(loggerTag.value).d("Key request sent for $sessionId in room $roomId to ${request.recipients}")
+            // The request was sent, so update state
+            cryptoStore.updateOutgoingRoomKeyRequestState(request.requestId, OutgoingRoomKeyRequestState.SENT)
+            // TODO update the audit trail
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value).v("Failed to request $sessionId targets:${request.recipients}")
+        }
+    }
+
+    private suspend fun handleRequestToCancel(request: OutgoingKeyRequest): Boolean {
+        Timber.tag(loggerTag.value).v("handleRequestToCancel for megolm session ${request.sessionId}")
+        // we have to cancel this
+        val toDeviceContent = RoomKeyShareRequest(
+                requestingDeviceId = cryptoStore.getDeviceId(),
+                requestId = request.requestId,
+                action = GossipingToDeviceObject.ACTION_SHARE_CANCELLATION
+        )
+        val contentMap = MXUsersDevicesMap()
+        request.recipients.forEach { userToDeviceMap ->
+            userToDeviceMap.value.forEach { deviceId ->
+                contentMap.setObject(userToDeviceMap.key, deviceId, toDeviceContent)
+            }
+        }
+
+        val params = SendToDeviceTask.Params(
+                eventType = EventType.ROOM_KEY_REQUEST,
+                contentMap = contentMap,
+                transactionId = request.requestId
+        )
+        return try {
+            withContext(coroutineDispatchers.io) {
+                sendToDeviceTask.executeRetry(params, 3)
+            }
+            // The request cancellation was sent, we don't delete yet because we want
+            // to keep trace of the sent replies
+            cryptoStore.updateOutgoingRoomKeyRequestState(request.requestId, OutgoingRoomKeyRequestState.SENT_THEN_CANCELED)
+            true
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value).v("Failed to cancel request ${request.requestId} for session $sessionId targets:${request.recipients}")
+            false
+        }
+    }
+
+    private suspend fun handleRequestToCancelWillResend(request: OutgoingKeyRequest) {
+        if (handleRequestToCancel(request)) {
+            // this will create a new unsent request with no replies that will be process in the following call
+            cryptoStore.deleteOutgoingRoomKeyRequest(request.requestId)
+            request.requestBody?.let { cryptoStore.getOrAddOutgoingRoomKeyRequest(it, request.recipients, request.fromIndex) }
+        }
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingSecretRequest.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingSecretRequest.kt
deleted file mode 100755
index 2ba2f5c817..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingSecretRequest.kt
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto
-
-import com.squareup.moshi.JsonClass
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState
-
-/**
- * Represents an outgoing room key request
- */
-@JsonClass(generateAdapter = true)
-internal class OutgoingSecretRequest(
-        // Secret Name
-        val secretName: String?,
-        // list of recipients for the request
-        override var recipients: Map>,
-        // Unique id for this request. Used for both
-        // an id within the request for later pairing with a cancellation, and for
-        // the transaction id when sending the to_device messages to our local
-        override var requestId: String,
-        // current state of this request
-        override var state: OutgoingGossipingRequestState) : OutgoingGossipingRequest {
-
-    // transaction id for the cancellation, if any
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/PerSessionBackupQueryRateLimiter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/PerSessionBackupQueryRateLimiter.kt
new file mode 100644
index 0000000000..5f62e7be9d
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/PerSessionBackupQueryRateLimiter.kt
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto
+
+import dagger.Lazy
+import kotlinx.coroutines.withContext
+import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
+import org.matrix.android.sdk.api.logger.LoggerTag
+import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersionResult
+import org.matrix.android.sdk.api.session.crypto.keysbackup.SavedKeyBackupKeyInfo
+import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult
+import org.matrix.android.sdk.api.util.awaitCallback
+import org.matrix.android.sdk.internal.crypto.keysbackup.DefaultKeysBackupService
+import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
+import org.matrix.android.sdk.internal.util.time.Clock
+import timber.log.Timber
+import javax.inject.Inject
+
+// I keep the same name as OutgoingGossipingRequestManager to ease filtering of logs
+private val loggerTag = LoggerTag("OutgoingGossipingRequestManager", LoggerTag.CRYPTO)
+
+/**
+ * Used to try to get the key for UISI messages before sending room key request.
+ * We are adding some rate limiting to avoid querying too much for a key not in backup.
+ * Nonetheless the backup can be updated so we might want to retry from time to time.
+ */
+internal class PerSessionBackupQueryRateLimiter @Inject constructor(
+        private val coroutineDispatchers: MatrixCoroutineDispatchers,
+        private val keysBackupService: Lazy,
+        private val cryptoStore: IMXCryptoStore,
+        private val clock: Clock,
+) {
+
+    companion object {
+        const val MIN_TRY_BACKUP_PERIOD_MILLIS = 60 * 60_000 // 1 hour
+    }
+
+    data class Info(
+            val megolmSessionId: String,
+            val roomId: String
+    )
+
+    data class LastTry(
+            val backupVersion: String,
+            val timestamp: Long
+    )
+
+    /**
+     * Remember what we already tried (a key not in backup or some server issue).
+     * We might want to retry from time to time as the backup could have been updated.
+     */
+    private val lastFailureMap = mutableMapOf()
+
+    private var backupVersion: KeysVersionResult? = null
+    private var savedKeyBackupKeyInfo: SavedKeyBackupKeyInfo? = null
+    var backupWasCheckedFromServer: Boolean = false
+    val now = clock.epochMillis()
+
+    fun refreshBackupInfoIfNeeded(force: Boolean = false) {
+        if (backupWasCheckedFromServer && !force) return
+        Timber.tag(loggerTag.value).v("Checking if can access a backup")
+        backupWasCheckedFromServer = true
+        val knownBackupSecret = cryptoStore.getKeyBackupRecoveryKeyInfo()
+                ?: return Unit.also {
+                    Timber.tag(loggerTag.value).v("We don't have the backup secret!")
+                }
+        this.backupVersion = keysBackupService.get().keysBackupVersion
+        this.savedKeyBackupKeyInfo = knownBackupSecret
+    }
+
+    suspend fun tryFromBackupIfPossible(sessionId: String, roomId: String): Boolean {
+        Timber.tag(loggerTag.value).v("tryFromBackupIfPossible for session:$sessionId in $roomId")
+        refreshBackupInfoIfNeeded()
+        val currentVersion = backupVersion
+        if (savedKeyBackupKeyInfo?.version == null ||
+                currentVersion == null ||
+                currentVersion.version != savedKeyBackupKeyInfo?.version) {
+            // We can't access the backup
+            Timber.tag(loggerTag.value).v("Can't get backup version info")
+            return false
+        }
+        val cacheKey = Info(sessionId, roomId)
+        val lastTry = lastFailureMap[cacheKey]
+        val shouldQuery =
+                lastTry == null ||
+                        lastTry.backupVersion != currentVersion.version ||
+                        (now - lastTry.timestamp) > MIN_TRY_BACKUP_PERIOD_MILLIS
+
+        if (!shouldQuery) return false
+
+        val successfullyImported = withContext(coroutineDispatchers.io) {
+            try {
+                awaitCallback {
+                    keysBackupService.get().restoreKeysWithRecoveryKey(
+                            currentVersion,
+                            savedKeyBackupKeyInfo?.recoveryKey ?: "",
+                            roomId,
+                            sessionId,
+                            null,
+                            it
+                    )
+                }.successfullyNumberOfImportedKeys
+            } catch (failure: Throwable) {
+                // Fail silently
+                Timber.tag(loggerTag.value).v("getFromBackup failed ${failure.localizedMessage}")
+                0
+            }
+        }
+        if (successfullyImported == 1) {
+            Timber.tag(loggerTag.value).v("Found key in backup session:$sessionId in $roomId")
+            lastFailureMap.remove(cacheKey)
+            return true
+        } else {
+            Timber.tag(loggerTag.value).v("Failed to find key in backup session:$sessionId in $roomId")
+            lastFailureMap[cacheKey] = LastTry(currentVersion.version, clock.epochMillis())
+            return false
+        }
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt
index dab806a565..c2f494b4b3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomDecryptorProvider.kt
@@ -79,7 +79,7 @@ internal class RoomDecryptorProvider @Inject constructor(
                             newSessionListeners.toList().forEach {
                                 try {
                                     it.onNewSession(roomId, senderKey, sessionId)
-                                } catch (e: Throwable) {
+                                } catch (ignore: Throwable) {
                                 }
                             }
                         }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt
index ba97d96133..1a8c160d9c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/RoomEncryptorsStore.kt
@@ -16,12 +16,21 @@
 
 package org.matrix.android.sdk.internal.crypto
 
+import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
+import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_OLM
 import org.matrix.android.sdk.internal.crypto.algorithms.IMXEncrypting
+import org.matrix.android.sdk.internal.crypto.algorithms.megolm.MXMegolmEncryptionFactory
+import org.matrix.android.sdk.internal.crypto.algorithms.olm.MXOlmEncryptionFactory
+import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
 import org.matrix.android.sdk.internal.session.SessionScope
 import javax.inject.Inject
 
 @SessionScope
-internal class RoomEncryptorsStore @Inject constructor() {
+internal class RoomEncryptorsStore @Inject constructor(
+        private val cryptoStore: IMXCryptoStore,
+        private val megolmEncryptionFactory: MXMegolmEncryptionFactory,
+        private val olmEncryptionFactory: MXOlmEncryptionFactory,
+) {
 
     // MXEncrypting instance for each room.
     private val roomEncryptors = mutableMapOf()
@@ -34,7 +43,18 @@ internal class RoomEncryptorsStore @Inject constructor() {
 
     fun get(roomId: String): IMXEncrypting? {
         return synchronized(roomEncryptors) {
-            roomEncryptors[roomId]
+            val cache = roomEncryptors[roomId]
+            if (cache != null) {
+                return@synchronized cache
+            } else {
+                val alg: IMXEncrypting? = when (cryptoStore.getRoomAlgorithm(roomId)) {
+                    MXCRYPTO_ALGORITHM_MEGOLM -> megolmEncryptionFactory.create(roomId)
+                    MXCRYPTO_ALGORITHM_OLM    -> olmEncryptionFactory.create(roomId)
+                    else                      -> null
+                }
+                alg?.let { roomEncryptors.put(roomId, it) }
+                return@synchronized alg
+            }
         }
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SecretShareManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SecretShareManager.kt
new file mode 100644
index 0000000000..6fb6914206
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SecretShareManager.kt
@@ -0,0 +1,300 @@
+/*
+ * Copyright (c) 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
+import org.matrix.android.sdk.api.auth.data.Credentials
+import org.matrix.android.sdk.api.logger.LoggerTag
+import org.matrix.android.sdk.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME
+import org.matrix.android.sdk.api.session.crypto.crosssigning.MASTER_KEY_SSSS_NAME
+import org.matrix.android.sdk.api.session.crypto.crosssigning.SELF_SIGNING_KEY_SSSS_NAME
+import org.matrix.android.sdk.api.session.crypto.crosssigning.USER_SIGNING_KEY_SSSS_NAME
+import org.matrix.android.sdk.api.session.crypto.keysbackup.extractCurveKeyFromRecoveryKey
+import org.matrix.android.sdk.api.session.crypto.keyshare.GossipingRequestListener
+import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
+import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest
+import org.matrix.android.sdk.api.session.events.model.Event
+import org.matrix.android.sdk.api.session.events.model.EventType
+import org.matrix.android.sdk.api.session.events.model.content.SecretSendEventContent
+import org.matrix.android.sdk.api.session.events.model.toModel
+import org.matrix.android.sdk.api.util.toBase64NoPadding
+import org.matrix.android.sdk.internal.crypto.actions.EnsureOlmSessionsForDevicesAction
+import org.matrix.android.sdk.internal.crypto.actions.MessageEncrypter
+import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
+import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
+import org.matrix.android.sdk.internal.crypto.tasks.createUniqueTxnId
+import org.matrix.android.sdk.internal.session.SessionScope
+import org.matrix.android.sdk.internal.util.time.Clock
+import timber.log.Timber
+import javax.inject.Inject
+
+private val loggerTag = LoggerTag("SecretShareManager", LoggerTag.CRYPTO)
+
+@SessionScope
+internal class SecretShareManager @Inject constructor(
+        private val credentials: Credentials,
+        private val cryptoStore: IMXCryptoStore,
+        private val cryptoCoroutineScope: CoroutineScope,
+        private val messageEncrypter: MessageEncrypter,
+        private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction,
+        private val sendToDeviceTask: SendToDeviceTask,
+        private val coroutineDispatchers: MatrixCoroutineDispatchers,
+        private val clock: Clock,
+) {
+
+    companion object {
+        private const val SECRET_SHARE_WINDOW_DURATION = 5 * 60 * 1000 // 5 minutes
+    }
+
+    /**
+     * Secret gossiping only occurs during a limited window period after interactive verification.
+     * We keep track of recent verification in memory for that purpose (no need to persist)
+     */
+    private val recentlyVerifiedDevices = mutableMapOf()
+    private val verifMutex = Mutex()
+
+    /**
+     * Secrets are exchanged as part of interactive verification,
+     * so we can just store in memory.
+     */
+    private val outgoingSecretRequests = mutableListOf()
+
+    // the listeners
+    private val gossipingRequestListeners: MutableSet = HashSet()
+
+    fun addListener(listener: GossipingRequestListener) {
+        synchronized(gossipingRequestListeners) {
+            gossipingRequestListeners.add(listener)
+        }
+    }
+
+    fun removeListener(listener: GossipingRequestListener) {
+        synchronized(gossipingRequestListeners) {
+            gossipingRequestListeners.remove(listener)
+        }
+    }
+
+    /**
+     * Called when a session has been verified.
+     * This information can be used by the manager to decide whether or not to fullfill gossiping requests.
+     * This should be called as fast as possible after a successful self interactive verification
+     */
+    fun onVerificationCompleteForDevice(deviceId: String) {
+        // For now we just keep an in memory cache
+        cryptoCoroutineScope.launch {
+            verifMutex.withLock {
+                recentlyVerifiedDevices[deviceId] = clock.epochMillis()
+            }
+        }
+    }
+
+    suspend fun handleSecretRequest(toDevice: Event) {
+        val request = toDevice.getClearContent().toModel()
+                ?: return Unit.also {
+                    Timber.tag(loggerTag.value)
+                            .w("handleSecretRequest() : malformed request")
+                }
+
+//            val (action, requestingDeviceId, requestId, secretName) = it
+        val secretName = request.secretName ?: return Unit.also {
+            Timber.tag(loggerTag.value)
+                    .v("handleSecretRequest() : Missing secret name")
+        }
+
+        val userId = toDevice.senderId ?: return Unit.also {
+            Timber.tag(loggerTag.value)
+                    .v("handleSecretRequest() : Missing senderId")
+        }
+
+        if (userId != credentials.userId) {
+            // secrets are only shared between our own devices
+            Timber.tag(loggerTag.value)
+                    .e("Ignoring secret share request from other users $userId")
+            return
+        }
+
+        val deviceId = request.requestingDeviceId
+                ?: return Unit.also {
+                    Timber.tag(loggerTag.value)
+                            .w("handleSecretRequest() : malformed request norequestingDeviceId ")
+                }
+
+        val device = cryptoStore.getUserDevice(credentials.userId, deviceId)
+                ?: return Unit.also {
+                    Timber.tag(loggerTag.value)
+                            .e("Received secret share request from unknown device $deviceId")
+                }
+
+        val isRequestingDeviceTrusted = device.isVerified
+        val isRecentInteractiveVerification = hasBeenVerifiedLessThanFiveMinutesFromNow(device.deviceId)
+        if (isRequestingDeviceTrusted && isRecentInteractiveVerification) {
+            // we can share the secret
+
+            val secretValue = when (secretName) {
+                MASTER_KEY_SSSS_NAME       -> cryptoStore.getCrossSigningPrivateKeys()?.master
+                SELF_SIGNING_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.selfSigned
+                USER_SIGNING_KEY_SSSS_NAME -> cryptoStore.getCrossSigningPrivateKeys()?.user
+                KEYBACKUP_SECRET_SSSS_NAME -> cryptoStore.getKeyBackupRecoveryKeyInfo()?.recoveryKey
+                        ?.let {
+                            extractCurveKeyFromRecoveryKey(it)?.toBase64NoPadding()
+                        }
+                else                       -> null
+            }
+            if (secretValue == null) {
+                Timber.tag(loggerTag.value)
+                        .i("The secret is unknown $secretName, passing to app layer")
+                val toList = synchronized(gossipingRequestListeners) { gossipingRequestListeners.toList() }
+                toList.onEach { listener ->
+                    listener.onSecretShareRequest(request)
+                }
+                return
+            }
+
+            val payloadJson = mapOf(
+                    "type" to EventType.SEND_SECRET,
+                    "content" to mapOf(
+                            "request_id" to request.requestId,
+                            "secret" to secretValue
+                    )
+            )
+
+            // Is it possible that we don't have an olm session?
+            val devicesByUser = mapOf(device.userId to listOf(device))
+            val usersDeviceMap = try {
+                ensureOlmSessionsForDevicesAction.handle(devicesByUser)
+            } catch (failure: Throwable) {
+                Timber.tag(loggerTag.value)
+                        .w("Can't share secret ${request.secretName}: Failed to establish olm session")
+                return
+            }
+
+            val olmSessionResult = usersDeviceMap.getObject(device.userId, device.deviceId)
+            if (olmSessionResult?.sessionId == null) {
+                Timber.tag(loggerTag.value)
+                        .w("secret share: no session with this device $deviceId, probably because there were no one-time keys")
+                return
+            }
+
+            val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(device))
+            val sendToDeviceMap = MXUsersDevicesMap()
+            sendToDeviceMap.setObject(device.userId, device.deviceId, encodedPayload)
+            val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap)
+            try {
+                // raise the retries for secret
+                sendToDeviceTask.executeRetry(sendToDeviceParams, 6)
+                Timber.tag(loggerTag.value)
+                        .i("successfully shared secret $secretName to ${device.shortDebugString()}")
+                // TODO add a trail for that in audit logs
+            } catch (failure: Throwable) {
+                Timber.tag(loggerTag.value)
+                        .e(failure, "failed to send shared secret $secretName to ${device.shortDebugString()}")
+            }
+        } else {
+            Timber.tag(loggerTag.value)
+                    .d(" Received secret share request from un-authorised device ${device.deviceId}")
+        }
+    }
+
+    private suspend fun hasBeenVerifiedLessThanFiveMinutesFromNow(deviceId: String): Boolean {
+        val verifTimestamp = verifMutex.withLock {
+            recentlyVerifiedDevices[deviceId]
+        } ?: return false
+
+        val age = clock.epochMillis() - verifTimestamp
+
+        return age < SECRET_SHARE_WINDOW_DURATION
+    }
+
+    suspend fun requestSecretTo(deviceId: String, secretName: String) {
+        val cryptoDeviceInfo = cryptoStore.getUserDevice(credentials.userId, deviceId) ?: return Unit.also {
+            Timber.tag(loggerTag.value)
+                    .d("Can't request secret for $secretName unknown device $deviceId")
+        }
+        val toDeviceContent = SecretShareRequest(
+                requestingDeviceId = credentials.deviceId,
+                secretName = secretName,
+                requestId = createUniqueTxnId()
+        )
+
+        verifMutex.withLock {
+            outgoingSecretRequests.add(toDeviceContent)
+        }
+
+        val contentMap = MXUsersDevicesMap()
+        contentMap.setObject(cryptoDeviceInfo.userId, cryptoDeviceInfo.deviceId, toDeviceContent)
+
+        val params = SendToDeviceTask.Params(
+                eventType = EventType.REQUEST_SECRET,
+                contentMap = contentMap
+        )
+        try {
+            withContext(coroutineDispatchers.io) {
+                sendToDeviceTask.executeRetry(params, 3)
+            }
+            Timber.tag(loggerTag.value)
+                    .d("Secret request sent for $secretName to ${cryptoDeviceInfo.shortDebugString()}")
+            // TODO update the audit trail
+        } catch (failure: Throwable) {
+            Timber.tag(loggerTag.value)
+                    .w("Failed to request secret $secretName to ${cryptoDeviceInfo.shortDebugString()}")
+        }
+    }
+
+    suspend fun onSecretSendReceived(toDevice: Event, handleGossip: ((name: String, value: String) -> Boolean)) {
+        Timber.tag(loggerTag.value)
+                .i("onSecretSend() from ${toDevice.senderId} : onSecretSendReceived ${toDevice.content?.get("sender_key")}")
+        if (!toDevice.isEncrypted()) {
+            // secret send messages must be encrypted
+            Timber.tag(loggerTag.value).e("onSecretSend() :Received unencrypted secret send event")
+            return
+        }
+
+        // Was that sent by us?
+        if (toDevice.senderId != credentials.userId) {
+            Timber.tag(loggerTag.value).e("onSecretSend() : Ignore secret from other user ${toDevice.senderId}")
+            return
+        }
+
+        val secretContent = toDevice.getClearContent().toModel() ?: return
+
+        val existingRequest = verifMutex.withLock {
+            outgoingSecretRequests.firstOrNull { it.requestId == secretContent.requestId }
+        }
+
+        // As per spec:
+        // Clients should ignore m.secret.send events received from devices that it did not send an m.secret.request event to.
+        if (existingRequest?.secretName == null) {
+            Timber.tag(loggerTag.value).i("onSecretSend() : Ignore secret that was not requested: ${secretContent.requestId}")
+            return
+        }
+        // we don't need to cancel the request as we only request to one device
+        // just forget about the request now
+        verifMutex.withLock {
+            outgoingSecretRequests.remove(existingRequest)
+        }
+
+        if (!handleGossip(existingRequest.secretName, secretContent.secretValue)) {
+            // TODO Ask to application layer?
+            Timber.tag(loggerTag.value).v("onSecretSend() : secret not handled by SDK")
+        }
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SendGossipRequestWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SendGossipRequestWorker.kt
deleted file mode 100644
index 3b43ad672b..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SendGossipRequestWorker.kt
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto
-
-import android.content.Context
-import androidx.work.WorkerParameters
-import com.squareup.moshi.JsonClass
-import org.matrix.android.sdk.api.auth.data.Credentials
-import org.matrix.android.sdk.api.failure.shouldBeRetried
-import org.matrix.android.sdk.api.session.crypto.model.GossipingToDeviceObject
-import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyShareRequest
-import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest
-import org.matrix.android.sdk.api.session.events.model.Event
-import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.api.session.events.model.toContent
-import org.matrix.android.sdk.internal.SessionManager
-import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
-import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
-import org.matrix.android.sdk.internal.crypto.tasks.createUniqueTxnId
-import org.matrix.android.sdk.internal.session.SessionComponent
-import org.matrix.android.sdk.internal.util.time.Clock
-import org.matrix.android.sdk.internal.worker.SessionSafeCoroutineWorker
-import org.matrix.android.sdk.internal.worker.SessionWorkerParams
-import timber.log.Timber
-import javax.inject.Inject
-
-internal class SendGossipRequestWorker(context: Context, params: WorkerParameters, sessionManager: SessionManager) :
-        SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) {
-
-    @JsonClass(generateAdapter = true)
-    internal data class Params(
-            override val sessionId: String,
-            val keyShareRequest: OutgoingRoomKeyRequest? = null,
-            val secretShareRequest: OutgoingSecretRequest? = null,
-            // The txnId for the sendToDevice request. Nullable for compatibility reasons, but MUST always be provided
-            // to use the same value if this worker is retried.
-            val txnId: String? = null,
-            override val lastFailureMessage: String? = null
-    ) : SessionWorkerParams
-
-    @Inject lateinit var sendToDeviceTask: SendToDeviceTask
-    @Inject lateinit var cryptoStore: IMXCryptoStore
-    @Inject lateinit var credentials: Credentials
-    @Inject lateinit var clock: Clock
-
-    override fun injectWith(injector: SessionComponent) {
-        injector.inject(this)
-    }
-
-    override suspend fun doSafeWork(params: Params): Result {
-        // params.txnId should be provided in all cases now. But Params can be deserialized by
-        // the WorkManager from data serialized in a previous version of the application, so without the txnId field.
-        // So if not present, we create a txnId
-        val txnId = params.txnId ?: createUniqueTxnId()
-        val contentMap = MXUsersDevicesMap()
-        val eventType: String
-        val requestId: String
-        when {
-            params.keyShareRequest != null    -> {
-                eventType = EventType.ROOM_KEY_REQUEST
-                requestId = params.keyShareRequest.requestId
-                val toDeviceContent = RoomKeyShareRequest(
-                        requestingDeviceId = credentials.deviceId,
-                        requestId = params.keyShareRequest.requestId,
-                        action = GossipingToDeviceObject.ACTION_SHARE_REQUEST,
-                        body = params.keyShareRequest.requestBody
-                )
-                cryptoStore.saveGossipingEvent(Event(
-                        type = eventType,
-                        content = toDeviceContent.toContent(),
-                        senderId = credentials.userId
-                ).also {
-                    it.ageLocalTs = clock.epochMillis()
-                })
-
-                params.keyShareRequest.recipients.forEach { userToDeviceMap ->
-                    userToDeviceMap.value.forEach { deviceId ->
-                        contentMap.setObject(userToDeviceMap.key, deviceId, toDeviceContent)
-                    }
-                }
-            }
-            params.secretShareRequest != null -> {
-                eventType = EventType.REQUEST_SECRET
-                requestId = params.secretShareRequest.requestId
-                val toDeviceContent = SecretShareRequest(
-                        requestingDeviceId = credentials.deviceId,
-                        requestId = params.secretShareRequest.requestId,
-                        action = GossipingToDeviceObject.ACTION_SHARE_REQUEST,
-                        secretName = params.secretShareRequest.secretName
-                )
-
-                cryptoStore.saveGossipingEvent(Event(
-                        type = eventType,
-                        content = toDeviceContent.toContent(),
-                        senderId = credentials.userId
-                ).also {
-                    it.ageLocalTs = clock.epochMillis()
-                })
-
-                params.secretShareRequest.recipients.forEach { userToDeviceMap ->
-                    userToDeviceMap.value.forEach { deviceId ->
-                        contentMap.setObject(userToDeviceMap.key, deviceId, toDeviceContent)
-                    }
-                }
-            }
-            else                              -> {
-                return buildErrorResult(params, "Unknown empty gossiping request").also {
-                    Timber.e("Unknown empty gossiping request: $params")
-                }
-            }
-        }
-        try {
-            cryptoStore.updateOutgoingGossipingRequestState(requestId, OutgoingGossipingRequestState.SENDING)
-            sendToDeviceTask.execute(
-                    SendToDeviceTask.Params(
-                            eventType = eventType,
-                            contentMap = contentMap,
-                            transactionId = txnId
-                    )
-            )
-            cryptoStore.updateOutgoingGossipingRequestState(requestId, OutgoingGossipingRequestState.SENT)
-            return Result.success()
-        } catch (throwable: Throwable) {
-            return if (throwable.shouldBeRetried()) {
-                Result.retry()
-            } else {
-                cryptoStore.updateOutgoingGossipingRequestState(requestId, OutgoingGossipingRequestState.FAILED_TO_SEND)
-                buildErrorResult(params, throwable.localizedMessage ?: "error")
-            }
-        }
-    }
-
-    override fun buildErrorParams(params: Params, message: String): Params {
-        return params.copy(lastFailureMessage = params.lastFailureMessage ?: message)
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SendGossipWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SendGossipWorker.kt
deleted file mode 100644
index 113d71d387..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/SendGossipWorker.kt
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto
-
-import android.content.Context
-import androidx.work.WorkerParameters
-import com.squareup.moshi.JsonClass
-import org.matrix.android.sdk.api.auth.data.Credentials
-import org.matrix.android.sdk.api.failure.shouldBeRetried
-import org.matrix.android.sdk.api.session.crypto.model.GossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
-import org.matrix.android.sdk.api.session.events.model.Event
-import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.api.session.events.model.content.SecretSendEventContent
-import org.matrix.android.sdk.api.session.events.model.toContent
-import org.matrix.android.sdk.internal.SessionManager
-import org.matrix.android.sdk.internal.crypto.actions.EnsureOlmSessionsForDevicesAction
-import org.matrix.android.sdk.internal.crypto.actions.MessageEncrypter
-import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
-import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
-import org.matrix.android.sdk.internal.crypto.tasks.createUniqueTxnId
-import org.matrix.android.sdk.internal.session.SessionComponent
-import org.matrix.android.sdk.internal.util.time.Clock
-import org.matrix.android.sdk.internal.worker.SessionSafeCoroutineWorker
-import org.matrix.android.sdk.internal.worker.SessionWorkerParams
-import timber.log.Timber
-import javax.inject.Inject
-
-internal class SendGossipWorker(
-        context: Context,
-        params: WorkerParameters,
-        sessionManager: SessionManager
-) : SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) {
-
-    @JsonClass(generateAdapter = true)
-    internal data class Params(
-            override val sessionId: String,
-            val secretValue: String,
-            val requestUserId: String?,
-            val requestDeviceId: String?,
-            val requestId: String?,
-            // The txnId for the sendToDevice request. Nullable for compatibility reasons, but MUST always be provided
-            // to use the same value if this worker is retried.
-            val txnId: String? = null,
-            override val lastFailureMessage: String? = null
-    ) : SessionWorkerParams
-
-    @Inject lateinit var sendToDeviceTask: SendToDeviceTask
-    @Inject lateinit var cryptoStore: IMXCryptoStore
-    @Inject lateinit var credentials: Credentials
-    @Inject lateinit var messageEncrypter: MessageEncrypter
-    @Inject lateinit var ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction
-    @Inject lateinit var clock: Clock
-
-    override fun injectWith(injector: SessionComponent) {
-        injector.inject(this)
-    }
-
-    override suspend fun doSafeWork(params: Params): Result {
-        // params.txnId should be provided in all cases now. But Params can be deserialized by
-        // the WorkManager from data serialized in a previous version of the application, so without the txnId field.
-        // So if not present, we create a txnId
-        val txnId = params.txnId ?: createUniqueTxnId()
-        val eventType: String = EventType.SEND_SECRET
-
-        val toDeviceContent = SecretSendEventContent(
-                requestId = params.requestId ?: "",
-                secretValue = params.secretValue
-        )
-
-        val requestingUserId = params.requestUserId ?: ""
-        val requestingDeviceId = params.requestDeviceId ?: ""
-        val deviceInfo = cryptoStore.getUserDevice(requestingUserId, requestingDeviceId)
-                ?: return buildErrorResult(params, "Unknown deviceInfo, cannot send message").also {
-                    cryptoStore.updateGossipingRequestState(
-                            requestUserId = params.requestUserId,
-                            requestDeviceId = params.requestDeviceId,
-                            requestId = params.requestId,
-                            state = GossipingRequestState.FAILED_TO_ACCEPTED
-                    )
-                    Timber.e("Unknown deviceInfo, cannot send message, sessionId: ${params.requestDeviceId}")
-                }
-
-        val sendToDeviceMap = MXUsersDevicesMap()
-
-        val devicesByUser = mapOf(requestingUserId to listOf(deviceInfo))
-        val usersDeviceMap = ensureOlmSessionsForDevicesAction.handle(devicesByUser)
-        val olmSessionResult = usersDeviceMap.getObject(requestingUserId, requestingDeviceId)
-        if (olmSessionResult?.sessionId == null) {
-            // no session with this device, probably because there
-            // were no one-time keys.
-            return buildErrorResult(params, "no session with this device").also {
-                cryptoStore.updateGossipingRequestState(
-                        requestUserId = params.requestUserId,
-                        requestDeviceId = params.requestDeviceId,
-                        requestId = params.requestId,
-                        state = GossipingRequestState.FAILED_TO_ACCEPTED
-                )
-                Timber.e("no session with this device $requestingDeviceId, probably because there were no one-time keys.")
-            }
-        }
-
-        val payloadJson = mapOf(
-                "type" to EventType.SEND_SECRET,
-                "content" to toDeviceContent.toContent()
-        )
-
-        try {
-            val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo))
-            sendToDeviceMap.setObject(requestingUserId, requestingDeviceId, encodedPayload)
-        } catch (failure: Throwable) {
-            Timber.e("## Fail to encrypt gossip + ${failure.localizedMessage}")
-        }
-
-        cryptoStore.saveGossipingEvent(Event(
-                type = eventType,
-                content = toDeviceContent.toContent(),
-                senderId = credentials.userId
-        ).also {
-            it.ageLocalTs = clock.epochMillis()
-        })
-
-        try {
-            sendToDeviceTask.execute(
-                    SendToDeviceTask.Params(
-                            eventType = EventType.ENCRYPTED,
-                            contentMap = sendToDeviceMap,
-                            transactionId = txnId
-                    )
-            )
-            cryptoStore.updateGossipingRequestState(
-                    requestUserId = params.requestUserId,
-                    requestDeviceId = params.requestDeviceId,
-                    requestId = params.requestId,
-                    state = GossipingRequestState.ACCEPTED
-            )
-            return Result.success()
-        } catch (throwable: Throwable) {
-            return if (throwable.shouldBeRetried()) {
-                Result.retry()
-            } else {
-                cryptoStore.updateGossipingRequestState(
-                        requestUserId = params.requestUserId,
-                        requestDeviceId = params.requestDeviceId,
-                        requestId = params.requestId,
-                        state = GossipingRequestState.FAILED_TO_ACCEPTED
-                )
-                buildErrorResult(params, throwable.localizedMessage ?: "error")
-            }
-        }
-    }
-
-    override fun buildErrorParams(params: Params, message: String): Params {
-        return params.copy(lastFailureMessage = params.lastFailureMessage ?: message)
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt
index df29a494db..c728f1b682 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt
@@ -45,7 +45,7 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor(
 
     /**
      * We want to synchronize a bit here, because we are iterating to check existing olm session and
-     * also adding some
+     * also adding some.
      */
     suspend fun handle(devicesByUser: Map>, force: Boolean = false): MXUsersDevicesMap {
         ensureMutex.withLock {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt
index 86674b4ac5..22c4e59b18 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/actions/MegolmSessionDataImporter.kt
@@ -17,12 +17,13 @@
 package org.matrix.android.sdk.internal.crypto.actions
 
 import androidx.annotation.WorkerThread
+import org.matrix.android.sdk.api.extensions.tryOrNull
 import org.matrix.android.sdk.api.listeners.ProgressListener
+import org.matrix.android.sdk.api.logger.LoggerTag
 import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
 import org.matrix.android.sdk.internal.crypto.MXOlmDevice
 import org.matrix.android.sdk.internal.crypto.MegolmSessionData
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
 import org.matrix.android.sdk.internal.crypto.RoomDecryptorProvider
 import org.matrix.android.sdk.internal.crypto.algorithms.megolm.MXMegolmDecryption
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
@@ -30,12 +31,13 @@ import org.matrix.android.sdk.internal.util.time.Clock
 import timber.log.Timber
 import javax.inject.Inject
 
-internal class MegolmSessionDataImporter @Inject constructor(
-        private val olmDevice: MXOlmDevice,
-        private val roomDecryptorProvider: RoomDecryptorProvider,
-        private val outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        private val cryptoStore: IMXCryptoStore,
-        private val clock: Clock,
+private val loggerTag = LoggerTag("MegolmSessionDataImporter", LoggerTag.CRYPTO)
+
+internal class MegolmSessionDataImporter @Inject constructor(private val olmDevice: MXOlmDevice,
+                                                             private val roomDecryptorProvider: RoomDecryptorProvider,
+                                                             private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
+                                                             private val cryptoStore: IMXCryptoStore,
+                                                             private val clock: Clock,
 ) {
 
     /**
@@ -66,19 +68,23 @@ internal class MegolmSessionDataImporter @Inject constructor(
             if (null != decrypting) {
                 try {
                     val sessionId = megolmSessionData.sessionId
-                    Timber.v("## importRoomKeys retrieve senderKey " + megolmSessionData.senderKey + " sessionId " + sessionId)
+                    Timber.tag(loggerTag.value).v("## importRoomKeys retrieve senderKey ${megolmSessionData.senderKey} sessionId $sessionId")
 
                     totalNumbersOfImportedKeys++
 
                     // cancel any outstanding room key requests for this session
-                    val roomKeyRequestBody = RoomKeyRequestBody(
-                            algorithm = megolmSessionData.algorithm,
-                            roomId = megolmSessionData.roomId,
-                            senderKey = megolmSessionData.senderKey,
-                            sessionId = megolmSessionData.sessionId
-                    )
 
-                    outgoingGossipingRequestManager.cancelRoomKeyRequest(roomKeyRequestBody)
+                    Timber.tag(loggerTag.value).d("Imported megolm session $sessionId from backup=$fromBackup in ${megolmSessionData.roomId}")
+                    outgoingKeyRequestManager.postCancelRequestForSessionIfNeeded(
+                            megolmSessionData.sessionId ?: "",
+                            megolmSessionData.roomId ?: "",
+                            megolmSessionData.senderKey ?: "",
+                            tryOrNull {
+                                olmInboundGroupSessionWrappers
+                                        .firstOrNull { it.olmInboundGroupSession?.sessionIdentifier() == megolmSessionData.sessionId }
+                                        ?.firstKnownIndex?.toInt()
+                            } ?: 0
+                    )
 
                     // Have another go at decrypting events sent with this session
                     when (decrypting) {
@@ -87,7 +93,7 @@ internal class MegolmSessionDataImporter @Inject constructor(
                         }
                     }
                 } catch (e: Exception) {
-                    Timber.e(e, "## importRoomKeys() : onNewSession failed")
+                    Timber.tag(loggerTag.value).e(e, "## importRoomKeys() : onNewSession failed")
                 }
             }
 
@@ -109,7 +115,7 @@ internal class MegolmSessionDataImporter @Inject constructor(
 
         val t1 = clock.epochMillis()
 
-        Timber.v("## importMegolmSessionsData : sessions import " + (t1 - t0) + " ms (" + megolmSessionsData.size + " sessions)")
+        Timber.tag(loggerTag.value).v("## importMegolmSessionsData : sessions import " + (t1 - t0) + " ms (" + megolmSessionsData.size + " sessions)")
 
         return ImportRoomKeysResult(totalNumbersOfKeys, totalNumbersOfImportedKeys)
     }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXDecrypting.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXDecrypting.kt
index 2ea4e1dd29..34006ecfde 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXDecrypting.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXDecrypting.kt
@@ -17,19 +17,17 @@
 package org.matrix.android.sdk.internal.crypto.algorithms
 
 import org.matrix.android.sdk.api.session.crypto.MXCryptoError
-import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.IncomingSecretShareRequest
 import org.matrix.android.sdk.api.session.crypto.model.MXEventDecryptionResult
 import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.internal.crypto.keysbackup.DefaultKeysBackupService
 
 /**
- * An interface for decrypting data
+ * An interface for decrypting data.
  */
 internal interface IMXDecrypting {
 
     /**
-     * Decrypt an event
+     * Decrypt an event.
      *
      * @param event    the raw event.
      * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack.
@@ -44,23 +42,4 @@ internal interface IMXDecrypting {
      * @param event the key event.
      */
     fun onRoomKeyEvent(event: Event, defaultKeysBackupService: DefaultKeysBackupService) {}
-
-    /**
-     * Determine if we have the keys necessary to respond to a room key request
-     *
-     * @param request keyRequest
-     * @return true if we have the keys and could (theoretically) share
-     */
-    fun hasKeysForKeyRequest(request: IncomingRoomKeyRequest): Boolean = false
-
-    /**
-     * Send the response to a room key request.
-     *
-     * @param request keyRequest
-     */
-    fun shareKeysWithDevice(request: IncomingRoomKeyRequest) {}
-
-    fun shareSecretWithDevice(request: IncomingSecretShareRequest, secretValue: String) {}
-
-    fun requestKeysForEvent(event: Event, withHeld: Boolean)
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXEncrypting.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXEncrypting.kt
index 5294429198..1d84120208 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXEncrypting.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXEncrypting.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.crypto.algorithms
 import org.matrix.android.sdk.api.session.events.model.Content
 
 /**
- * An interface for encrypting data
+ * An interface for encrypting data.
  */
 internal interface IMXEncrypting {
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt
index 8ba4f6b56b..8321b73b75 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt
@@ -17,51 +17,32 @@
 package org.matrix.android.sdk.internal.crypto.algorithms.megolm
 
 import dagger.Lazy
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.sync.withLock
-import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
 import org.matrix.android.sdk.api.logger.LoggerTag
 import org.matrix.android.sdk.api.session.crypto.MXCryptoError
 import org.matrix.android.sdk.api.session.crypto.NewSessionListener
 import org.matrix.android.sdk.api.session.crypto.model.ForwardedRoomKeyContent
-import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
 import org.matrix.android.sdk.api.session.crypto.model.MXEventDecryptionResult
-import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
 import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.events.model.EventType
 import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventContent
 import org.matrix.android.sdk.api.session.events.model.content.RoomKeyContent
-import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
 import org.matrix.android.sdk.api.session.events.model.toModel
-import org.matrix.android.sdk.internal.crypto.DeviceListManager
 import org.matrix.android.sdk.internal.crypto.MXOlmDevice
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
-import org.matrix.android.sdk.internal.crypto.actions.EnsureOlmSessionsForDevicesAction
-import org.matrix.android.sdk.internal.crypto.actions.MessageEncrypter
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
 import org.matrix.android.sdk.internal.crypto.algorithms.IMXDecrypting
-import org.matrix.android.sdk.internal.crypto.algorithms.IMXWithHeldExtension
 import org.matrix.android.sdk.internal.crypto.keysbackup.DefaultKeysBackupService
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
-import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
 import org.matrix.android.sdk.internal.session.StreamEventsManager
 import timber.log.Timber
 
 private val loggerTag = LoggerTag("MXMegolmDecryption", LoggerTag.CRYPTO)
 
-internal class MXMegolmDecryption(private val userId: String,
-                                  private val olmDevice: MXOlmDevice,
-                                  private val deviceListManager: DeviceListManager,
-                                  private val outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-                                  private val messageEncrypter: MessageEncrypter,
-                                  private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction,
-                                  private val cryptoStore: IMXCryptoStore,
-                                  private val sendToDeviceTask: SendToDeviceTask,
-                                  private val coroutineDispatchers: MatrixCoroutineDispatchers,
-                                  private val cryptoCoroutineScope: CoroutineScope,
-                                  private val liveEventManager: Lazy
-) : IMXDecrypting, IMXWithHeldExtension {
+internal class MXMegolmDecryption(
+        private val olmDevice: MXOlmDevice,
+        private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        private val cryptoStore: IMXCryptoStore,
+        private val liveEventManager: Lazy
+) : IMXDecrypting {
 
     var newSessionListener: NewSessionListener? = null
 
@@ -73,10 +54,7 @@ internal class MXMegolmDecryption(private val userId: String,
 
     @Throws(MXCryptoError::class)
     override suspend fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult {
-        // If cross signing is enabled, we don't send request until the keys are trusted
-        // There could be a race effect here when xsigning is enabled, we should ensure that keys was downloaded once
-        val requestOnFail = cryptoStore.getMyCrossSigningInfo()?.isTrusted() == true
-        return decryptEvent(event, timeline, requestOnFail)
+        return decryptEvent(event, timeline, true)
     }
 
     @Throws(MXCryptoError::class)
@@ -126,13 +104,14 @@ internal class MXMegolmDecryption(private val userId: String,
                             if (throwable is MXCryptoError.OlmError) {
                                 // TODO Check the value of .message
                                 if (throwable.olmException.message == "UNKNOWN_MESSAGE_INDEX") {
-                                    // addEventToPendingList(event, timeline)
-                                    // The session might has been partially withheld (and only pass ratcheted)
+                                    // So we know that session, but it's ratcheted and we can't decrypt at that index
+
+                                    if (requestKeysOnFail) {
+                                        requestKeysForEvent(event)
+                                    }
+                                    // Check if partially withheld
                                     val withHeldInfo = cryptoStore.getWithHeldMegolmSession(event.roomId, encryptedEventContent.sessionId)
                                     if (withHeldInfo != null) {
-                                        if (requestKeysOnFail) {
-                                            requestKeysForEvent(event, true)
-                                        }
                                         // Encapsulate as withHeld exception
                                         throw MXCryptoError.Base(
                                                 MXCryptoError.ErrorType.KEYS_WITHHELD,
@@ -141,10 +120,6 @@ internal class MXMegolmDecryption(private val userId: String,
                                         )
                                     }
 
-                                    if (requestKeysOnFail) {
-                                        requestKeysForEvent(event, false)
-                                    }
-
                                     throw MXCryptoError.Base(
                                             MXCryptoError.ErrorType.UNKNOWN_MESSAGE_INDEX,
                                             "UNKNOWN_MESSAGE_INDEX",
@@ -162,27 +137,22 @@ internal class MXMegolmDecryption(private val userId: String,
                                 )
                             }
                             if (throwable is MXCryptoError.Base) {
-                                if (
-                                /** if the session is unknown*/
-                                        throwable.errorType == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID
-                                ) {
+                                if (throwable.errorType == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) {
+                                    // Check if it was withheld by sender to enrich error code
                                     val withHeldInfo = cryptoStore.getWithHeldMegolmSession(event.roomId, encryptedEventContent.sessionId)
                                     if (withHeldInfo != null) {
                                         if (requestKeysOnFail) {
-                                            requestKeysForEvent(event, true)
+                                            requestKeysForEvent(event)
                                         }
                                         // Encapsulate as withHeld exception
                                         throw MXCryptoError.Base(
                                                 MXCryptoError.ErrorType.KEYS_WITHHELD,
                                                 withHeldInfo.code?.value ?: "",
-                                                withHeldInfo.reason
-                                        )
-                                    } else {
-                                        // This is un-used in Matrix Android SDK2, not sure if needed
-                                        // addEventToPendingList(event, timeline)
-                                        if (requestKeysOnFail) {
-                                            requestKeysForEvent(event, false)
-                                        }
+                                                withHeldInfo.reason)
+                                    }
+
+                                    if (requestKeysOnFail) {
+                                        requestKeysForEvent(event)
                                     }
                                 }
                             }
@@ -198,55 +168,10 @@ internal class MXMegolmDecryption(private val userId: String,
      *
      * @param event the event
      */
-    override fun requestKeysForEvent(event: Event, withHeld: Boolean) {
-        val sender = event.senderId ?: return
-        val encryptedEventContent = event.content.toModel()
-        val senderDevice = encryptedEventContent?.deviceId ?: return
-
-        val recipients = if (event.senderId == userId || withHeld) {
-            mapOf(
-                    userId to listOf("*")
-            )
-        } else {
-            // for the case where you share the key with a device that has a broken olm session
-            // The other user might Re-shares a megolm session key with devices if the key has already been
-            // sent to them.
-            mapOf(
-                    userId to listOf("*"),
-                    sender to listOf(senderDevice)
-            )
-        }
-
-        val requestBody = RoomKeyRequestBody(
-                roomId = event.roomId,
-                algorithm = encryptedEventContent.algorithm,
-                senderKey = encryptedEventContent.senderKey,
-                sessionId = encryptedEventContent.sessionId
-        )
-
-        outgoingGossipingRequestManager.sendRoomKeyRequest(requestBody, recipients)
+    private fun requestKeysForEvent(event: Event) {
+        outgoingKeyRequestManager.requestKeyForEvent(event, false)
     }
 
-//    /**
-//     * Add an event to the list of those we couldn't decrypt the first time we
-//     * saw them.
-//     *
-//     * @param event      the event to try to decrypt later
-//     * @param timelineId the timeline identifier
-//     */
-//    private fun addEventToPendingList(event: Event, timelineId: String) {
-//        val encryptedEventContent = event.content.toModel() ?: return
-//        val pendingEventsKey = "${encryptedEventContent.senderKey}|${encryptedEventContent.sessionId}"
-//
-//        val timeline = pendingEvents.getOrPut(pendingEventsKey) { HashMap() }
-//        val events = timeline.getOrPut(timelineId) { ArrayList() }
-//
-//        if (event !in events) {
-//            Timber.v("## CRYPTO | addEventToPendingList() : add Event ${event.eventId} in room id ${event.roomId}")
-//            events.add(event)
-//        }
-//    }
-
     /**
      * Handle a key event.
      *
@@ -266,6 +191,11 @@ internal class MXMegolmDecryption(private val userId: String,
             return
         }
         if (event.getClearType() == EventType.FORWARDED_ROOM_KEY) {
+            if (!cryptoStore.isKeyGossipingEnabled()) {
+                Timber.tag(loggerTag.value)
+                        .i("onRoomKeyEvent(), ignore forward adding as per crypto config : ${roomKeyContent.roomId}|${roomKeyContent.sessionId}")
+                return
+            }
             Timber.tag(loggerTag.value).i("onRoomKeyEvent(), forward adding key : ${roomKeyContent.roomId}|${roomKeyContent.sessionId}")
             val forwardedRoomKeyContent = event.getClearContent().toModel()
                     ?: return
@@ -306,7 +236,7 @@ internal class MXMegolmDecryption(private val userId: String,
         }
 
         Timber.tag(loggerTag.value).i("onRoomKeyEvent addInboundGroupSession ${roomKeyContent.sessionId}")
-        val added = olmDevice.addInboundGroupSession(
+        val addSessionResult = olmDevice.addInboundGroupSession(
                 roomKeyContent.sessionId,
                 roomKeyContent.sessionKey,
                 roomKeyContent.roomId,
@@ -316,24 +246,53 @@ internal class MXMegolmDecryption(private val userId: String,
                 exportFormat
         )
 
-        if (added) {
+        when (addSessionResult) {
+            is MXOlmDevice.AddSessionResult.Imported               -> addSessionResult.ratchetIndex
+            is MXOlmDevice.AddSessionResult.NotImportedHigherIndex -> addSessionResult.newIndex
+            else                                                   -> null
+        }?.let { index ->
+            if (event.getClearType() == EventType.FORWARDED_ROOM_KEY) {
+                val fromDevice = (event.content?.get("sender_key") as? String)?.let { senderDeviceIdentityKey ->
+                    cryptoStore.getUserDeviceList(event.senderId ?: "")
+                            ?.firstOrNull {
+                                it.identityKey() == senderDeviceIdentityKey
+                            }
+                }?.deviceId
+
+                outgoingKeyRequestManager.onRoomKeyForwarded(
+                        sessionId = roomKeyContent.sessionId,
+                        algorithm = roomKeyContent.algorithm ?: "",
+                        roomId = roomKeyContent.roomId,
+                        senderKey = senderKey,
+                        fromIndex = index,
+                        fromDevice = fromDevice,
+                        event = event)
+
+                cryptoStore.saveIncomingForwardKeyAuditTrail(
+                        roomId = roomKeyContent.roomId,
+                        sessionId = roomKeyContent.sessionId,
+                        senderKey = senderKey,
+                        algorithm = roomKeyContent.algorithm ?: "",
+                        userId = event.senderId ?: "",
+                        deviceId = fromDevice ?: "",
+                        chainIndex = index.toLong())
+
+                // The index is used to decide if we cancel sent request or if we wait for a better key
+                outgoingKeyRequestManager.postCancelRequestForSessionIfNeeded(roomKeyContent.sessionId, roomKeyContent.roomId, senderKey, index)
+            }
+        }
+
+        if (addSessionResult is MXOlmDevice.AddSessionResult.Imported) {
+            Timber.tag(loggerTag.value)
+                    .d("onRoomKeyEvent(${event.getClearType()}) : Added megolm session ${roomKeyContent.sessionId} in ${roomKeyContent.roomId}")
             defaultKeysBackupService.maybeBackupKeys()
 
-            val content = RoomKeyRequestBody(
-                    algorithm = roomKeyContent.algorithm,
-                    roomId = roomKeyContent.roomId,
-                    sessionId = roomKeyContent.sessionId,
-                    senderKey = senderKey
-            )
-
-            outgoingGossipingRequestManager.cancelRoomKeyRequest(content)
-
             onNewSession(roomKeyContent.roomId, senderKey, roomKeyContent.sessionId)
         }
     }
 
     /**
-     * Check if the some messages can be decrypted with a new session
+     * Check if the some messages can be decrypted with a new session.
      *
      * @param roomId the room id where the new Megolm session has been created for, may be null when importing from external sessions
      * @param senderKey the session sender key
@@ -343,77 +302,4 @@ internal class MXMegolmDecryption(private val userId: String,
         Timber.tag(loggerTag.value).v("ON NEW SESSION $sessionId - $senderKey")
         newSessionListener?.onNewSession(roomId, senderKey, sessionId)
     }
-
-    override fun hasKeysForKeyRequest(request: IncomingRoomKeyRequest): Boolean {
-        val roomId = request.requestBody?.roomId ?: return false
-        val senderKey = request.requestBody.senderKey ?: return false
-        val sessionId = request.requestBody.sessionId ?: return false
-        return olmDevice.hasInboundSessionKeys(roomId, senderKey, sessionId)
-    }
-
-    override fun shareKeysWithDevice(request: IncomingRoomKeyRequest) {
-        // sanity checks
-        if (request.requestBody == null) {
-            return
-        }
-        val userId = request.userId ?: return
-
-        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-            val body = request.requestBody
-            val sessionHolder = try {
-                olmDevice.getInboundGroupSession(body.sessionId, body.senderKey, body.roomId)
-            } catch (failure: Throwable) {
-                Timber.tag(loggerTag.value).e(failure, "shareKeysWithDevice: failed to get session for request $body")
-                return@launch
-            }
-
-            val export = sessionHolder.mutex.withLock {
-                sessionHolder.wrapper.exportKeys()
-            } ?: return@launch Unit.also {
-                Timber.tag(loggerTag.value).e("shareKeysWithDevice: failed to export group session ${body.sessionId}")
-            }
-
-            runCatching { deviceListManager.downloadKeys(listOf(userId), false) }
-                    .mapCatching {
-                        val deviceId = request.deviceId
-                        val deviceInfo = cryptoStore.getUserDevice(userId, deviceId ?: "")
-                        if (deviceInfo == null) {
-                            throw RuntimeException()
-                        } else {
-                            val devicesByUser = mapOf(userId to listOf(deviceInfo))
-                            val usersDeviceMap = ensureOlmSessionsForDevicesAction.handle(devicesByUser)
-                            val olmSessionResult = usersDeviceMap.getObject(userId, deviceId)
-                            if (olmSessionResult?.sessionId == null) {
-                                // no session with this device, probably because there
-                                // were no one-time keys.
-                                Timber.tag(loggerTag.value).e("no session with this device $deviceId, probably because there were no one-time keys.")
-                                return@mapCatching
-                            }
-                            Timber.tag(loggerTag.value).i("shareKeysWithDevice() : sharing session ${body.sessionId} with device $userId:$deviceId")
-
-                            val payloadJson = mapOf(
-                                    "type" to EventType.FORWARDED_ROOM_KEY,
-                                    "content" to export
-                            )
-
-                            val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo))
-                            val sendToDeviceMap = MXUsersDevicesMap()
-                            sendToDeviceMap.setObject(userId, deviceId, encodedPayload)
-                            Timber.tag(loggerTag.value).i("shareKeysWithDevice() : sending ${body.sessionId} to $userId:$deviceId")
-                            val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap)
-                            try {
-                                sendToDeviceTask.execute(sendToDeviceParams)
-                            } catch (failure: Throwable) {
-                                Timber.tag(loggerTag.value).e(failure, "shareKeysWithDevice() : Failed to send ${body.sessionId} to $userId:$deviceId")
-                            }
-                        }
-                    }
-        }
-    }
-
-    override fun onRoomKeyWithHeldEvent(withHeldInfo: RoomKeyWithHeldContent) {
-        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-            cryptoStore.addWithHeldMegolmSession(withHeldInfo)
-        }
-    }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt
index 8ad9f191d7..096773a959 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmDecryptionFactory.kt
@@ -17,46 +17,24 @@
 package org.matrix.android.sdk.internal.crypto.algorithms.megolm
 
 import dagger.Lazy
-import kotlinx.coroutines.CoroutineScope
-import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
-import org.matrix.android.sdk.internal.crypto.DeviceListManager
 import org.matrix.android.sdk.internal.crypto.MXOlmDevice
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
-import org.matrix.android.sdk.internal.crypto.actions.EnsureOlmSessionsForDevicesAction
-import org.matrix.android.sdk.internal.crypto.actions.MessageEncrypter
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
-import org.matrix.android.sdk.internal.crypto.tasks.SendToDeviceTask
-import org.matrix.android.sdk.internal.di.UserId
 import org.matrix.android.sdk.internal.session.StreamEventsManager
 import javax.inject.Inject
 
 internal class MXMegolmDecryptionFactory @Inject constructor(
-        @UserId private val userId: String,
         private val olmDevice: MXOlmDevice,
-        private val deviceListManager: DeviceListManager,
-        private val outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        private val messageEncrypter: MessageEncrypter,
-        private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction,
+        private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
         private val cryptoStore: IMXCryptoStore,
-        private val sendToDeviceTask: SendToDeviceTask,
-        private val coroutineDispatchers: MatrixCoroutineDispatchers,
-        private val cryptoCoroutineScope: CoroutineScope,
         private val eventsManager: Lazy
 ) {
 
     fun create(): MXMegolmDecryption {
         return MXMegolmDecryption(
-                userId,
                 olmDevice,
-                deviceListManager,
-                outgoingGossipingRequestManager,
-                messageEncrypter,
-                ensureOlmSessionsForDevicesAction,
+                outgoingKeyRequestManager,
                 cryptoStore,
-                sendToDeviceTask,
-                coroutineDispatchers,
-                cryptoCoroutineScope,
-                eventsManager
-        )
+                eventsManager)
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt
index 4ceef4fa5c..79e907945f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt
@@ -28,7 +28,6 @@ import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
 import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
 import org.matrix.android.sdk.api.session.crypto.model.forEach
 import org.matrix.android.sdk.api.session.events.model.Content
-import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.events.model.EventType
 import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
 import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode
@@ -80,7 +79,7 @@ internal class MXMegolmEncryption(
     }
 
     // Default rotation periods
-    // TODO: Make it configurable via parameters
+    // TODO Make it configurable via parameters
     // Session rotation periods
     private var sessionRotationPeriodMsgs: Int = 100
     private var sessionRotationPeriodMs: Int = 7 * 24 * 3600 * 1000
@@ -161,7 +160,7 @@ internal class MXMegolmEncryption(
     }
 
     /**
-     * Ensure the outbound session
+     * Ensure the outbound session.
      *
      * @param devicesInRoom the devices list
      */
@@ -197,7 +196,7 @@ internal class MXMegolmEncryption(
     }
 
     /**
-     * Share the device key to a list of users
+     * Share the device key to a list of users.
      *
      * @param session        the session info
      * @param devicesByUsers the devices map
@@ -226,7 +225,7 @@ internal class MXMegolmEncryption(
     }
 
     /**
-     * Share the device keys of a an user
+     * Share the device keys of a an user.
      *
      * @param session       the session info
      * @param devicesByUser the devices map
@@ -285,25 +284,14 @@ internal class MXMegolmEncryption(
         // attempted to share with) rather than the contentMap (those we did
         // share with), because we don't want to try to claim a one-time-key
         // for dead devices on every message.
-        val gossipingEventBuffer = arrayListOf()
-        for ((userId, devicesToShareWith) in devicesByUser) {
+        for ((_, devicesToShareWith) in devicesByUser) {
             for (deviceInfo in devicesToShareWith) {
                 session.sharedWithHelper.markedSessionAsShared(deviceInfo, chainIndex)
-                gossipingEventBuffer.add(
-                        Event(
-                                type = EventType.ROOM_KEY,
-                                senderId = myUserId,
-                                content = submap.apply {
-                                    this["session_key"] = ""
-                                    // we add a fake key for trail
-                                    this["_dest"] = "$userId|${deviceInfo.deviceId}"
-                                }
-                        ))
+                // XXX is it needed to add it to the audit trail?
+                // For now decided that no, we are more interested by forward trail
             }
         }
 
-        cryptoStore.saveGossipingEvents(gossipingEventBuffer)
-
         if (haveTargets) {
             t0 = clock.epochMillis()
             Timber.tag(loggerTag.value).i("shareUserDevicesKey() ${session.sessionId} : has target")
@@ -346,7 +334,8 @@ internal class MXMegolmEncryption(
                 senderKey = senderKey,
                 algorithm = MXCRYPTO_ALGORITHM_MEGOLM,
                 sessionId = sessionId,
-                codeString = code.value
+                codeString = code.value,
+                fromDevice = myDeviceId
         )
         val params = SendToDeviceTask.Params(
                 EventType.ROOM_KEY_WITHHELD,
@@ -367,7 +356,7 @@ internal class MXMegolmEncryption(
     }
 
     /**
-     * process the pending encryptions
+     * process the pending encryptions.
      */
     private fun encryptContent(session: MXOutboundSessionInfo, eventType: String, eventContent: Content): Content {
         // Everything is in place, encrypt all pending events
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt
index 13eeefd1a6..1e66fe84c9 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmDecryption.kt
@@ -265,8 +265,4 @@ internal class MXOlmDecryption(
 
         return res["payload"]
     }
-
-    override fun requestKeysForEvent(event: Event, withHeld: Boolean) {
-        // nop
-    }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt
index c842c54041..3c9706abe1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/olm/MXOlmEncryption.kt
@@ -38,7 +38,7 @@ internal class MXOlmEncryption(
     override suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List): Content {
         // pick the list of recipients based on the membership list.
         //
-        // TODO: there is a race condition here! What if a new user turns up
+        // TODO there is a race condition here! What if a new user turns up
         ensureSession(userIds)
         val deviceInfos = ArrayList()
         for (userId in userIds) {
@@ -68,7 +68,7 @@ internal class MXOlmEncryption(
     }
 
     /**
-     * Ensure that the session
+     * Ensure that the session.
      *
      * @param users    the user ids list
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/EncryptionResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/EncryptionResult.kt
index 80090cf4a8..95254bd679 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/EncryptionResult.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/EncryptionResult.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.crypto.attachments
 import org.matrix.android.sdk.api.session.crypto.model.EncryptedFileInfo
 
 /**
- * Define the result of an encryption file
+ * Define the result of an encryption file.
  */
 internal data class EncryptionResult(
         val encryptedFileInfo: EncryptedFileInfo,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt
index 65bbb0c412..b4cbd15109 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/attachments/MXEncryptedAttachments.kt
@@ -227,7 +227,7 @@ internal object MXEncryptedAttachments {
     }
 
     /**
-     * Decrypt an attachment
+     * Decrypt an attachment.
      *
      * @param attachmentStream the attachment stream. Will be closed after this method call.
      * @param elementToDecrypt the elementToDecrypt info
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/CrossSigningOlm.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/CrossSigningOlm.kt
new file mode 100644
index 0000000000..4fa355cd2a
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/CrossSigningOlm.kt
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto.crosssigning
+
+import org.matrix.android.sdk.api.util.JsonDict
+import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
+import org.matrix.android.sdk.internal.session.SessionScope
+import org.matrix.android.sdk.internal.util.JsonCanonicalizer
+import org.matrix.olm.OlmPkSigning
+import org.matrix.olm.OlmUtility
+import javax.inject.Inject
+
+/**
+ * Holds the OlmPkSigning for cross signing.
+ * Can be injected without having to get the full cross signing service
+ */
+@SessionScope
+internal class CrossSigningOlm @Inject constructor(
+        private val cryptoStore: IMXCryptoStore,
+) {
+
+    enum class KeyType {
+        SELF,
+        USER,
+        MASTER
+    }
+
+    var olmUtility: OlmUtility = OlmUtility()
+
+    var masterPkSigning: OlmPkSigning? = null
+    var userPkSigning: OlmPkSigning? = null
+    var selfSigningPkSigning: OlmPkSigning? = null
+
+    fun release() {
+        olmUtility.releaseUtility()
+        listOf(masterPkSigning, userPkSigning, selfSigningPkSigning).forEach { it?.releaseSigning() }
+    }
+
+    fun signObject(type: KeyType, strToSign: String): Map {
+        val myKeys = cryptoStore.getMyCrossSigningInfo()
+        val pubKey = when (type) {
+            KeyType.SELF   -> myKeys?.selfSigningKey()
+            KeyType.USER   -> myKeys?.userKey()
+            KeyType.MASTER -> myKeys?.masterKey()
+        }?.unpaddedBase64PublicKey
+        val pkSigning = when (type) {
+            KeyType.SELF   -> selfSigningPkSigning
+            KeyType.USER   -> userPkSigning
+            KeyType.MASTER -> masterPkSigning
+        }
+        if (pubKey == null || pkSigning == null) {
+            throw Throwable("Cannot sign from this account, public and/or privateKey Unknown $type|$pkSigning")
+        }
+        val signature = pkSigning.sign(strToSign)
+        return mapOf(
+                "ed25519:$pubKey" to signature
+        )
+    }
+
+    fun verifySignature(type: KeyType, signable: JsonDict, signatures: Map>) {
+        val myKeys = cryptoStore.getMyCrossSigningInfo()
+                ?: throw NoSuchElementException("Cross Signing not configured")
+        val myUserID = myKeys.userId
+        val pubKey = when (type) {
+            KeyType.SELF   -> myKeys.selfSigningKey()
+            KeyType.USER   -> myKeys.userKey()
+            KeyType.MASTER -> myKeys.masterKey()
+        }?.unpaddedBase64PublicKey ?: throw NoSuchElementException("Cross Signing not configured")
+        val signaturesMadeByMyKey = signatures[myUserID] // Signatures made by me
+                ?.get("ed25519:$pubKey")
+
+        if (signaturesMadeByMyKey.isNullOrBlank()) {
+            throw IllegalArgumentException("Not signed with my key $type")
+        }
+
+        // Check that Alice USK signature of Bob MSK is valid
+        olmUtility.verifyEd25519Signature(signaturesMadeByMyKey, pubKey, JsonCanonicalizer.getCanonicalJson(Map::class.java, signable))
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt
index e2887e5826..6c198abc2e 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/crosssigning/DefaultCrossSigningService.kt
@@ -38,6 +38,7 @@ import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
 import org.matrix.android.sdk.api.util.Optional
 import org.matrix.android.sdk.api.util.fromBase64
 import org.matrix.android.sdk.internal.crypto.DeviceListManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
 import org.matrix.android.sdk.internal.crypto.model.rest.UploadSignatureQueryBuilder
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
 import org.matrix.android.sdk.internal.crypto.tasks.InitializeCrossSigningTask
@@ -53,7 +54,6 @@ import org.matrix.android.sdk.internal.util.JsonCanonicalizer
 import org.matrix.android.sdk.internal.util.logLimit
 import org.matrix.android.sdk.internal.worker.WorkerParamsFactory
 import org.matrix.olm.OlmPkSigning
-import org.matrix.olm.OlmUtility
 import timber.log.Timber
 import java.util.concurrent.TimeUnit
 import javax.inject.Inject
@@ -70,19 +70,14 @@ internal class DefaultCrossSigningService @Inject constructor(
         private val coroutineDispatchers: MatrixCoroutineDispatchers,
         private val cryptoCoroutineScope: CoroutineScope,
         private val workManagerProvider: WorkManagerProvider,
+        private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        private val crossSigningOlm: CrossSigningOlm,
         private val updateTrustWorkerDataRepository: UpdateTrustWorkerDataRepository
 ) : CrossSigningService,
         DeviceListManager.UserDevicesUpdateListener {
 
-    private var olmUtility: OlmUtility? = null
-
-    private var masterPkSigning: OlmPkSigning? = null
-    private var userPkSigning: OlmPkSigning? = null
-    private var selfSigningPkSigning: OlmPkSigning? = null
-
     init {
         try {
-            olmUtility = OlmUtility()
 
             // Try to get stored keys if they exist
             cryptoStore.getMyCrossSigningInfo()?.let { mxCrossSigningInfo ->
@@ -95,7 +90,7 @@ internal class DefaultCrossSigningService @Inject constructor(
                             ?.let { privateKeySeed ->
                                 val pkSigning = OlmPkSigning()
                                 if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.masterKey()?.unpaddedBase64PublicKey) {
-                                    masterPkSigning = pkSigning
+                                    crossSigningOlm.masterPkSigning = pkSigning
                                     Timber.i("## CrossSigning - Loading master key success")
                                 } else {
                                     Timber.w("## CrossSigning - Public master key does not match the private key")
@@ -108,7 +103,7 @@ internal class DefaultCrossSigningService @Inject constructor(
                             ?.let { privateKeySeed ->
                                 val pkSigning = OlmPkSigning()
                                 if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.userKey()?.unpaddedBase64PublicKey) {
-                                    userPkSigning = pkSigning
+                                    crossSigningOlm.userPkSigning = pkSigning
                                     Timber.i("## CrossSigning - Loading User Signing key success")
                                 } else {
                                     Timber.w("## CrossSigning - Public User key does not match the private key")
@@ -121,7 +116,7 @@ internal class DefaultCrossSigningService @Inject constructor(
                             ?.let { privateKeySeed ->
                                 val pkSigning = OlmPkSigning()
                                 if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.selfSigningKey()?.unpaddedBase64PublicKey) {
-                                    selfSigningPkSigning = pkSigning
+                                    crossSigningOlm.selfSigningPkSigning = pkSigning
                                     Timber.i("## CrossSigning - Loading Self Signing key success")
                                 } else {
                                     Timber.w("## CrossSigning - Public Self Signing key does not match the private key")
@@ -143,8 +138,7 @@ internal class DefaultCrossSigningService @Inject constructor(
     }
 
     fun release() {
-        olmUtility?.releaseUtility()
-        listOf(masterPkSigning, userPkSigning, selfSigningPkSigning).forEach { it?.releaseSigning() }
+        crossSigningOlm.release()
         deviceListManager.removeListener(this)
     }
 
@@ -153,10 +147,10 @@ internal class DefaultCrossSigningService @Inject constructor(
     }
 
     /**
-     *   - Make 3 key pairs (MSK, USK, SSK)
-     *   - Save the private keys with proper security
-     *   - Sign the keys and upload them
-     *   - Sign the current device with SSK and sign MSK with device key (migration) and upload signatures
+     * - Make 3 key pairs (MSK, USK, SSK)
+     * - Save the private keys with proper security
+     * - Sign the keys and upload them
+     * - Sign the current device with SSK and sign MSK with device key (migration) and upload signatures.
      */
     override fun initializeCrossSigning(uiaInterceptor: UserInteractiveAuthInterceptor?, callback: MatrixCallback) {
         Timber.d("## CrossSigning  initializeCrossSigning")
@@ -177,9 +171,9 @@ internal class DefaultCrossSigningService @Inject constructor(
                     cryptoStore.setMyCrossSigningInfo(crossSigningInfo)
                     setUserKeysAsTrusted(userId, true)
                     cryptoStore.storePrivateKeysInfo(data.masterKeyPK, data.userKeyPK, data.selfSigningKeyPK)
-                    masterPkSigning = OlmPkSigning().apply { initWithSeed(data.masterKeyPK.fromBase64()) }
-                    userPkSigning = OlmPkSigning().apply { initWithSeed(data.userKeyPK.fromBase64()) }
-                    selfSigningPkSigning = OlmPkSigning().apply { initWithSeed(data.selfSigningKeyPK.fromBase64()) }
+                    crossSigningOlm.masterPkSigning = OlmPkSigning().apply { initWithSeed(data.masterKeyPK.fromBase64()) }
+                    crossSigningOlm.userPkSigning = OlmPkSigning().apply { initWithSeed(data.userKeyPK.fromBase64()) }
+                    crossSigningOlm.selfSigningPkSigning = OlmPkSigning().apply { initWithSeed(data.selfSigningKeyPK.fromBase64()) }
 
                     callback.onSuccess(Unit)
                 }
@@ -198,8 +192,8 @@ internal class DefaultCrossSigningService @Inject constructor(
                     val pkSigning = OlmPkSigning()
                     try {
                         if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.masterKey()?.unpaddedBase64PublicKey) {
-                            masterPkSigning?.releaseSigning()
-                            masterPkSigning = pkSigning
+                            crossSigningOlm.masterPkSigning?.releaseSigning()
+                            crossSigningOlm.masterPkSigning = pkSigning
                             Timber.i("## CrossSigning - Loading MSK success")
                             cryptoStore.storeMSKPrivateKey(mskPrivateKey)
                             return
@@ -225,8 +219,8 @@ internal class DefaultCrossSigningService @Inject constructor(
                     val pkSigning = OlmPkSigning()
                     try {
                         if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.selfSigningKey()?.unpaddedBase64PublicKey) {
-                            selfSigningPkSigning?.releaseSigning()
-                            selfSigningPkSigning = pkSigning
+                            crossSigningOlm.selfSigningPkSigning?.releaseSigning()
+                            crossSigningOlm.selfSigningPkSigning = pkSigning
                             Timber.i("## CrossSigning - Loading SSK success")
                             cryptoStore.storeSSKPrivateKey(sskPrivateKey)
                             return
@@ -252,8 +246,8 @@ internal class DefaultCrossSigningService @Inject constructor(
                     val pkSigning = OlmPkSigning()
                     try {
                         if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.userKey()?.unpaddedBase64PublicKey) {
-                            userPkSigning?.releaseSigning()
-                            userPkSigning = pkSigning
+                            crossSigningOlm.userPkSigning?.releaseSigning()
+                            crossSigningOlm.userPkSigning = pkSigning
                             Timber.i("## CrossSigning - Loading USK success")
                             cryptoStore.storeUSKPrivateKey(uskPrivateKey)
                             return
@@ -282,8 +276,8 @@ internal class DefaultCrossSigningService @Inject constructor(
                     val pkSigning = OlmPkSigning()
                     try {
                         if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.masterKey()?.unpaddedBase64PublicKey) {
-                            masterPkSigning?.releaseSigning()
-                            masterPkSigning = pkSigning
+                            crossSigningOlm.masterPkSigning?.releaseSigning()
+                            crossSigningOlm.masterPkSigning = pkSigning
                             masterKeyIsTrusted = true
                             Timber.i("## CrossSigning - Loading master key success")
                         } else {
@@ -299,8 +293,8 @@ internal class DefaultCrossSigningService @Inject constructor(
                     val pkSigning = OlmPkSigning()
                     try {
                         if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.userKey()?.unpaddedBase64PublicKey) {
-                            userPkSigning?.releaseSigning()
-                            userPkSigning = pkSigning
+                            crossSigningOlm.userPkSigning?.releaseSigning()
+                            crossSigningOlm.userPkSigning = pkSigning
                             userKeyIsTrusted = true
                             Timber.i("## CrossSigning - Loading master key success")
                         } else {
@@ -316,8 +310,8 @@ internal class DefaultCrossSigningService @Inject constructor(
                     val pkSigning = OlmPkSigning()
                     try {
                         if (pkSigning.initWithSeed(privateKeySeed) == mxCrossSigningInfo.selfSigningKey()?.unpaddedBase64PublicKey) {
-                            selfSigningPkSigning?.releaseSigning()
-                            selfSigningPkSigning = pkSigning
+                            crossSigningOlm.selfSigningPkSigning?.releaseSigning()
+                            crossSigningOlm.selfSigningPkSigning = pkSigning
                             selfSignedKeyIsTrusted = true
                             Timber.i("## CrossSigning - Loading master key success")
                         } else {
@@ -353,6 +347,7 @@ internal class DefaultCrossSigningService @Inject constructor(
      *     │                      │
      *     │                      │
      *     └──▶ USK   ────────────┘
+     * .
      */
     override fun isUserTrusted(otherUserId: String): Boolean {
         return cryptoStore.getCrossSigningInfo(userId)?.isTrusted() == true
@@ -363,7 +358,7 @@ internal class DefaultCrossSigningService @Inject constructor(
     }
 
     /**
-     * Will not force a download of the key, but will verify signatures trust chain
+     * Will not force a download of the key, but will verify signatures trust chain.
      */
     override fun checkUserTrust(otherUserId: String): UserTrustResult {
         Timber.v("## CrossSigning  checkUserTrust for $otherUserId")
@@ -405,7 +400,11 @@ internal class DefaultCrossSigningService @Inject constructor(
 
         // Check that Alice USK signature of Bob MSK is valid
         try {
-            olmUtility!!.verifyEd25519Signature(masterKeySignaturesMadeByMyUserKey, myUserKey.unpaddedBase64PublicKey, otherMasterKey.canonicalSignable())
+            crossSigningOlm.olmUtility.verifyEd25519Signature(
+                    masterKeySignaturesMadeByMyUserKey,
+                    myUserKey.unpaddedBase64PublicKey,
+                    otherMasterKey.canonicalSignable()
+            )
         } catch (failure: Throwable) {
             return UserTrustResult.InvalidSignature(myUserKey, masterKeySignaturesMadeByMyUserKey)
         }
@@ -459,7 +458,7 @@ internal class DefaultCrossSigningService @Inject constructor(
                 if (potentialDevice != null && potentialDevice.isVerified) {
                     // Check signature validity?
                     try {
-                        olmUtility?.verifyEd25519Signature(value, potentialDevice.fingerprint(), myMasterKey.canonicalSignable())
+                        crossSigningOlm.olmUtility.verifyEd25519Signature(value, potentialDevice.fingerprint(), myMasterKey.canonicalSignable())
                         isMaterKeyTrusted = true
                         return@forEach
                     } catch (failure: Throwable) {
@@ -488,7 +487,11 @@ internal class DefaultCrossSigningService @Inject constructor(
 
         // Check that Alice USK signature of Alice MSK is valid
         try {
-            olmUtility!!.verifyEd25519Signature(userKeySignaturesMadeByMyMasterKey, myMasterKey.unpaddedBase64PublicKey, myUserKey.canonicalSignable())
+            crossSigningOlm.olmUtility.verifyEd25519Signature(
+                    userKeySignaturesMadeByMyMasterKey,
+                    myMasterKey.unpaddedBase64PublicKey,
+                    myUserKey.canonicalSignable()
+            )
         } catch (failure: Throwable) {
             return UserTrustResult.InvalidSignature(myUserKey, userKeySignaturesMadeByMyMasterKey)
         }
@@ -507,7 +510,11 @@ internal class DefaultCrossSigningService @Inject constructor(
 
         // Check that Alice USK signature of Alice MSK is valid
         try {
-            olmUtility!!.verifyEd25519Signature(ssKeySignaturesMadeByMyMasterKey, myMasterKey.unpaddedBase64PublicKey, mySSKey.canonicalSignable())
+            crossSigningOlm.olmUtility.verifyEd25519Signature(
+                    ssKeySignaturesMadeByMyMasterKey,
+                    myMasterKey.unpaddedBase64PublicKey,
+                    mySSKey.canonicalSignable()
+            )
         } catch (failure: Throwable) {
             return UserTrustResult.InvalidSignature(mySSKey, ssKeySignaturesMadeByMyMasterKey)
         }
@@ -560,7 +567,7 @@ internal class DefaultCrossSigningService @Inject constructor(
                 return@launch
             }
             val userPubKey = myKeys.userKey()?.unpaddedBase64PublicKey
-            if (userPubKey == null || userPkSigning == null) {
+            if (userPubKey == null || crossSigningOlm.userPkSigning == null) {
                 callback.onFailure(Throwable("## CrossSigning - Cannot sign from this account, privateKeyUnknown $userPubKey"))
                 return@launch
             }
@@ -569,7 +576,7 @@ internal class DefaultCrossSigningService @Inject constructor(
             val newSignature = JsonCanonicalizer.getCanonicalJson(
                     Map::class.java,
                     otherMasterKeys.signalableJSONDictionary()
-            ).let { userPkSigning?.sign(it) }
+            ).let { crossSigningOlm.userPkSigning?.sign(it) }
 
             if (newSignature == null) {
                 // race??
@@ -616,13 +623,13 @@ internal class DefaultCrossSigningService @Inject constructor(
             }
 
             val ssPubKey = myKeys.selfSigningKey()?.unpaddedBase64PublicKey
-            if (ssPubKey == null || selfSigningPkSigning == null) {
+            if (ssPubKey == null || crossSigningOlm.selfSigningPkSigning == null) {
                 callback.onFailure(Throwable("Cannot sign from this account, public and/or privateKey Unknown $ssPubKey"))
                 return@launch
             }
 
             // Sign with self signing
-            val newSignature = selfSigningPkSigning?.sign(device.canonicalSignable())
+            val newSignature = crossSigningOlm.selfSigningPkSigning?.sign(device.canonicalSignable())
 
             if (newSignature == null) {
                 // race??
@@ -695,7 +702,11 @@ internal class DefaultCrossSigningService @Inject constructor(
 
         // Check  bob's device is signed by bob's SSK
         try {
-            olmUtility!!.verifyEd25519Signature(otherSSKSignature, otherKeys.selfSigningKey()?.unpaddedBase64PublicKey, otherDevice.canonicalSignable())
+            crossSigningOlm.olmUtility.verifyEd25519Signature(
+                    otherSSKSignature,
+                    otherKeys.selfSigningKey()?.unpaddedBase64PublicKey,
+                    otherDevice.canonicalSignable()
+            )
         } catch (e: Throwable) {
             return legacyFallbackTrust(locallyTrusted, DeviceTrustResult.InvalidDeviceSignature(otherDeviceId, otherSSKSignature, e))
         }
@@ -745,7 +756,11 @@ internal class DefaultCrossSigningService @Inject constructor(
 
         // Check  bob's device is signed by bob's SSK
         try {
-            olmUtility!!.verifyEd25519Signature(otherSSKSignature, otherKeys.selfSigningKey()?.unpaddedBase64PublicKey, otherDevice.canonicalSignable())
+            crossSigningOlm.olmUtility.verifyEd25519Signature(
+                    otherSSKSignature,
+                    otherKeys.selfSigningKey()?.unpaddedBase64PublicKey,
+                    otherDevice.canonicalSignable()
+            )
         } catch (e: Throwable) {
             return legacyFallbackTrust(locallyTrusted, DeviceTrustResult.InvalidDeviceSignature(otherDevice.deviceId, otherSSKSignature, e))
         }
@@ -785,7 +800,8 @@ internal class DefaultCrossSigningService @Inject constructor(
         // If it's me, recheck trust of all users and devices?
         val users = ArrayList()
         if (otherUserId == userId && currentTrust != trusted) {
-//                reRequestAllPendingRoomKeyRequest()
+            // notify key requester
+            outgoingKeyRequestManager.onSelfCrossSigningTrustChanged(trusted)
             cryptoStore.updateUsersTrust {
                 users.add(it)
                 checkUserTrust(it).isVerified()
@@ -800,19 +816,4 @@ internal class DefaultCrossSigningService @Inject constructor(
             }
         }
     }
-
-//    private fun reRequestAllPendingRoomKeyRequest() {
-//        cryptoCoroutineScope.launch(coroutineDispatchers.crypto) {
-//            Timber.d("## CrossSigning - reRequest pending outgoing room key requests")
-//            cryptoStore.getOutgoingRoomKeyRequests().forEach {
-//                it.requestBody?.let { requestBody ->
-//                    if (cryptoStore.getInboundGroupSession(requestBody.sessionId ?: "", requestBody.senderKey ?: "") == null) {
-//                        outgoingRoomKeyRequestManager.resendRoomKeyRequest(requestBody)
-//                    } else {
-//                        outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody)
-//                    }
-//                }
-//            }
-//        }
-//    }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt
index e6352809c4..5ea4695da2 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/DefaultKeysBackupService.kt
@@ -54,6 +54,7 @@ import org.matrix.android.sdk.internal.crypto.MXOlmDevice
 import org.matrix.android.sdk.internal.crypto.MegolmSessionData
 import org.matrix.android.sdk.internal.crypto.ObjectSigner
 import org.matrix.android.sdk.internal.crypto.actions.MegolmSessionDataImporter
+import org.matrix.android.sdk.internal.crypto.crosssigning.CrossSigningOlm
 import org.matrix.android.sdk.internal.crypto.keysbackup.model.SignalableMegolmBackupAuthData
 import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.BackupKeysResult
 import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.CreateKeysBackupVersionBody
@@ -63,16 +64,11 @@ import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.RoomKeysBack
 import org.matrix.android.sdk.internal.crypto.keysbackup.model.rest.UpdateKeysBackupVersionBody
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.CreateKeysBackupVersionTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.DeleteBackupTask
-import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.DeleteRoomSessionDataTask
-import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.DeleteRoomSessionsDataTask
-import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.DeleteSessionsDataTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.GetKeysBackupLastVersionTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.GetKeysBackupVersionTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.GetRoomSessionDataTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.GetRoomSessionsDataTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.GetSessionsDataTask
-import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.StoreRoomSessionDataTask
-import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.StoreRoomSessionsDataTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.StoreSessionsDataTask
 import org.matrix.android.sdk.internal.crypto.keysbackup.tasks.UpdateKeysBackupVersionTask
 import org.matrix.android.sdk.internal.crypto.model.OlmInboundGroupSessionWrapper2
@@ -107,21 +103,17 @@ internal class DefaultKeysBackupService @Inject constructor(
         private val cryptoStore: IMXCryptoStore,
         private val olmDevice: MXOlmDevice,
         private val objectSigner: ObjectSigner,
+        private val crossSigningOlm: CrossSigningOlm,
         // Actions
         private val megolmSessionDataImporter: MegolmSessionDataImporter,
         // Tasks
         private val createKeysBackupVersionTask: CreateKeysBackupVersionTask,
         private val deleteBackupTask: DeleteBackupTask,
-        private val deleteRoomSessionDataTask: DeleteRoomSessionDataTask,
-        private val deleteRoomSessionsDataTask: DeleteRoomSessionsDataTask,
-        private val deleteSessionDataTask: DeleteSessionsDataTask,
         private val getKeysBackupLastVersionTask: GetKeysBackupLastVersionTask,
         private val getKeysBackupVersionTask: GetKeysBackupVersionTask,
         private val getRoomSessionDataTask: GetRoomSessionDataTask,
         private val getRoomSessionsDataTask: GetRoomSessionsDataTask,
         private val getSessionsDataTask: GetSessionsDataTask,
-        private val storeRoomSessionDataTask: StoreRoomSessionDataTask,
-        private val storeSessionsDataTask: StoreRoomSessionsDataTask,
         private val storeSessionDataTask: StoreSessionsDataTask,
         private val updateKeysBackupVersionTask: UpdateKeysBackupVersionTask,
         // Task executor
@@ -168,58 +160,76 @@ internal class DefaultKeysBackupService @Inject constructor(
     override fun prepareKeysBackupVersion(password: String?,
                                           progressListener: ProgressListener?,
                                           callback: MatrixCallback) {
-        cryptoCoroutineScope.launch(coroutineDispatchers.main) {
-            runCatching {
-                withContext(coroutineDispatchers.crypto) {
-                    val olmPkDecryption = OlmPkDecryption()
-                    val signalableMegolmBackupAuthData = if (password != null) {
-                        // Generate a private key from the password
-                        val backgroundProgressListener = if (progressListener == null) {
-                            null
-                        } else {
-                            object : ProgressListener {
-                                override fun onProgress(progress: Int, total: Int) {
-                                    uiHandler.post {
-                                        try {
-                                            progressListener.onProgress(progress, total)
-                                        } catch (e: Exception) {
-                                            Timber.e(e, "prepareKeysBackupVersion: onProgress failure")
-                                        }
+        cryptoCoroutineScope.launch(coroutineDispatchers.io) {
+            try {
+                val olmPkDecryption = OlmPkDecryption()
+                val signalableMegolmBackupAuthData = if (password != null) {
+                    // Generate a private key from the password
+                    val backgroundProgressListener = if (progressListener == null) {
+                        null
+                    } else {
+                        object : ProgressListener {
+                            override fun onProgress(progress: Int, total: Int) {
+                                uiHandler.post {
+                                    try {
+                                        progressListener.onProgress(progress, total)
+                                    } catch (e: Exception) {
+                                        Timber.e(e, "prepareKeysBackupVersion: onProgress failure")
                                     }
                                 }
                             }
                         }
-
-                        val generatePrivateKeyResult = generatePrivateKeyWithPassword(password, backgroundProgressListener)
-                        SignalableMegolmBackupAuthData(
-                                publicKey = olmPkDecryption.setPrivateKey(generatePrivateKeyResult.privateKey),
-                                privateKeySalt = generatePrivateKeyResult.salt,
-                                privateKeyIterations = generatePrivateKeyResult.iterations
-                        )
-                    } else {
-                        val publicKey = olmPkDecryption.generateKey()
-
-                        SignalableMegolmBackupAuthData(
-                                publicKey = publicKey
-                        )
                     }
-
-                    val canonicalJson = JsonCanonicalizer.getCanonicalJson(Map::class.java, signalableMegolmBackupAuthData.signalableJSONDictionary())
-
-                    val signedMegolmBackupAuthData = MegolmBackupAuthData(
-                            publicKey = signalableMegolmBackupAuthData.publicKey,
-                            privateKeySalt = signalableMegolmBackupAuthData.privateKeySalt,
-                            privateKeyIterations = signalableMegolmBackupAuthData.privateKeyIterations,
-                            signatures = objectSigner.signObject(canonicalJson)
+                    val generatePrivateKeyResult = generatePrivateKeyWithPassword(password, backgroundProgressListener)
+                    SignalableMegolmBackupAuthData(
+                            publicKey = olmPkDecryption.setPrivateKey(generatePrivateKeyResult.privateKey),
+                            privateKeySalt = generatePrivateKeyResult.salt,
+                            privateKeyIterations = generatePrivateKeyResult.iterations
                     )
-
-                    MegolmBackupCreationInfo(
-                            algorithm = MXCRYPTO_ALGORITHM_MEGOLM_BACKUP,
-                            authData = signedMegolmBackupAuthData,
-                            recoveryKey = computeRecoveryKey(olmPkDecryption.privateKey())
+                } else {
+                    val publicKey = olmPkDecryption.generateKey()
+                    SignalableMegolmBackupAuthData(
+                            publicKey = publicKey
                     )
                 }
-            }.foldToCallback(callback)
+
+                val canonicalJson = JsonCanonicalizer.getCanonicalJson(Map::class.java, signalableMegolmBackupAuthData.signalableJSONDictionary())
+
+                val signatures = mutableMapOf>()
+
+                val deviceSignature = objectSigner.signObject(canonicalJson)
+                deviceSignature.forEach { (userID, content) ->
+                    signatures[userID] = content.toMutableMap()
+                }
+
+                // If we have cross signing add signature, will throw if cross signing not properly configured
+                try {
+                    val crossSign = crossSigningOlm.signObject(CrossSigningOlm.KeyType.MASTER, canonicalJson)
+                    signatures[credentials.userId]?.putAll(crossSign)
+                } catch (failure: Throwable) {
+                    // ignore and log
+                    Timber.w(failure, "prepareKeysBackupVersion: failed to sign with cross signing keys")
+                }
+
+                val signedMegolmBackupAuthData = MegolmBackupAuthData(
+                        publicKey = signalableMegolmBackupAuthData.publicKey,
+                        privateKeySalt = signalableMegolmBackupAuthData.privateKeySalt,
+                        privateKeyIterations = signalableMegolmBackupAuthData.privateKeyIterations,
+                        signatures = signatures
+                )
+                val creationInfo = MegolmBackupCreationInfo(
+                        algorithm = MXCRYPTO_ALGORITHM_MEGOLM_BACKUP,
+                        authData = signedMegolmBackupAuthData,
+                        recoveryKey = computeRecoveryKey(olmPkDecryption.privateKey())
+                )
+                uiHandler.post {
+                    callback.onSuccess(creationInfo)
+                }
+            } catch (failure: Throwable) {
+                uiHandler.post {
+                    callback.onFailure(failure)
+                }
+            }
         }
     }
 
@@ -267,41 +277,39 @@ internal class DefaultKeysBackupService @Inject constructor(
     }
 
     override fun deleteBackup(version: String, callback: MatrixCallback?) {
-        cryptoCoroutineScope.launch(coroutineDispatchers.main) {
-            withContext(coroutineDispatchers.crypto) {
-                // If we're currently backing up to this backup... stop.
-                // (We start using it automatically in createKeysBackupVersion so this is symmetrical).
-                if (keysBackupVersion != null && version == keysBackupVersion?.version) {
-                    resetKeysBackupData()
-                    keysBackupVersion = null
-                    keysBackupStateManager.state = KeysBackupState.Unknown
-                }
+        cryptoCoroutineScope.launch(coroutineDispatchers.io) {
+            // If we're currently backing up to this backup... stop.
+            // (We start using it automatically in createKeysBackupVersion so this is symmetrical).
+            if (keysBackupVersion != null && version == keysBackupVersion?.version) {
+                resetKeysBackupData()
+                keysBackupVersion = null
+                keysBackupStateManager.state = KeysBackupState.Unknown
+            }
 
-                deleteBackupTask
-                        .configureWith(DeleteBackupTask.Params(version)) {
-                            this.callback = object : MatrixCallback {
-                                private fun eventuallyRestartBackup() {
-                                    // Do not stay in KeysBackupState.Unknown but check what is available on the homeserver
-                                    if (state == KeysBackupState.Unknown) {
-                                        checkAndStartKeysBackup()
-                                    }
-                                }
-
-                                override fun onSuccess(data: Unit) {
-                                    eventuallyRestartBackup()
-
-                                    uiHandler.post { callback?.onSuccess(Unit) }
-                                }
-
-                                override fun onFailure(failure: Throwable) {
-                                    eventuallyRestartBackup()
-
-                                    uiHandler.post { callback?.onFailure(failure) }
+            deleteBackupTask
+                    .configureWith(DeleteBackupTask.Params(version)) {
+                        this.callback = object : MatrixCallback {
+                            private fun eventuallyRestartBackup() {
+                                // Do not stay in KeysBackupState.Unknown but check what is available on the homeserver
+                                if (state == KeysBackupState.Unknown) {
+                                    checkAndStartKeysBackup()
                                 }
                             }
+
+                            override fun onSuccess(data: Unit) {
+                                eventuallyRestartBackup()
+
+                                uiHandler.post { callback?.onSuccess(Unit) }
+                            }
+
+                            override fun onFailure(failure: Throwable) {
+                                eventuallyRestartBackup()
+
+                                uiHandler.post { callback?.onFailure(failure) }
+                            }
                         }
-                        .executeBy(taskExecutor)
-            }
+                    }
+                    .executeBy(taskExecutor)
         }
     }
 
@@ -339,6 +347,10 @@ internal class DefaultKeysBackupService @Inject constructor(
 
     override fun backupAllGroupSessions(progressListener: ProgressListener?,
                                         callback: MatrixCallback?) {
+        if (!isEnabled || backupOlmPkEncryption == null || keysBackupVersion == null) {
+            callback?.onFailure(Throwable("Backup not enabled"))
+            return
+        }
         // Get a status right now
         getBackupProgress(object : ProgressListener {
             override fun onProgress(progress: Int, total: Int) {
@@ -427,18 +439,41 @@ internal class DefaultKeysBackupService @Inject constructor(
 
         for ((keyId, mySignature) in mySigs) {
             // XXX: is this how we're supposed to get the device id?
-            var deviceId: String? = null
+            var deviceOrCrossSigningKeyId: String? = null
             val components = keyId.split(":")
             if (components.size == 2) {
-                deviceId = components[1]
+                deviceOrCrossSigningKeyId = components[1]
             }
 
-            if (deviceId != null) {
-                val device = cryptoStore.getUserDevice(userId, deviceId)
+            // Let's check if it's my master key
+            val myMSKPKey = cryptoStore.getMyCrossSigningInfo()?.masterKey()?.unpaddedBase64PublicKey
+            if (deviceOrCrossSigningKeyId == myMSKPKey) {
+                // we have to check if we can trust
+
+                var isSignatureValid = false
+                try {
+                    crossSigningOlm.verifySignature(CrossSigningOlm.KeyType.MASTER, authData.signalableJSONDictionary(), authData.signatures)
+                    isSignatureValid = true
+                } catch (failure: Throwable) {
+                    Timber.w(failure, "getKeysBackupTrust: Bad signature from my user MSK")
+                }
+                val mskTrusted = cryptoStore.getMyCrossSigningInfo()?.masterKey()?.trustLevel?.isVerified() == true
+                if (isSignatureValid && mskTrusted) {
+                    keysBackupVersionTrustIsUsable = true
+                }
+                val signature = KeysBackupVersionTrustSignature.UserSignature(
+                        keyId = deviceOrCrossSigningKeyId,
+                        cryptoCrossSigningKey = cryptoStore.getMyCrossSigningInfo()?.masterKey(),
+                        valid = isSignatureValid
+                )
+
+                keysBackupVersionTrustSignatures.add(signature)
+            } else if (deviceOrCrossSigningKeyId != null) {
+                val device = cryptoStore.getUserDevice(userId, deviceOrCrossSigningKeyId)
                 var isSignatureValid = false
 
                 if (device == null) {
-                    Timber.v("getKeysBackupTrust: Signature from unknown device $deviceId")
+                    Timber.v("getKeysBackupTrust: Signature from unknown device $deviceOrCrossSigningKeyId")
                 } else {
                     val fingerprint = device.fingerprint()
                     if (fingerprint != null) {
@@ -455,8 +490,8 @@ internal class DefaultKeysBackupService @Inject constructor(
                     }
                 }
 
-                val signature = KeysBackupVersionTrustSignature(
-                        deviceId = deviceId,
+                val signature = KeysBackupVersionTrustSignature.DeviceSignature(
+                        deviceId = deviceOrCrossSigningKeyId,
                         device = device,
                         valid = isSignatureValid,
                 )
@@ -480,10 +515,11 @@ internal class DefaultKeysBackupService @Inject constructor(
 
         if (authData == null) {
             Timber.w("trustKeyBackupVersion:trust: Key backup is missing required data")
-
-            callback.onFailure(IllegalArgumentException("Missing element"))
+            uiHandler.post {
+                callback.onFailure(IllegalArgumentException("Missing element"))
+            }
         } else {
-            cryptoCoroutineScope.launch(coroutineDispatchers.main) {
+            cryptoCoroutineScope.launch(coroutineDispatchers.io) {
                 val updateKeysBackupVersionBody = withContext(coroutineDispatchers.crypto) {
                     // Get current signatures, or create an empty set
                     val myUserSignatures = authData.signatures?.get(userId).orEmpty().toMutableMap()
@@ -536,11 +572,15 @@ internal class DefaultKeysBackupService @Inject constructor(
 
                                     checkAndStartWithKeysBackupVersion(newKeysBackupVersion)
 
-                                    callback.onSuccess(data)
+                                    uiHandler.post {
+                                        callback.onSuccess(data)
+                                    }
                                 }
 
                                 override fun onFailure(failure: Throwable) {
-                                    callback.onFailure(failure)
+                                    uiHandler.post {
+                                        callback.onFailure(failure)
+                                    }
                                 }
                             }
                         }
@@ -554,15 +594,14 @@ internal class DefaultKeysBackupService @Inject constructor(
                                                        callback: MatrixCallback) {
         Timber.v("trustKeysBackupVersionWithRecoveryKey: version ${keysBackupVersion.version}")
 
-        cryptoCoroutineScope.launch(coroutineDispatchers.main) {
-            val isValid = withContext(coroutineDispatchers.crypto) {
-                isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysBackupVersion)
-            }
+        cryptoCoroutineScope.launch(coroutineDispatchers.io) {
+            val isValid = isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysBackupVersion)
 
             if (!isValid) {
                 Timber.w("trustKeyBackupVersionWithRecoveryKey: Invalid recovery key.")
-
-                callback.onFailure(IllegalArgumentException("Invalid recovery key or password"))
+                uiHandler.post {
+                    callback.onFailure(IllegalArgumentException("Invalid recovery key or password"))
+                }
             } else {
                 trustKeysBackupVersion(keysBackupVersion, true, callback)
             }
@@ -574,15 +613,14 @@ internal class DefaultKeysBackupService @Inject constructor(
                                                       callback: MatrixCallback) {
         Timber.v("trustKeysBackupVersionWithPassphrase: version ${keysBackupVersion.version}")
 
-        cryptoCoroutineScope.launch(coroutineDispatchers.main) {
-            val recoveryKey = withContext(coroutineDispatchers.crypto) {
-                recoveryKeyFromPassword(password, keysBackupVersion, null)
-            }
+        cryptoCoroutineScope.launch(coroutineDispatchers.io) {
+            val recoveryKey = recoveryKeyFromPassword(password, keysBackupVersion, null)
 
             if (recoveryKey == null) {
                 Timber.w("trustKeysBackupVersionWithPassphrase: Key backup is missing required data")
-
-                callback.onFailure(IllegalArgumentException("Missing element"))
+                uiHandler.post {
+                    callback.onFailure(IllegalArgumentException("Missing element"))
+                }
             } else {
                 // Check trust using the recovery key
                 trustKeysBackupVersionWithRecoveryKey(keysBackupVersion, recoveryKey, callback)
@@ -593,30 +631,28 @@ internal class DefaultKeysBackupService @Inject constructor(
     override fun onSecretKeyGossip(secret: String) {
         Timber.i("## CrossSigning - onSecretKeyGossip")
 
-        cryptoCoroutineScope.launch(coroutineDispatchers.main) {
+        cryptoCoroutineScope.launch(coroutineDispatchers.io) {
             try {
-                when (val keysBackupLastVersionResult = getKeysBackupLastVersionTask.execute(Unit)) {
-                    KeysBackupLastVersionResult.NoKeysBackup  -> {
-                        Timber.d("No keys backup found")
-                    }
-                    is KeysBackupLastVersionResult.KeysBackup -> {
-                        val keysBackupVersion = keysBackupLastVersionResult.keysVersionResult
-                        val recoveryKey = computeRecoveryKey(secret.fromBase64())
-                        if (isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysBackupVersion)) {
-                            awaitCallback {
-                                trustKeysBackupVersion(keysBackupVersion, true, it)
-                            }
-                            val importResult = awaitCallback {
-                                restoreKeysWithRecoveryKey(keysBackupVersion, recoveryKey, null, null, null, it)
-                            }
-                            withContext(coroutineDispatchers.crypto) {
-                                cryptoStore.saveBackupRecoveryKey(recoveryKey, keysBackupVersion.version)
-                            }
-                            Timber.i("onSecretKeyGossip: Recovered keys $importResult")
-                        } else {
-                            Timber.e("onSecretKeyGossip: Recovery key is not valid ${keysBackupVersion.version}")
+                val keysBackupVersion = getKeysBackupLastVersionTask.execute(Unit).toKeysVersionResult()
+                        ?: return@launch Unit.also {
+                            Timber.d("Failed to get backup last version")
                         }
+                val recoveryKey = computeRecoveryKey(secret.fromBase64())
+                if (isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysBackupVersion)) {
+                    awaitCallback {
+                        trustKeysBackupVersion(keysBackupVersion, true, it)
                     }
+                    // we don't want to start immediately downloading all as it can take very long
+
+//                    val importResult = awaitCallback {
+//                        restoreKeysWithRecoveryKey(keysBackupVersion, recoveryKey, null, null, null, it)
+//                    }
+                    withContext(coroutineDispatchers.crypto) {
+                        cryptoStore.saveBackupRecoveryKey(recoveryKey, keysBackupVersion.version)
+                    }
+                    Timber.i("onSecretKeyGossip: saved valid backup key")
+                } else {
+                    Timber.e("onSecretKeyGossip: Recovery key is not valid ${keysBackupVersion.version}")
                 }
             } catch (failure: Throwable) {
                 Timber.e("onSecretKeyGossip: failed to trust key backup version ${keysBackupVersion?.version}")
@@ -625,7 +661,7 @@ internal class DefaultKeysBackupService @Inject constructor(
     }
 
     /**
-     * Get public key from a Recovery key
+     * Get public key from a Recovery key.
      *
      * @param recoveryKey the recovery key
      * @return the corresponding public key, from Olm
@@ -679,9 +715,9 @@ internal class DefaultKeysBackupService @Inject constructor(
                                             callback: MatrixCallback) {
         Timber.v("restoreKeysWithRecoveryKey: From backup version: ${keysVersionResult.version}")
 
-        cryptoCoroutineScope.launch(coroutineDispatchers.main) {
+        cryptoCoroutineScope.launch(coroutineDispatchers.io) {
             runCatching {
-                val decryption = withContext(coroutineDispatchers.crypto) {
+                val decryption = withContext(coroutineDispatchers.computation) {
                     // Check if the recovery is valid before going any further
                     if (!isValidRecoveryKeyForKeysBackupVersion(recoveryKey, keysVersionResult)) {
                         Timber.e("restoreKeysWithRecoveryKey: Invalid recovery key for this keys version")
@@ -754,7 +790,19 @@ internal class DefaultKeysBackupService @Inject constructor(
                     }
                     result
                 }
-            }.foldToCallback(callback)
+            }.foldToCallback(object : MatrixCallback {
+                override fun onSuccess(data: ImportRoomKeysResult) {
+                    uiHandler.post {
+                        callback.onSuccess(data)
+                    }
+                }
+
+                override fun onFailure(failure: Throwable) {
+                    uiHandler.post {
+                        callback.onFailure(failure)
+                    }
+                }
+            })
         }
     }
 
@@ -766,7 +814,7 @@ internal class DefaultKeysBackupService @Inject constructor(
                                               callback: MatrixCallback) {
         Timber.v("[MXKeyBackup] restoreKeyBackup with password: From backup version: ${keysBackupVersion.version}")
 
-        cryptoCoroutineScope.launch(coroutineDispatchers.main) {
+        cryptoCoroutineScope.launch(coroutineDispatchers.io) {
             runCatching {
                 val progressListener = if (stepProgressListener != null) {
                     object : ProgressListener {
@@ -791,13 +839,25 @@ internal class DefaultKeysBackupService @Inject constructor(
                         restoreKeysWithRecoveryKey(keysBackupVersion, recoveryKey, roomId, sessionId, stepProgressListener, it)
                     }
                 }
-            }.foldToCallback(callback)
+            }.foldToCallback(object : MatrixCallback {
+                override fun onSuccess(data: ImportRoomKeysResult) {
+                    uiHandler.post {
+                        callback.onSuccess(data)
+                    }
+                }
+
+                override fun onFailure(failure: Throwable) {
+                    uiHandler.post {
+                        callback.onFailure(failure)
+                    }
+                }
+            })
         }
     }
 
     /**
      * Same method as [RoomKeysRestClient.getRoomKey] except that it accepts nullable
-     * parameters and always returns a KeysBackupData object through the Callback
+     * parameters and always returns a KeysBackupData object through the Callback.
      */
     private suspend fun getKeys(sessionId: String?,
                                 roomId: String?,
@@ -817,12 +877,16 @@ internal class DefaultKeysBackupService @Inject constructor(
             )
         } else if (roomId != null) {
             // Get all keys for the room
-            val data = getRoomSessionsDataTask.execute(GetRoomSessionsDataTask.Params(roomId, version))
+            val data = withContext(coroutineDispatchers.io) {
+                getRoomSessionsDataTask.execute(GetRoomSessionsDataTask.Params(roomId, version))
+            }
             // Convert to KeysBackupData
             KeysBackupData(mutableMapOf(roomId to data))
         } else {
             // Get all keys
-            getSessionsDataTask.execute(GetSessionsDataTask.Params(version))
+            withContext(coroutineDispatchers.io) {
+                getSessionsDataTask.execute(GetSessionsDataTask.Params(version))
+            }
         }
     }
 
@@ -847,7 +911,7 @@ internal class DefaultKeysBackupService @Inject constructor(
     }
 
     /**
-     * Do a backup if there are new keys, with a delay
+     * Do a backup if there are new keys, with a delay.
      */
     fun maybeBackupKeys() {
         when {
@@ -1158,7 +1222,7 @@ internal class DefaultKeysBackupService @Inject constructor(
     }
 
     /**
-     * Update the DB with data fetch from the server
+     * Update the DB with data fetch from the server.
      */
     private fun onServerDataRetrieved(count: Int?, etag: String?) {
         cryptoStore.setKeysBackupData(KeysBackupDataEntity()
@@ -1187,7 +1251,7 @@ internal class DefaultKeysBackupService @Inject constructor(
     }
 
     /**
-     * Send a chunk of keys to backup
+     * Send a chunk of keys to backup.
      */
     @UiThread
     private fun backupKeys() {
@@ -1198,7 +1262,6 @@ internal class DefaultKeysBackupService @Inject constructor(
             Timber.v("backupKeys: Invalid configuration")
             backupAllGroupSessionsCallback?.onFailure(IllegalStateException("Invalid configuration"))
             resetBackupAllGroupSessionsListeners()
-
             return
         }
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt
index 4d5b38acbf..d5bab33180 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupPassword.kt
@@ -59,7 +59,7 @@ internal fun generatePrivateKeyWithPassword(password: String,
 }
 
 /**
- * Retrieve a private key from {password, salt, iterations}
+ * Retrieve a private key from {password, salt, iterations}.
  *
  * @param password the password used to generated the private key.
  * @param salt the salt.
@@ -143,7 +143,7 @@ internal fun deriveKey(password: String,
 }
 
 /**
- * Generate a 32 chars salt
+ * Generate a 32 chars salt.
  */
 private fun generateSalt(): String {
     val salt = buildString {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt
index 8464b33526..ea23be5923 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/api/RoomKeysApi.kt
@@ -50,7 +50,7 @@ internal interface RoomKeysApi {
     suspend fun createKeysBackupVersion(@Body createKeysBackupVersionBody: CreateKeysBackupVersionBody): KeysVersion
 
     /**
-     * Get the key backup last version
+     * Get the key backup last version.
      * If not supported by the server, an error is returned: {"errcode":"M_NOT_FOUND","error":"No backup found"}
      */
     @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "room_keys/version")
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/CreateKeysBackupVersionBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/CreateKeysBackupVersionBody.kt
index a6bd8f8aaa..2d483893c0 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/CreateKeysBackupVersionBody.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/CreateKeysBackupVersionBody.kt
@@ -23,13 +23,13 @@ import org.matrix.android.sdk.api.util.JsonDict
 @JsonClass(generateAdapter = true)
 internal data class CreateKeysBackupVersionBody(
         /**
-         * The algorithm used for storing backups. Currently, only "m.megolm_backup.v1.curve25519-aes-sha2" is defined
+         * The algorithm used for storing backups. Currently, only "m.megolm_backup.v1.curve25519-aes-sha2" is defined.
          */
         @Json(name = "algorithm")
         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]
          */
         @Json(name = "auth_data")
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/KeysAlgorithmAndData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/KeysAlgorithmAndData.kt
index 898b357c51..19581a686b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/KeysAlgorithmAndData.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/KeysAlgorithmAndData.kt
@@ -41,17 +41,17 @@ import org.matrix.android.sdk.internal.di.MoshiProvider
 internal interface KeysAlgorithmAndData {
 
     /**
-     * The algorithm used for storing backups. Currently, only "m.megolm_backup.v1.curve25519-aes-sha2" is defined
+     * The algorithm used for storing backups. Currently, only "m.megolm_backup.v1.curve25519-aes-sha2" is defined.
      */
     val algorithm: String
 
     /**
-     * algorithm-dependent data, for "m.megolm_backup.v1.curve25519-aes-sha2" see [org.matrix.android.sdk.internal.crypto.keysbackup.MegolmBackupAuthData]
+     * algorithm-dependent data, for "m.megolm_backup.v1.curve25519-aes-sha2" see [org.matrix.android.sdk.internal.crypto.keysbackup.MegolmBackupAuthData].
      */
     val authData: JsonDict
 
     /**
-     * Facility method to convert authData to a MegolmBackupAuthData object
+     * Facility method to convert authData to a MegolmBackupAuthData object.
      */
     fun getAuthDataAsMegolmBackupAuthData(): MegolmBackupAuthData? {
         return MoshiProvider.providesMoshi()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/UpdateKeysBackupVersionBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/UpdateKeysBackupVersionBody.kt
index 3f2def84d5..a4b8f811e4 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/UpdateKeysBackupVersionBody.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/model/rest/UpdateKeysBackupVersionBody.kt
@@ -29,7 +29,7 @@ internal data class UpdateKeysBackupVersionBody(
         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]
          */
         @Json(name = "auth_data")
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/util/Base58.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/util/Base58.kt
index 0e746f289b..407e034acb 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/util/Base58.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/keysbackup/util/Base58.kt
@@ -39,7 +39,7 @@ private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqr
 private val BASE = BigInteger.valueOf(58)
 
 /**
- * Encode a byte array to a human readable string with base58 chars
+ * Encode a byte array to a human readable string with base58 chars.
  */
 internal fun base58encode(input: ByteArray): String {
     var bi = BigInteger(1, input)
@@ -62,7 +62,7 @@ internal fun base58encode(input: ByteArray): String {
 }
 
 /**
- * Decode a base58 String to a byte array
+ * Decode a base58 String to a byte array.
  */
 internal fun base58decode(input: String): ByteArray {
     var result = decodeToBigInteger(input).toByteArray()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXKey.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXKey.kt
index cff713bf8f..6bfa56ae8d 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXKey.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXKey.kt
@@ -36,13 +36,13 @@ internal data class MXKey(
         val value: String,
 
         /**
-         * signature user Id to [deviceid][signature]
+         * signature user Id to [deviceid][signature].
          */
         private val signatures: Map>,
 
         /**
          * We have to store the original json because it can contain other fields
-         * that we don't support yet but they would be needed to check signatures
+         * that we don't support yet but they would be needed to check signatures.
          */
         private val rawMap: JsonDict
 ) {
@@ -57,7 +57,7 @@ internal data class MXKey(
     }
 
     /**
-     * Returns a signature for an user Id and a signkey
+     * Returns a signature for an user Id and a signkey.
      *
      * @param userId  the user id
      * @param signkey the sign key
@@ -81,7 +81,7 @@ internal data class MXKey(
         // const val KEY_ED_25519_TYPE = "ed25519"
 
         /**
-         * Convert a map to a MXKey
+         * Convert a map to a MXKey.
          *
          * @param map the map to convert
          *
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXOlmSessionResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXOlmSessionResult.kt
index 671827799e..666ab2d678 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXOlmSessionResult.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/MXOlmSessionResult.kt
@@ -21,7 +21,7 @@ import java.io.Serializable
 
 internal data class MXOlmSessionResult(
         /**
-         * the device
+         * the device.
          */
         val deviceInfo: CryptoDeviceInfo,
         /**
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper.kt
index 45ffcc6606..ecb2946680 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper.kt
@@ -60,7 +60,7 @@ internal class OlmInboundGroupSessionWrapper : Serializable {
         }
 
     /**
-     * Constructor
+     * Constructor.
      *
      * @param sessionKey the session key
      * @param isImported true if it is an imported session key
@@ -101,7 +101,7 @@ internal class OlmInboundGroupSessionWrapper : Serializable {
     }
 
     /**
-     * Export the inbound group session keys
+     * Export the inbound group session keys.
      *
      * @return the inbound group session as MegolmSessionData if the operation succeeds
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper2.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper2.kt
index 1f671aa896..289c169d6d 100755
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper2.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmInboundGroupSessionWrapper2.kt
@@ -57,7 +57,7 @@ internal class OlmInboundGroupSessionWrapper2 : Serializable {
         }
 
     /**
-     * Constructor
+     * Constructor.
      *
      * @param sessionKey the session key
      * @param isImported true if it is an imported session key
@@ -104,7 +104,7 @@ internal class OlmInboundGroupSessionWrapper2 : Serializable {
     }
 
     /**
-     * Export the inbound group session keys
+     * Export the inbound group session keys.
      * @param index the index to export. If null, the first known index will be used
      *
      * @return the inbound group session as MegolmSessionData if the operation succeeds
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmSessionWrapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmSessionWrapper.kt
index d7ce553f39..a1e58ead0c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmSessionWrapper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/OlmSessionWrapper.kt
@@ -20,7 +20,7 @@ import kotlinx.coroutines.sync.Mutex
 import org.matrix.olm.OlmSession
 
 /**
- * Encapsulate a OlmSession and a last received message Timestamp
+ * Encapsulate a OlmSession and a last received message Timestamp.
  */
 internal data class OlmSessionWrapper(
         // The associated olm session.
@@ -32,7 +32,7 @@ internal data class OlmSessionWrapper(
 ) {
 
     /**
-     * Notify that a message has been received on this olm session so that it updates `lastReceivedMessageTs`
+     * Notify that a message has been received on this olm session so that it updates `lastReceivedMessageTs`.
      */
     fun onMessageReceived(currentTimeMillis: Long) {
         lastReceivedMessageTs = currentTimeMillis
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/DeleteDeviceParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/DeleteDeviceParams.kt
index f636ab890d..c26c6107c4 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/DeleteDeviceParams.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/DeleteDeviceParams.kt
@@ -19,7 +19,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * This class provides the parameter to delete a device
+ * This class provides the parameter to delete a device.
  */
 @JsonClass(generateAdapter = true)
 internal data class DeleteDeviceParams(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyChangesResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyChangesResponse.kt
index f0ed77a1e3..5d432eca8c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyChangesResponse.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyChangesResponse.kt
@@ -19,7 +19,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * This class describes the key changes response
+ * This class describes the key changes response.
  */
 @JsonClass(generateAdapter = true)
 internal data class KeyChangesResponse(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt
index 7a5773bf24..9fdeda01c9 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationAccept.kt
@@ -35,25 +35,25 @@ internal data class KeyVerificationAccept(
         override val transactionId: String? = null,
 
         /**
-         * The key agreement protocol that Bob’s device has selected to use, out of the list proposed by Alice’s device
+         * The key agreement protocol that Bob’s device has selected to use, out of the list proposed by Alice’s device.
          */
         @Json(name = "key_agreement_protocol")
         override val keyAgreementProtocol: String? = null,
 
         /**
-         * The hash algorithm that Bob’s device has selected to use, out of the list proposed by Alice’s device
+         * The hash algorithm that Bob’s device has selected to use, out of the list proposed by Alice’s device.
          */
         @Json(name = "hash")
         override val hash: String? = null,
 
         /**
-         * The message authentication code that Bob’s device has selected to use, out of the list proposed by Alice’s device
+         * The message authentication code that Bob’s device has selected to use, out of the list proposed by Alice’s device.
          */
         @Json(name = "message_authentication_code")
         override val messageAuthenticationCode: String? = null,
 
         /**
-         * An array of short authentication string methods that Bob’s client (and Bob) understands.  Must be a subset of the list proposed by Alice’s device
+         * An array of short authentication string methods that Bob’s client (and Bob) understands.  Must be a subset of the list proposed by Alice’s device.
          */
         @Json(name = "short_authentication_string")
         override val shortAuthenticationStrings: List? = null,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationCancel.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationCancel.kt
index 90272bf0e4..2858ef3eed 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationCancel.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationCancel.kt
@@ -27,18 +27,18 @@ import org.matrix.android.sdk.internal.crypto.verification.VerificationInfoCance
 @JsonClass(generateAdapter = true)
 internal data class KeyVerificationCancel(
         /**
-         * the transaction ID of the verification to cancel
+         * the transaction ID of the verification to cancel.
          */
         @Json(name = "transaction_id")
         override val transactionId: String? = null,
 
         /**
-         * machine-readable reason for cancelling, see #CancelCode
+         * machine-readable reason for cancelling, see #CancelCode.
          */
         override val code: String? = null,
 
         /**
-         * human-readable reason for cancelling.  This should only be used if the receiving client does not understand the code given.
+         * human-readable reason for cancelling. This should only be used if the receiving client does not understand the code given.
          */
         override val reason: String? = null
 ) : SendToDeviceObject, VerificationInfoCancel {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationKey.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationKey.kt
index 19d8c32ddf..a833148b9d 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationKey.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeyVerificationKey.kt
@@ -27,12 +27,12 @@ import org.matrix.android.sdk.internal.crypto.verification.VerificationInfoKeyFa
 @JsonClass(generateAdapter = true)
 internal data class KeyVerificationKey(
         /**
-         * the ID of the transaction that the message is part of
+         * The ID of the transaction that the message is part of.
          */
         @Json(name = "transaction_id") override val transactionId: String? = null,
 
         /**
-         * The device’s ephemeral public key, as an unpadded base64 string
+         * The device’s ephemeral public key, as an unpadded base64 string.
          */
         @Json(name = "key") override val key: String? = null
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysQueryBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysQueryBody.kt
index 4f98be9da3..dc570820f2 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysQueryBody.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysQueryBody.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * This class represents the body to /keys/query
+ * This class represents the body to /keys/query.
  */
 @JsonClass(generateAdapter = true)
 internal data class KeysQueryBody(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysUploadResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysUploadResponse.kt
index 3d0ea8677f..c445f55ba7 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysUploadResponse.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/KeysUploadResponse.kt
@@ -31,7 +31,7 @@ internal data class KeysUploadResponse(
         val oneTimeKeyCounts: Map? = null
 ) {
     /**
-     * Helper methods to extract information from 'oneTimeKeyCounts'
+     * Helper methods to extract information from 'oneTimeKeyCounts'.
      *
      * @param algorithm the expected algorithm
      * @return the time key counts
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/RestKeyInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/RestKeyInfo.kt
index 66247d07d1..cdcbe5ffe2 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/RestKeyInfo.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/RestKeyInfo.kt
@@ -23,7 +23,7 @@ import org.matrix.android.sdk.internal.crypto.model.CryptoInfoMapper
 @JsonClass(generateAdapter = true)
 internal data class RestKeyInfo(
         /**
-         * The user who owns the key
+         * The user who owns the key.
          */
         @Json(name = "user_id")
         val userId: String,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/ShareRequestCancellation.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/ShareRequestCancellation.kt
index a96534fc3a..ea9b451ed6 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/ShareRequestCancellation.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/ShareRequestCancellation.kt
@@ -21,7 +21,7 @@ import org.matrix.android.sdk.api.session.crypto.model.GossipingToDeviceObject
 import org.matrix.android.sdk.api.session.crypto.model.GossipingToDeviceObject.Companion.ACTION_SHARE_CANCELLATION
 
 /**
- * Class representing a room key request cancellation content
+ * Class representing a room key request cancellation content.
  */
 @JsonClass(generateAdapter = true)
 internal data class ShareRequestCancellation(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/SignatureUploadResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/SignatureUploadResponse.kt
index fb92b67fc4..f89426d91b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/SignatureUploadResponse.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/SignatureUploadResponse.kt
@@ -20,7 +20,7 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
- * Upload Signature response
+ * Upload Signature response.
  */
 @JsonClass(generateAdapter = true)
 internal data class SignatureUploadResponse(
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/UploadSignatureQueryBuilder.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/UploadSignatureQueryBuilder.kt
index dd0ce47cd3..1c1e223bc8 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/UploadSignatureQueryBuilder.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/UploadSignatureQueryBuilder.kt
@@ -21,7 +21,7 @@ import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
 import org.matrix.android.sdk.internal.crypto.model.toRest
 
 /**
- * Helper class to build CryptoApi#uploadSignatures params
+ * Helper class to build CryptoApi#uploadSignatures params.
  */
 internal data class UploadSignatureQueryBuilder(
         private val deviceInfoList: MutableList = mutableListOf(),
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/repository/WarnOnUnknownDeviceRepository.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/repository/WarnOnUnknownDeviceRepository.kt
index deec8b1b3c..d699950e4f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/repository/WarnOnUnknownDeviceRepository.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/repository/WarnOnUnknownDeviceRepository.kt
@@ -22,7 +22,7 @@ import javax.inject.Inject
 @SessionScope
 internal class WarnOnUnknownDeviceRepository @Inject constructor() {
 
-    // TODO: set it back to true by default. Need UI
+    // TODO set it back to true by default. Need UI
     // Warn the user if some new devices are detected while encrypting a message.
     private var warnOnUnknownDevices = false
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt
index dc50afe67d..1ded9c6c7e 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/secrets/DefaultSharedSecretStorageService.kt
@@ -40,7 +40,7 @@ import org.matrix.android.sdk.api.session.securestorage.SsssKeySpec
 import org.matrix.android.sdk.api.session.securestorage.SsssPassphrase
 import org.matrix.android.sdk.api.util.fromBase64
 import org.matrix.android.sdk.api.util.toBase64NoPadding
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.SecretShareManager
 import org.matrix.android.sdk.internal.crypto.keysbackup.generatePrivateKeyWithPassword
 import org.matrix.android.sdk.internal.crypto.tools.HkdfSha256
 import org.matrix.android.sdk.internal.crypto.tools.withOlmDecryption
@@ -57,7 +57,7 @@ import kotlin.experimental.and
 internal class DefaultSharedSecretStorageService @Inject constructor(
         @UserId private val userId: String,
         private val accountDataService: SessionAccountDataService,
-        private val outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
+        private val secretShareManager: SecretShareManager,
         private val coroutineDispatchers: MatrixCoroutineDispatchers,
         private val cryptoCoroutineScope: CoroutineScope
 ) : SharedSecretStorageService {
@@ -380,10 +380,7 @@ internal class DefaultSharedSecretStorageService @Inject constructor(
         return IntegrityResult.Success(keyInfo.content.passphrase != null)
     }
 
-    override fun requestSecret(name: String, myOtherDeviceId: String) {
-        outgoingGossipingRequestManager.sendSecretShareRequest(
-                name,
-                mapOf(userId to listOf(myOtherDeviceId))
-        )
+    override suspend fun requestSecret(name: String, myOtherDeviceId: String) {
+        secretShareManager.requestSecretTo(myOtherDeviceId, name)
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt
index 8bedb78808..480009dbce 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/IMXCryptoStore.kt
@@ -19,23 +19,22 @@ package org.matrix.android.sdk.internal.crypto.store
 import androidx.lifecycle.LiveData
 import androidx.paging.PagedList
 import org.matrix.android.sdk.api.session.crypto.NewSessionListener
+import org.matrix.android.sdk.api.session.crypto.OutgoingKeyRequest
+import org.matrix.android.sdk.api.session.crypto.OutgoingRoomKeyRequestState
 import org.matrix.android.sdk.api.session.crypto.crosssigning.CryptoCrossSigningKey
 import org.matrix.android.sdk.api.session.crypto.crosssigning.MXCrossSigningInfo
 import org.matrix.android.sdk.api.session.crypto.crosssigning.PrivateKeysInfo
 import org.matrix.android.sdk.api.session.crypto.keysbackup.SavedKeyBackupKeyInfo
+import org.matrix.android.sdk.api.session.crypto.model.AuditTrail
 import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
 import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo
-import org.matrix.android.sdk.api.session.crypto.model.GossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
 import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest
 import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
+import org.matrix.android.sdk.api.session.crypto.model.TrailType
 import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
+import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode
 import org.matrix.android.sdk.api.util.Optional
-import org.matrix.android.sdk.internal.crypto.IncomingShareRequestCommon
-import org.matrix.android.sdk.internal.crypto.OutgoingSecretRequest
 import org.matrix.android.sdk.internal.crypto.model.OlmInboundGroupSessionWrapper2
 import org.matrix.android.sdk.internal.crypto.model.OlmSessionWrapper
 import org.matrix.android.sdk.internal.crypto.model.OutboundGroupSessionWrapper
@@ -44,7 +43,7 @@ import org.matrix.olm.OlmAccount
 import org.matrix.olm.OlmOutboundGroupSession
 
 /**
- * the crypto data store
+ * The crypto data store.
  */
 internal interface IMXCryptoStore {
 
@@ -82,6 +81,15 @@ internal interface IMXCryptoStore {
      */
     fun setGlobalBlacklistUnverifiedDevices(block: Boolean)
 
+    /**
+     * Enable or disable key gossiping.
+     * Default is true.
+     * If set to false this device won't send key_request nor will accept key forwarded
+     */
+    fun enableKeyGossiping(enable: Boolean)
+
+    fun isKeyGossipingEnabled(): Boolean
+
     /**
      * Provides the rooms ids list in which the messages are not encrypted for the unverified devices.
      *
@@ -97,24 +105,24 @@ internal interface IMXCryptoStore {
     fun setRoomsListBlacklistUnverifiedDevices(roomIds: List)
 
     /**
-     * Get the current keys backup version
+     * Get the current keys backup version.
      */
     fun getKeyBackupVersion(): String?
 
     /**
-     * Set the current keys backup version
+     * Set the current keys backup version.
      *
      * @param keyBackupVersion the keys backup version or null to delete it
      */
     fun setKeyBackupVersion(keyBackupVersion: String?)
 
     /**
-     * Get the current keys backup local data
+     * Get the current keys backup local data.
      */
     fun getKeysBackupData(): KeysBackupDataEntity?
 
     /**
-     * Set the keys backup local data
+     * Set the keys backup local data.
      *
      * @param keysBackupData the keys backup local data, or null to erase data
      */
@@ -125,18 +133,6 @@ internal interface IMXCryptoStore {
      */
     fun getDeviceTrackingStatuses(): Map
 
-    /**
-     * @return the pending IncomingRoomKeyRequest requests
-     */
-    fun getPendingIncomingRoomKeyRequests(): List
-
-    fun getPendingIncomingGossipingRequests(): List
-
-    fun storeIncomingGossipingRequest(request: IncomingShareRequestCommon, ageLocalTS: Long?)
-
-    fun storeIncomingGossipingRequests(requests: List)
-//    fun getPendingIncomingSecretShareRequests(): List
-
     /**
      * Indicate if the store contains data for the passed account.
      *
@@ -150,12 +146,12 @@ internal interface IMXCryptoStore {
     fun deleteStore()
 
     /**
-     * open any existing crypto store
+     * open any existing crypto store.
      */
     fun open()
 
     /**
-     * Close the store
+     * Close the store.
      */
     fun close()
 
@@ -243,10 +239,10 @@ internal interface IMXCryptoStore {
     fun getRoomAlgorithm(roomId: String): String?
 
     /**
-     * This is a bit different than isRoomEncrypted
-     * A room is encrypted when there is a m.room.encryption state event in the room (malformed/invalid or not)
-     * But the crypto layer has additional guaranty to ensure that encryption would never been reverted
-     * It's defensive coding out of precaution (if ever state is reset)
+     * This is a bit different than isRoomEncrypted.
+     * A room is encrypted when there is a m.room.encryption state event in the room (malformed/invalid or not).
+     * But the crypto layer has additional guaranty to ensure that encryption would never been reverted.
+     * It's defensive coding out of precaution (if ever state is reset).
      */
     fun roomWasOnceEncrypted(roomId: String): Boolean
 
@@ -282,7 +278,7 @@ internal interface IMXCryptoStore {
     fun getDeviceSession(sessionId: String, deviceKey: String): OlmSessionWrapper?
 
     /**
-     * Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist
+     * Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist.
      *
      * @param deviceKey the public key of the other device.
      * @return last used sessionId, or null if not found
@@ -306,17 +302,17 @@ internal interface IMXCryptoStore {
     fun getInboundGroupSession(sessionId: String, senderKey: String): OlmInboundGroupSessionWrapper2?
 
     /**
-     * Get the current outbound group session for this encrypted room
+     * Get the current outbound group session for this encrypted room.
      */
     fun getCurrentOutboundGroupSessionForRoom(roomId: String): OutboundGroupSessionWrapper?
 
     /**
-     * Get the current outbound group session for this encrypted room
+     * Get the current outbound group session for this encrypted room.
      */
     fun storeCurrentOutboundGroupSessionForRoom(roomId: String, outboundGroupSession: OlmOutboundGroupSession?)
 
     /**
-     * Remove an inbound group session
+     * Remove an inbound group session.
      *
      * @param sessionId the session identifier.
      * @param senderKey the base64-encoded curve25519 key of the sender.
@@ -356,7 +352,7 @@ internal interface IMXCryptoStore {
     fun inboundGroupSessionsCount(onlyBackedUp: Boolean): Int
 
     /**
-     * Save the device statuses
+     * Save the device statuses.
      *
      * @param deviceTrackingStatuses the device tracking statuses
      */
@@ -372,12 +368,14 @@ internal interface IMXCryptoStore {
     fun getDeviceTrackingStatus(userId: String, defaultValue: Int): Int
 
     /**
-     * Look for an existing outgoing room key request, and if none is found, return null
+     * Look for an existing outgoing room key request, and if none is found, return null.
      *
      * @param requestBody the request body
      * @return an OutgoingRoomKeyRequest instance or null
      */
-    fun getOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody): OutgoingRoomKeyRequest?
+    fun getOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody): OutgoingKeyRequest?
+    fun getOutgoingRoomKeyRequest(requestId: String): OutgoingKeyRequest?
+    fun getOutgoingRoomKeyRequest(roomId: String, sessionId: String, algorithm: String, senderKey: String): List
 
     /**
      * Look for an existing outgoing room key request, and if none is found, add a new one.
@@ -385,39 +383,59 @@ internal interface IMXCryptoStore {
      * @param request the request
      * @return either the same instance as passed in, or the existing one.
      */
-    fun getOrAddOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody, recipients: Map>): OutgoingRoomKeyRequest?
+    fun getOrAddOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody, recipients: Map>, fromIndex: Int): OutgoingKeyRequest
+    fun updateOutgoingRoomKeyRequestState(requestId: String, newState: OutgoingRoomKeyRequestState)
+    fun updateOutgoingRoomKeyRequiredIndex(requestId: String, newIndex: Int)
+    fun updateOutgoingRoomKeyReply(
+            roomId: String,
+            sessionId: String,
+            algorithm: String,
+            senderKey: String,
+            fromDevice: String?,
+            event: Event)
 
-    fun getOrAddOutgoingSecretShareRequest(secretName: String, recipients: Map>): OutgoingSecretRequest?
+    fun deleteOutgoingRoomKeyRequest(requestId: String)
+    fun deleteOutgoingRoomKeyRequestInState(state: OutgoingRoomKeyRequestState)
 
-    fun saveGossipingEvent(event: Event) = saveGossipingEvents(listOf(event))
+    fun saveIncomingKeyRequestAuditTrail(
+            requestId: String,
+            roomId: String,
+            sessionId: String,
+            senderKey: String,
+            algorithm: String,
+            fromUser: String,
+            fromDevice: String
+    )
 
-    fun saveGossipingEvents(events: List)
+    fun saveWithheldAuditTrail(
+            roomId: String,
+            sessionId: String,
+            senderKey: String,
+            algorithm: String,
+            code: WithHeldCode,
+            userId: String,
+            deviceId: String
+    )
 
-    fun updateGossipingRequestState(request: IncomingShareRequestCommon, state: GossipingRequestState) {
-        updateGossipingRequestState(
-                requestUserId = request.userId,
-                requestDeviceId = request.deviceId,
-                requestId = request.requestId,
-                state = state
-        )
-    }
+    fun saveForwardKeyAuditTrail(
+            roomId: String,
+            sessionId: String,
+            senderKey: String,
+            algorithm: String,
+            userId: String,
+            deviceId: String,
+            chainIndex: Long?
+    )
 
-    fun updateGossipingRequestState(requestUserId: String?,
-                                    requestDeviceId: String?,
-                                    requestId: String?,
-                                    state: GossipingRequestState)
-
-    /**
-     * Search an IncomingRoomKeyRequest
-     *
-     * @param userId    the user id
-     * @param deviceId  the device id
-     * @param requestId the request id
-     * @return an IncomingRoomKeyRequest if it exists, else null
-     */
-    fun getIncomingRoomKeyRequest(userId: String, deviceId: String, requestId: String): IncomingRoomKeyRequest?
-
-    fun updateOutgoingGossipingRequestState(requestId: String, state: OutgoingGossipingRequestState)
+    fun saveIncomingForwardKeyAuditTrail(
+            roomId: String,
+            sessionId: String,
+            senderKey: String,
+            algorithm: String,
+            userId: String,
+            deviceId: String,
+            chainIndex: Long?
+    )
 
     fun addNewSessionListener(listener: NewSessionListener)
 
@@ -428,7 +446,7 @@ internal interface IMXCryptoStore {
     // =============================================
 
     /**
-     * Gets the current crosssigning info
+     * Gets the current crosssigning info.
      */
     fun getMyCrossSigningInfo(): MXCrossSigningInfo?
 
@@ -477,17 +495,15 @@ internal interface IMXCryptoStore {
     fun getSharedWithInfo(roomId: String?, sessionId: String): MXUsersDevicesMap
     // Dev tools
 
-    fun getOutgoingRoomKeyRequests(): List
-    fun getOutgoingRoomKeyRequestsPaged(): LiveData>
-    fun getOutgoingSecretKeyRequests(): List
-    fun getOutgoingSecretRequest(secretName: String): OutgoingSecretRequest?
-    fun getIncomingRoomKeyRequests(): List
-    fun getIncomingRoomKeyRequestsPaged(): LiveData>
-    fun getGossipingEventsTrail(): LiveData>
-    fun getGossipingEvents(): List
+    fun getOutgoingRoomKeyRequests(): List
+    fun getOutgoingRoomKeyRequestsPaged(): LiveData>
+    fun getGossipingEventsTrail(): LiveData>
+    fun  getGossipingEventsTrail(type: TrailType, mapper: ((AuditTrail) -> T)): LiveData>
+    fun getGossipingEvents(): List
 
     fun setDeviceKeysUploaded(uploaded: Boolean)
     fun areDeviceKeysUploaded(): Boolean
     fun tidyUpDataBase()
     fun logDbUsageInfo()
+    fun getOutgoingRoomKeyRequests(inStates: Set): List
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/Helper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/Helper.kt
index b841e9c6e5..2d66ce1488 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/Helper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/Helper.kt
@@ -26,7 +26,7 @@ import java.util.zip.GZIPInputStream
 import java.util.zip.GZIPOutputStream
 
 /**
- * Get realm, invoke the action, close realm, and return the result of the action
+ * Get realm, invoke the action, close realm, and return the result of the action.
  */
 internal fun  doWithRealm(realmConfiguration: RealmConfiguration, action: (Realm) -> T): T {
     return Realm.getInstance(realmConfiguration).use { realm ->
@@ -35,7 +35,7 @@ internal fun  doWithRealm(realmConfiguration: RealmConfiguration, action: (Re
 }
 
 /**
- * Get realm, do the query, copy from realm, close realm, and return the copied result
+ * Get realm, do the query, copy from realm, close realm, and return the copied result.
  */
 internal fun  doRealmQueryAndCopy(realmConfiguration: RealmConfiguration, action: (Realm) -> T?): T? {
     return Realm.getInstance(realmConfiguration).use { realm ->
@@ -44,7 +44,7 @@ internal fun  doRealmQueryAndCopy(realmConfiguration: RealmConf
 }
 
 /**
- * Get realm, do the list query, copy from realm, close realm, and return the copied result
+ * Get realm, do the list query, copy from realm, close realm, and return the copied result.
  */
 internal fun  doRealmQueryAndCopyList(realmConfiguration: RealmConfiguration, action: (Realm) -> Iterable): Iterable {
     return Realm.getInstance(realmConfiguration).use { realm ->
@@ -53,7 +53,7 @@ internal fun  doRealmQueryAndCopyList(realmConfiguration: Realm
 }
 
 /**
- * Get realm instance, invoke the action in a transaction and close realm
+ * Get realm instance, invoke the action in a transaction and close realm.
  */
 internal fun doRealmTransaction(realmConfiguration: RealmConfiguration, action: (Realm) -> Unit) {
     Realm.getInstance(realmConfiguration).use { realm ->
@@ -68,7 +68,7 @@ internal fun doRealmTransactionAsync(realmConfiguration: RealmConfiguration, act
 }
 
 /**
- * Serialize any Serializable object, zip it and convert to Base64 String
+ * Serialize any Serializable object, zip it and convert to Base64 String.
  */
 internal fun serializeForRealm(o: Any?): String? {
     if (o == null) {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt
index a509315e7a..533ab70bba 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStore.kt
@@ -24,37 +24,40 @@ import com.zhuinden.monarchy.Monarchy
 import io.realm.Realm
 import io.realm.RealmConfiguration
 import io.realm.Sort
+import io.realm.kotlin.createObject
 import io.realm.kotlin.where
 import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
 import org.matrix.android.sdk.api.extensions.tryOrNull
+import org.matrix.android.sdk.api.logger.LoggerTag
 import org.matrix.android.sdk.api.session.crypto.NewSessionListener
+import org.matrix.android.sdk.api.session.crypto.OutgoingKeyRequest
+import org.matrix.android.sdk.api.session.crypto.OutgoingRoomKeyRequestState
 import org.matrix.android.sdk.api.session.crypto.crosssigning.CryptoCrossSigningKey
 import org.matrix.android.sdk.api.session.crypto.crosssigning.MXCrossSigningInfo
 import org.matrix.android.sdk.api.session.crypto.crosssigning.PrivateKeysInfo
 import org.matrix.android.sdk.api.session.crypto.keysbackup.SavedKeyBackupKeyInfo
+import org.matrix.android.sdk.api.session.crypto.model.AuditTrail
 import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo
 import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo
-import org.matrix.android.sdk.api.session.crypto.model.GossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.IncomingSecretShareRequest
+import org.matrix.android.sdk.api.session.crypto.model.ForwardInfo
+import org.matrix.android.sdk.api.session.crypto.model.IncomingKeyRequestInfo
 import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap
-import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest
 import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
+import org.matrix.android.sdk.api.session.crypto.model.TrailType
+import org.matrix.android.sdk.api.session.crypto.model.WithheldInfo
 import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
-import org.matrix.android.sdk.api.session.room.send.SendState
+import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode
 import org.matrix.android.sdk.api.util.Optional
 import org.matrix.android.sdk.api.util.toOptional
-import org.matrix.android.sdk.internal.crypto.GossipRequestType
-import org.matrix.android.sdk.internal.crypto.IncomingShareRequestCommon
-import org.matrix.android.sdk.internal.crypto.OutgoingSecretRequest
 import org.matrix.android.sdk.internal.crypto.model.OlmInboundGroupSessionWrapper2
 import org.matrix.android.sdk.internal.crypto.model.OlmSessionWrapper
 import org.matrix.android.sdk.internal.crypto.model.OutboundGroupSessionWrapper
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
 import org.matrix.android.sdk.internal.crypto.store.db.mapper.CrossSigningKeysMapper
+import org.matrix.android.sdk.internal.crypto.store.db.model.AuditTrailEntity
+import org.matrix.android.sdk.internal.crypto.store.db.model.AuditTrailEntityFields
+import org.matrix.android.sdk.internal.crypto.store.db.model.AuditTrailMapper
 import org.matrix.android.sdk.internal.crypto.store.db.model.CrossSigningInfoEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.CrossSigningInfoEntityFields
 import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoMapper
@@ -63,10 +66,6 @@ import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoRoomEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoRoomEntityFields
 import org.matrix.android.sdk.internal.crypto.store.db.model.DeviceInfoEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.DeviceInfoEntityFields
-import org.matrix.android.sdk.internal.crypto.store.db.model.GossipingEventEntity
-import org.matrix.android.sdk.internal.crypto.store.db.model.GossipingEventEntityFields
-import org.matrix.android.sdk.internal.crypto.store.db.model.IncomingGossipingRequestEntity
-import org.matrix.android.sdk.internal.crypto.store.db.model.IncomingGossipingRequestEntityFields
 import org.matrix.android.sdk.internal.crypto.store.db.model.KeysBackupDataEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.MyDeviceLastSeenInfoEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.OlmInboundGroupSessionEntity
@@ -74,8 +73,8 @@ import org.matrix.android.sdk.internal.crypto.store.db.model.OlmInboundGroupSess
 import org.matrix.android.sdk.internal.crypto.store.db.model.OlmSessionEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.OlmSessionEntityFields
 import org.matrix.android.sdk.internal.crypto.store.db.model.OutboundGroupSessionInfoEntity
-import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingGossipingRequestEntity
-import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingGossipingRequestEntityFields
+import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingKeyRequestEntity
+import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingKeyRequestEntityFields
 import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.TrustLevelEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.UserEntity
@@ -89,7 +88,6 @@ import org.matrix.android.sdk.internal.crypto.store.db.query.get
 import org.matrix.android.sdk.internal.crypto.store.db.query.getById
 import org.matrix.android.sdk.internal.crypto.store.db.query.getOrCreate
 import org.matrix.android.sdk.internal.crypto.util.RequestIdHelper
-import org.matrix.android.sdk.internal.database.mapper.ContentMapper
 import org.matrix.android.sdk.internal.database.tools.RealmDebugTools
 import org.matrix.android.sdk.internal.di.CryptoDatabase
 import org.matrix.android.sdk.internal.di.DeviceId
@@ -106,6 +104,8 @@ import java.util.concurrent.Executors
 import java.util.concurrent.TimeUnit
 import javax.inject.Inject
 
+private val loggerTag = LoggerTag("RealmCryptoStore", LoggerTag.CRYPTO)
+
 @SessionScope
 internal class RealmCryptoStore @Inject constructor(
         @CryptoDatabase private val realmConfiguration: RealmConfiguration,
@@ -233,7 +233,7 @@ internal class RealmCryptoStore @Inject constructor(
     }
 
     /**
-     * Olm account access should be synchronized
+     * Olm account access should be synchronized.
      */
     override fun  doWithOlmAccount(block: (OlmAccount) -> T): T {
         return olmAccount!!.let { olmAccount ->
@@ -273,12 +273,13 @@ internal class RealmCryptoStore @Inject constructor(
     }
 
     override fun deviceWithIdentityKey(identityKey: String): CryptoDeviceInfo? {
-        return doWithRealm(realmConfiguration) {
-            it.where()
-                    .equalTo(DeviceInfoEntityFields.IDENTITY_KEY, identityKey)
-                    .findFirst()
-                    ?.let { deviceInfo ->
-                        CryptoMapper.mapToModel(deviceInfo)
+        return doWithRealm(realmConfiguration) { realm ->
+            realm.where()
+                    .contains(DeviceInfoEntityFields.KEYS_MAP_JSON, identityKey)
+                    .findAll()
+                    .mapNotNull { CryptoMapper.mapToModel(it) }
+                    .firstOrNull {
+                        it.identityKey() == identityKey
                     }
         }
     }
@@ -743,14 +744,23 @@ internal class RealmCryptoStore @Inject constructor(
                 if (sessionIdentifier != null) {
                     val key = OlmInboundGroupSessionEntity.createPrimaryKey(sessionIdentifier, session.senderKey)
 
-                    val realmOlmInboundGroupSession = OlmInboundGroupSessionEntity().apply {
-                        primaryKey = key
-                        sessionId = sessionIdentifier
-                        senderKey = session.senderKey
-                        putInboundGroupSession(session)
-                    }
+                    val existing = realm.where()
+                            .equalTo(OlmInboundGroupSessionEntityFields.PRIMARY_KEY, key)
+                            .findFirst()
 
-                    realm.insertOrUpdate(realmOlmInboundGroupSession)
+                    if (existing != null) {
+                        // we want to keep the existing backup status
+                        existing.putInboundGroupSession(session)
+                    } else {
+                        val realmOlmInboundGroupSession = OlmInboundGroupSessionEntity().apply {
+                            primaryKey = key
+                            sessionId = sessionIdentifier
+                            senderKey = session.senderKey
+                            putInboundGroupSession(session)
+                        }
+
+                        realm.insertOrUpdate(realmOlmInboundGroupSession)
+                    }
                 }
             }
         }
@@ -805,7 +815,7 @@ internal class RealmCryptoStore @Inject constructor(
 
     /**
      * Note: the result will be only use to export all the keys and not to use the OlmInboundGroupSessionWrapper2,
-     * so there is no need to use or update `inboundGroupSessionToRelease` for native memory management
+     * so there is no need to use or update `inboundGroupSessionToRelease` for native memory management.
      */
     override fun getInboundGroupSessions(): List {
         return doWithRealm(realmConfiguration) {
@@ -879,18 +889,33 @@ internal class RealmCryptoStore @Inject constructor(
             return
         }
 
-        doRealmTransaction(realmConfiguration) {
+        doRealmTransaction(realmConfiguration) { realm ->
             olmInboundGroupSessionWrappers.forEach { olmInboundGroupSessionWrapper ->
                 try {
+                    val sessionIdentifier = olmInboundGroupSessionWrapper.olmInboundGroupSession?.sessionIdentifier()
                     val key = OlmInboundGroupSessionEntity.createPrimaryKey(
-                            olmInboundGroupSessionWrapper.olmInboundGroupSession?.sessionIdentifier(),
+                            sessionIdentifier,
                             olmInboundGroupSessionWrapper.senderKey
                     )
 
-                    it.where()
+                    val existing = realm.where()
                             .equalTo(OlmInboundGroupSessionEntityFields.PRIMARY_KEY, key)
                             .findFirst()
-                            ?.backedUp = true
+
+                    if (existing != null) {
+                        existing.backedUp = true
+                    } else {
+                        // ... might be in cache but not yet persisted, create a record to persist backedup state
+                        val realmOlmInboundGroupSession = OlmInboundGroupSessionEntity().apply {
+                            primaryKey = key
+                            sessionId = sessionIdentifier
+                            senderKey = olmInboundGroupSessionWrapper.senderKey
+                            putInboundGroupSession(olmInboundGroupSessionWrapper)
+                            backedUp = true
+                        }
+
+                        realm.insertOrUpdate(realmOlmInboundGroupSession)
+                    }
                 } catch (e: OlmException) {
                     Timber.e(e, "OlmException")
                 }
@@ -929,6 +954,18 @@ internal class RealmCryptoStore @Inject constructor(
         }
     }
 
+    override fun enableKeyGossiping(enable: Boolean) {
+        doRealmTransaction(realmConfiguration) {
+            it.where().findFirst()?.globalEnableKeyGossiping = enable
+        }
+    }
+
+    override fun isKeyGossipingEnabled(): Boolean {
+        return doWithRealm(realmConfiguration) {
+            it.where().findFirst()?.globalEnableKeyGossiping
+        } ?: true
+    }
+
     override fun getGlobalBlacklistUnverifiedDevices(): Boolean {
         return doWithRealm(realmConfiguration) {
             it.where().findFirst()?.globalBlacklistUnverifiedDevices
@@ -1010,12 +1047,13 @@ internal class RealmCryptoStore @Inject constructor(
                 ?: defaultValue
     }
 
-    override fun getOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody): OutgoingRoomKeyRequest? {
+    override fun getOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody): OutgoingKeyRequest? {
         return monarchy.fetchAllCopiedSync { realm ->
-            realm.where()
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
-        }.mapNotNull {
-            it.toOutgoingGossipingRequest() as? OutgoingRoomKeyRequest
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.ROOM_ID, requestBody.roomId)
+                    .equalTo(OutgoingKeyRequestEntityFields.MEGOLM_SESSION_ID, requestBody.sessionId)
+        }.map {
+            it.toOutgoingKeyRequest()
         }.firstOrNull {
             it.requestBody?.algorithm == requestBody.algorithm &&
                     it.requestBody?.roomId == requestBody.roomId &&
@@ -1024,41 +1062,37 @@ internal class RealmCryptoStore @Inject constructor(
         }
     }
 
-    override fun getOutgoingSecretRequest(secretName: String): OutgoingSecretRequest? {
+    override fun getOutgoingRoomKeyRequest(requestId: String): OutgoingKeyRequest? {
         return monarchy.fetchAllCopiedSync { realm ->
-            realm.where()
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.SECRET.name)
-                    .equalTo(OutgoingGossipingRequestEntityFields.REQUESTED_INFO_STR, secretName)
-        }.mapNotNull {
-            it.toOutgoingGossipingRequest() as? OutgoingSecretRequest
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.REQUEST_ID, requestId)
+        }.map {
+            it.toOutgoingKeyRequest()
         }.firstOrNull()
     }
 
-    override fun getIncomingRoomKeyRequests(): List {
+    override fun getOutgoingRoomKeyRequest(roomId: String, sessionId: String, algorithm: String, senderKey: String): List {
+        // TODO this annoying we have to load all
         return monarchy.fetchAllCopiedSync { realm ->
-            realm.where()
-                    .equalTo(IncomingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
-        }.mapNotNull {
-            it.toIncomingGossipingRequest() as? IncomingRoomKeyRequest
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.ROOM_ID, roomId)
+                    .equalTo(OutgoingKeyRequestEntityFields.MEGOLM_SESSION_ID, sessionId)
+        }.map {
+            it.toOutgoingKeyRequest()
+        }.filter {
+            it.requestBody?.algorithm == algorithm &&
+                    it.requestBody?.senderKey == senderKey
         }
     }
 
-    override fun getIncomingRoomKeyRequestsPaged(): LiveData> {
+    override fun getGossipingEventsTrail(): LiveData> {
         val realmDataSourceFactory = monarchy.createDataSourceFactory { realm ->
-            realm.where()
-                    .equalTo(IncomingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
-                    .sort(IncomingGossipingRequestEntityFields.LOCAL_CREATION_TIMESTAMP, Sort.DESCENDING)
+            realm.where().sort(AuditTrailEntityFields.AGE_LOCAL_TS, Sort.DESCENDING)
         }
         val dataSourceFactory = realmDataSourceFactory.map {
-            it.toIncomingGossipingRequest() as? IncomingRoomKeyRequest
-                    ?: IncomingRoomKeyRequest(
-                            requestBody = null,
-                            deviceId = "",
-                            userId = "",
-                            requestId = "",
-                            state = GossipingRequestState.NONE,
-                            localCreationTimestamp = 0
-                    )
+            AuditTrailMapper.map(it)
+            // mm we can't map not null...
+                    ?: createUnknownTrail()
         }
         return monarchy.findAllPagedWithChanges(
                 realmDataSourceFactory,
@@ -1073,12 +1107,33 @@ internal class RealmCryptoStore @Inject constructor(
         )
     }
 
-    override fun getGossipingEventsTrail(): LiveData> {
+    private fun createUnknownTrail() = AuditTrail(
+            clock.epochMillis(),
+            TrailType.Unknown,
+            IncomingKeyRequestInfo(
+                    "",
+                    "",
+                    "",
+                    "",
+                    "",
+                    "",
+                    "",
+            )
+    )
+
+    override fun  getGossipingEventsTrail(type: TrailType, mapper: ((AuditTrail) -> T)): LiveData> {
         val realmDataSourceFactory = monarchy.createDataSourceFactory { realm ->
-            realm.where().sort(GossipingEventEntityFields.AGE_LOCAL_TS, Sort.DESCENDING)
+            realm.where()
+                    .equalTo(AuditTrailEntityFields.TYPE, type.name)
+                    .sort(AuditTrailEntityFields.AGE_LOCAL_TS, Sort.DESCENDING)
         }
-        val dataSourceFactory = realmDataSourceFactory.map { it.toModel() }
-        val trail = monarchy.findAllPagedWithChanges(
+        val dataSourceFactory = realmDataSourceFactory.map { entity ->
+            (AuditTrailMapper.map(entity)
+            // mm we can't map not null...
+                    ?: createUnknownTrail()
+                    ).let { mapper.invoke(it) }
+        }
+        return monarchy.findAllPagedWithChanges(
                 realmDataSourceFactory,
                 LivePagedListBuilder(
                         dataSourceFactory,
@@ -1089,28 +1144,36 @@ internal class RealmCryptoStore @Inject constructor(
                                 .build()
                 )
         )
-        return trail
     }
 
-    override fun getGossipingEvents(): List {
+    override fun getGossipingEvents(): List {
         return monarchy.fetchAllCopiedSync { realm ->
-            realm.where()
-        }.map {
-            it.toModel()
+            realm.where()
+        }.mapNotNull {
+            AuditTrailMapper.map(it)
         }
     }
 
-    override fun getOrAddOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody, recipients: Map>): OutgoingRoomKeyRequest? {
+    override fun getOrAddOutgoingRoomKeyRequest(requestBody: RoomKeyRequestBody,
+                                                recipients: Map>,
+                                                fromIndex: Int): OutgoingKeyRequest {
         // Insert the request and return the one passed in parameter
-        var request: OutgoingRoomKeyRequest? = null
+        lateinit var request: OutgoingKeyRequest
         doRealmTransaction(realmConfiguration) { realm ->
 
-            val existing = realm.where()
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
+            val existing = realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.MEGOLM_SESSION_ID, requestBody.sessionId)
+                    .equalTo(OutgoingKeyRequestEntityFields.ROOM_ID, requestBody.roomId)
                     .findAll()
-                    .mapNotNull {
-                        it.toOutgoingGossipingRequest() as? OutgoingRoomKeyRequest
-                    }.firstOrNull {
+                    .map {
+                        it.toOutgoingKeyRequest()
+                    }.also {
+                        if (it.size > 1) {
+                            // there should be one or zero but not more, worth warning
+                            Timber.tag(loggerTag.value).w("There should not be more than one active key request per session")
+                        }
+                    }
+                    .firstOrNull {
                         it.requestBody?.algorithm == requestBody.algorithm &&
                                 it.requestBody?.sessionId == requestBody.sessionId &&
                                 it.requestBody?.senderKey == requestBody.senderKey &&
@@ -1118,13 +1181,14 @@ internal class RealmCryptoStore @Inject constructor(
                     }
 
             if (existing == null) {
-                request = realm.createObject(OutgoingGossipingRequestEntity::class.java).apply {
+                request = realm.createObject(OutgoingKeyRequestEntity::class.java).apply {
                     this.requestId = RequestIdHelper.createUniqueRequestId()
                     this.setRecipients(recipients)
-                    this.requestState = OutgoingGossipingRequestState.UNSENT
-                    this.type = GossipRequestType.KEY
-                    this.requestedInfoStr = requestBody.toJson()
-                }.toOutgoingGossipingRequest() as? OutgoingRoomKeyRequest
+                    this.requestedIndex = fromIndex
+                    this.requestState = OutgoingRoomKeyRequestState.UNSENT
+                    this.setRequestBody(requestBody)
+                    this.creationTimeStamp = clock.epochMillis()
+                }.toOutgoingKeyRequest()
             } else {
                 request = existing
             }
@@ -1132,284 +1196,175 @@ internal class RealmCryptoStore @Inject constructor(
         return request
     }
 
-    override fun getOrAddOutgoingSecretShareRequest(secretName: String, recipients: Map>): OutgoingSecretRequest? {
-        var request: OutgoingSecretRequest? = null
-
-        // Insert the request and return the one passed in parameter
+    override fun updateOutgoingRoomKeyRequestState(requestId: String, newState: OutgoingRoomKeyRequestState) {
         doRealmTransaction(realmConfiguration) { realm ->
-            val existing = realm.where()
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.SECRET.name)
-                    .equalTo(OutgoingGossipingRequestEntityFields.REQUESTED_INFO_STR, secretName)
-                    .findAll()
-                    .mapNotNull {
-                        it.toOutgoingGossipingRequest() as? OutgoingSecretRequest
-                    }.firstOrNull()
-            if (existing == null) {
-                request = realm.createObject(OutgoingGossipingRequestEntity::class.java).apply {
-                    this.type = GossipRequestType.SECRET
-                    setRecipients(recipients)
-                    this.requestState = OutgoingGossipingRequestState.UNSENT
-                    this.requestId = RequestIdHelper.createUniqueRequestId()
-                    this.requestedInfoStr = secretName
-                }.toOutgoingGossipingRequest() as? OutgoingSecretRequest
-            } else {
-                request = existing
-            }
-        }
-
-        return request
-    }
-
-    override fun saveGossipingEvents(events: List) {
-        monarchy.writeAsync { realm ->
-            val now = clock.epochMillis()
-            events.forEach { event ->
-                val ageLocalTs = event.unsignedData?.age?.let { now - it } ?: now
-                val entity = GossipingEventEntity(
-                        type = event.type,
-                        sender = event.senderId,
-                        ageLocalTs = ageLocalTs,
-                        content = ContentMapper.map(event.content)
-                ).apply {
-                    sendState = SendState.SYNCED
-                    decryptionResultJson = MoshiProvider.providesMoshi().adapter(OlmDecryptionResult::class.java).toJson(event.mxDecryptionResult)
-                    decryptionErrorCode = event.mCryptoError?.name
-                }
-                realm.insertOrUpdate(entity)
-            }
-        }
-    }
-
-//    override fun getOutgoingRoomKeyRequestByState(states: Set): OutgoingRoomKeyRequest? {
-//        val statesIndex = states.map { it.ordinal }.toTypedArray()
-//        return doRealmQueryAndCopy(realmConfiguration) { realm ->
-//            realm.where()
-//                    .equalTo(GossipingEventEntityFields.SENDER, credentials.userId)
-//                    .findAll()
-//                    .filter {entity ->
-//                        states.any { it == entity.requestState}
-//                    }
-//        }.mapNotNull {
-//            ContentMapper.map(it.content)?.toModel()
-//        }
-//                ?.toOutgoingRoomKeyRequest()
-//    }
-//
-//    override fun getOutgoingSecretShareRequestByState(states: Set): OutgoingSecretRequest? {
-//        val statesIndex = states.map { it.ordinal }.toTypedArray()
-//        return doRealmQueryAndCopy(realmConfiguration) {
-//            it.where()
-//                    .`in`(OutgoingSecretRequestEntityFields.STATE, statesIndex)
-//                    .findFirst()
-//        }
-//                ?.toOutgoingSecretRequest()
-//    }
-
-//    override fun updateOutgoingRoomKeyRequest(request: OutgoingRoomKeyRequest) {
-//        doRealmTransaction(realmConfiguration) {
-//            val obj = OutgoingRoomKeyRequestEntity().apply {
-//                requestId = request.requestId
-//                cancellationTxnId = request.cancellationTxnId
-//                state = request.state.ordinal
-//                putRecipients(request.recipients)
-//                putRequestBody(request.requestBody)
-//            }
-//
-//            it.insertOrUpdate(obj)
-//        }
-//    }
-
-//    override fun deleteOutgoingRoomKeyRequest(transactionId: String) {
-//        doRealmTransaction(realmConfiguration) {
-//            it.where()
-//                    .equalTo(OutgoingRoomKeyRequestEntityFields.REQUEST_ID, transactionId)
-//                    .findFirst()
-//                    ?.deleteFromRealm()
-//        }
-//    }
-
-//    override fun storeIncomingRoomKeyRequest(incomingRoomKeyRequest: IncomingRoomKeyRequest?) {
-//        if (incomingRoomKeyRequest == null) {
-//            return
-//        }
-//
-//        doRealmTransaction(realmConfiguration) {
-//            // Delete any previous store request with the same parameters
-//            it.where()
-//                    .equalTo(IncomingRoomKeyRequestEntityFields.USER_ID, incomingRoomKeyRequest.userId)
-//                    .equalTo(IncomingRoomKeyRequestEntityFields.DEVICE_ID, incomingRoomKeyRequest.deviceId)
-//                    .equalTo(IncomingRoomKeyRequestEntityFields.REQUEST_ID, incomingRoomKeyRequest.requestId)
-//                    .findAll()
-//                    .deleteAllFromRealm()
-//
-//            // Then store it
-//            it.createObject(IncomingRoomKeyRequestEntity::class.java).apply {
-//                userId = incomingRoomKeyRequest.userId
-//                deviceId = incomingRoomKeyRequest.deviceId
-//                requestId = incomingRoomKeyRequest.requestId
-//                putRequestBody(incomingRoomKeyRequest.requestBody)
-//            }
-//        }
-//    }
-
-//    override fun deleteIncomingRoomKeyRequest(incomingRoomKeyRequest: IncomingShareRequestCommon) {
-//        doRealmTransaction(realmConfiguration) {
-//            it.where()
-//                    .equalTo(GossipingEventEntityFields.TYPE, EventType.ROOM_KEY_REQUEST)
-//                    .notEqualTo(GossipingEventEntityFields.SENDER, credentials.userId)
-//                    .findAll()
-//                    .filter {
-//                        ContentMapper.map(it.content).toModel()?.let {
-//
-//                        }
-//                    }
-// //                    .equalTo(IncomingRoomKeyRequestEntityFields.USER_ID, incomingRoomKeyRequest.userId)
-// //                    .equalTo(IncomingRoomKeyRequestEntityFields.DEVICE_ID, incomingRoomKeyRequest.deviceId)
-// //                    .equalTo(IncomingRoomKeyRequestEntityFields.REQUEST_ID, incomingRoomKeyRequest.requestId)
-// //                    .findAll()
-// //                    .deleteAllFromRealm()
-//        }
-//    }
-
-    override fun updateGossipingRequestState(requestUserId: String?,
-                                             requestDeviceId: String?,
-                                             requestId: String?,
-                                             state: GossipingRequestState) {
-        doRealmTransaction(realmConfiguration) { realm ->
-            realm.where()
-                    .equalTo(IncomingGossipingRequestEntityFields.OTHER_USER_ID, requestUserId)
-                    .equalTo(IncomingGossipingRequestEntityFields.OTHER_DEVICE_ID, requestDeviceId)
-                    .equalTo(IncomingGossipingRequestEntityFields.REQUEST_ID, requestId)
-                    .findAll().forEach {
-                        it.requestState = state
-                    }
-        }
-    }
-
-    override fun updateOutgoingGossipingRequestState(requestId: String, state: OutgoingGossipingRequestState) {
-        doRealmTransaction(realmConfiguration) { realm ->
-            realm.where()
-                    .equalTo(OutgoingGossipingRequestEntityFields.REQUEST_ID, requestId)
-                    .findAll().forEach {
-                        it.requestState = state
-                    }
-        }
-    }
-
-    override fun getIncomingRoomKeyRequest(userId: String, deviceId: String, requestId: String): IncomingRoomKeyRequest? {
-        return doWithRealm(realmConfiguration) { realm ->
-            realm.where()
-                    .equalTo(IncomingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
-                    .equalTo(IncomingGossipingRequestEntityFields.OTHER_DEVICE_ID, deviceId)
-                    .equalTo(IncomingGossipingRequestEntityFields.OTHER_USER_ID, userId)
-                    .findAll()
-                    .mapNotNull { entity ->
-                        entity.toIncomingGossipingRequest() as? IncomingRoomKeyRequest
-                    }
-                    .firstOrNull()
-        }
-    }
-
-    override fun getPendingIncomingRoomKeyRequests(): List {
-        return doWithRealm(realmConfiguration) {
-            it.where()
-                    .equalTo(IncomingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
-                    .equalTo(IncomingGossipingRequestEntityFields.REQUEST_STATE_STR, GossipingRequestState.PENDING.name)
-                    .findAll()
-                    .map { entity ->
-                        IncomingRoomKeyRequest(
-                                userId = entity.otherUserId,
-                                deviceId = entity.otherDeviceId,
-                                requestId = entity.requestId,
-                                requestBody = entity.getRequestedKeyInfo(),
-                                localCreationTimestamp = entity.localCreationTimestamp
-                        )
-                    }
-        }
-    }
-
-    override fun getPendingIncomingGossipingRequests(): List {
-        return doWithRealm(realmConfiguration) {
-            it.where()
-                    .equalTo(IncomingGossipingRequestEntityFields.REQUEST_STATE_STR, GossipingRequestState.PENDING.name)
-                    .findAll()
-                    .mapNotNull { entity ->
-                        when (entity.type) {
-                            GossipRequestType.KEY -> {
-                                IncomingRoomKeyRequest(
-                                        userId = entity.otherUserId,
-                                        deviceId = entity.otherDeviceId,
-                                        requestId = entity.requestId,
-                                        requestBody = entity.getRequestedKeyInfo(),
-                                        localCreationTimestamp = entity.localCreationTimestamp
-                                )
-                            }
-                            GossipRequestType.SECRET -> {
-                                IncomingSecretShareRequest(
-                                        userId = entity.otherUserId,
-                                        deviceId = entity.otherDeviceId,
-                                        requestId = entity.requestId,
-                                        secretName = entity.getRequestedSecretName(),
-                                        localCreationTimestamp = entity.localCreationTimestamp
-                                )
-                            }
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.REQUEST_ID, requestId)
+                    .findFirst()?.apply {
+                        this.requestState = newState
+                        if (newState == OutgoingRoomKeyRequestState.UNSENT) {
+                            // clear the old replies
+                            this.replies.deleteAllFromRealm()
                         }
                     }
         }
     }
 
-    override fun storeIncomingGossipingRequest(request: IncomingShareRequestCommon, ageLocalTS: Long?) {
-        doRealmTransactionAsync(realmConfiguration) { realm ->
-
-            // After a clear cache, we might have a
-
-            realm.createObject(IncomingGossipingRequestEntity::class.java).let {
-                it.otherDeviceId = request.deviceId
-                it.otherUserId = request.userId
-                it.requestId = request.requestId ?: ""
-                it.requestState = GossipingRequestState.PENDING
-                it.localCreationTimestamp = ageLocalTS ?: clock.epochMillis()
-                if (request is IncomingSecretShareRequest) {
-                    it.type = GossipRequestType.SECRET
-                    it.requestedInfoStr = request.secretName
-                } else if (request is IncomingRoomKeyRequest) {
-                    it.type = GossipRequestType.KEY
-                    it.requestedInfoStr = request.requestBody?.toJson()
-                }
-            }
-        }
-    }
-
-    override fun storeIncomingGossipingRequests(requests: List) {
-        doRealmTransactionAsync(realmConfiguration) { realm ->
-            requests.forEach { request ->
-                // After a clear cache, we might have a
-                realm.createObject(IncomingGossipingRequestEntity::class.java).let {
-                    it.otherDeviceId = request.deviceId
-                    it.otherUserId = request.userId
-                    it.requestId = request.requestId ?: ""
-                    it.requestState = GossipingRequestState.PENDING
-                    it.localCreationTimestamp = request.localCreationTimestamp ?: clock.epochMillis()
-                    if (request is IncomingSecretShareRequest) {
-                        it.type = GossipRequestType.SECRET
-                        it.requestedInfoStr = request.secretName
-                    } else if (request is IncomingRoomKeyRequest) {
-                        it.type = GossipRequestType.KEY
-                        it.requestedInfoStr = request.requestBody?.toJson()
+    override fun updateOutgoingRoomKeyRequiredIndex(requestId: String, newIndex: Int) {
+        doRealmTransaction(realmConfiguration) { realm ->
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.REQUEST_ID, requestId)
+                    .findFirst()?.apply {
+                        this.requestedIndex = newIndex
                     }
+        }
+    }
+
+    override fun updateOutgoingRoomKeyReply(roomId: String,
+                                            sessionId: String,
+                                            algorithm: String,
+                                            senderKey: String,
+                                            fromDevice: String?,
+                                            event: Event) {
+        doRealmTransaction(realmConfiguration) { realm ->
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.ROOM_ID, roomId)
+                    .equalTo(OutgoingKeyRequestEntityFields.MEGOLM_SESSION_ID, sessionId)
+                    .findAll().firstOrNull { entity ->
+                        entity.toOutgoingKeyRequest().let {
+                            it.requestBody?.senderKey == senderKey &&
+                                    it.requestBody?.algorithm == algorithm
+                        }
+                    }?.apply {
+                        event.senderId?.let { addReply(it, fromDevice, event) }
+                    }
+        }
+    }
+
+    override fun deleteOutgoingRoomKeyRequest(requestId: String) {
+        doRealmTransaction(realmConfiguration) { realm ->
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.REQUEST_ID, requestId)
+                    .findFirst()?.deleteOnCascade()
+        }
+    }
+
+    override fun deleteOutgoingRoomKeyRequestInState(state: OutgoingRoomKeyRequestState) {
+        doRealmTransaction(realmConfiguration) { realm ->
+            realm.where()
+                    .equalTo(OutgoingKeyRequestEntityFields.REQUEST_STATE_STR, state.name)
+                    .findAll()
+                    // I delete like this because I want to cascade delete replies?
+                    .onEach { it.deleteOnCascade() }
+        }
+    }
+
+    override fun saveIncomingKeyRequestAuditTrail(
+            requestId: String,
+            roomId: String,
+            sessionId: String,
+            senderKey: String,
+            algorithm: String,
+            fromUser: String,
+            fromDevice: String) {
+        monarchy.writeAsync { realm ->
+            val now = clock.epochMillis()
+            realm.createObject().apply {
+                this.ageLocalTs = now
+                this.type = TrailType.IncomingKeyRequest.name
+                val info = IncomingKeyRequestInfo(
+                        roomId = roomId,
+                        sessionId = sessionId,
+                        senderKey = senderKey,
+                        alg = algorithm,
+                        userId = fromUser,
+                        deviceId = fromDevice,
+                        requestId = requestId
+                )
+                MoshiProvider.providesMoshi().adapter(IncomingKeyRequestInfo::class.java).toJson(info)?.let {
+                    this.contentJson = it
                 }
             }
         }
     }
 
-//    override fun getPendingIncomingSecretShareRequests(): List {
-//        return doRealmQueryAndCopyList(realmConfiguration) {
-//            it.where()
-//                    .findAll()
-//        }.map {
-//            it.toIncomingSecretShareRequest()
-//        }
-//    }
+    override fun saveWithheldAuditTrail(roomId: String,
+                                        sessionId: String,
+                                        senderKey: String,
+                                        algorithm: String,
+                                        code: WithHeldCode,
+                                        userId: String,
+                                        deviceId: String) {
+        monarchy.writeAsync { realm ->
+            val now = clock.epochMillis()
+            realm.createObject().apply {
+                this.ageLocalTs = now
+                this.type = TrailType.OutgoingKeyWithheld.name
+                val info = WithheldInfo(
+                        roomId = roomId,
+                        sessionId = sessionId,
+                        senderKey = senderKey,
+                        alg = algorithm,
+                        code = code,
+                        userId = userId,
+                        deviceId = deviceId
+                )
+                MoshiProvider.providesMoshi().adapter(WithheldInfo::class.java).toJson(info)?.let {
+                    this.contentJson = it
+                }
+            }
+        }
+    }
+
+    override fun saveForwardKeyAuditTrail(roomId: String,
+                                          sessionId: String,
+                                          senderKey: String,
+                                          algorithm: String,
+                                          userId: String,
+                                          deviceId: String,
+                                          chainIndex: Long?) {
+        saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, false)
+    }
+
+    override fun saveIncomingForwardKeyAuditTrail(roomId: String,
+                                                  sessionId: String,
+                                                  senderKey: String,
+                                                  algorithm: String,
+                                                  userId: String,
+                                                  deviceId: String,
+                                                  chainIndex: Long?) {
+        saveForwardKeyTrail(roomId, sessionId, senderKey, algorithm, userId, deviceId, chainIndex, true)
+    }
+
+    private fun saveForwardKeyTrail(roomId: String,
+                                    sessionId: String,
+                                    senderKey: String,
+                                    algorithm: String,
+                                    userId: String,
+                                    deviceId: String,
+                                    chainIndex: Long?,
+                                    incoming: Boolean
+    ) {
+        monarchy.writeAsync { realm ->
+            val now = clock.epochMillis()
+            realm.createObject().apply {
+                this.ageLocalTs = now
+                this.type = if (incoming) TrailType.IncomingKeyForward.name else TrailType.OutgoingKeyForward.name
+                val info = ForwardInfo(
+                        roomId = roomId,
+                        sessionId = sessionId,
+                        senderKey = senderKey,
+                        alg = algorithm,
+                        userId = userId,
+                        deviceId = deviceId,
+                        chainIndex = chainIndex
+                )
+                MoshiProvider.providesMoshi().adapter(ForwardInfo::class.java).toJson(info)?.let {
+                    this.contentJson = it
+                }
+            }
+        }
+    }
 
     /* ==========================================================================================
      * Cross Signing
@@ -1513,37 +1468,34 @@ internal class RealmCryptoStore @Inject constructor(
         }
     }
 
-    override fun getOutgoingRoomKeyRequests(): List {
+    override fun getOutgoingRoomKeyRequests(): List {
         return monarchy.fetchAllMappedSync({ realm ->
             realm
-                    .where(OutgoingGossipingRequestEntity::class.java)
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
+                    .where(OutgoingKeyRequestEntity::class.java)
         }, { entity ->
-            entity.toOutgoingGossipingRequest() as? OutgoingRoomKeyRequest
+            entity.toOutgoingKeyRequest()
         })
                 .filterNotNull()
     }
 
-    override fun getOutgoingSecretKeyRequests(): List {
+    override fun getOutgoingRoomKeyRequests(inStates: Set): List {
         return monarchy.fetchAllMappedSync({ realm ->
             realm
-                    .where(OutgoingGossipingRequestEntity::class.java)
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.SECRET.name)
+                    .where(OutgoingKeyRequestEntity::class.java)
+                    .`in`(OutgoingKeyRequestEntityFields.REQUEST_STATE_STR, inStates.map { it.name }.toTypedArray())
         }, { entity ->
-            entity.toOutgoingGossipingRequest() as? OutgoingSecretRequest
+            entity.toOutgoingKeyRequest()
         })
                 .filterNotNull()
     }
 
-    override fun getOutgoingRoomKeyRequestsPaged(): LiveData> {
+    override fun getOutgoingRoomKeyRequestsPaged(): LiveData> {
         val realmDataSourceFactory = monarchy.createDataSourceFactory { realm ->
             realm
-                    .where(OutgoingGossipingRequestEntity::class.java)
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
+                    .where(OutgoingKeyRequestEntity::class.java)
         }
         val dataSourceFactory = realmDataSourceFactory.map {
-            it.toOutgoingGossipingRequest() as? OutgoingRoomKeyRequest
-                    ?: OutgoingRoomKeyRequest(requestBody = null, requestId = "?", recipients = emptyMap(), state = OutgoingGossipingRequestState.CANCELLED)
+            it.toOutgoingKeyRequest()
         }
         val trail = monarchy.findAllPagedWithChanges(
                 realmDataSourceFactory,
@@ -1715,33 +1667,27 @@ internal class RealmCryptoStore @Inject constructor(
     }
 
     /**
-     * Some entries in the DB can get a bit out of control with time
-     * So we need to tidy up a bit
+     * Some entries in the DB can get a bit out of control with time.
+     * So we need to tidy up a bit.
      */
     override fun tidyUpDataBase() {
         val prevWeekTs = clock.epochMillis() - 7 * 24 * 60 * 60 * 1_000
         doRealmTransaction(realmConfiguration) { realm ->
 
-            // Only keep one week history
-            realm.where()
-                    .lessThan(IncomingGossipingRequestEntityFields.LOCAL_CREATION_TIMESTAMP, prevWeekTs)
+            // Clean the old ones?
+            realm.where()
+                    .lessThan(OutgoingKeyRequestEntityFields.CREATION_TIME_STAMP, prevWeekTs)
                     .findAll()
-                    .also { Timber.i("## Crypto Clean up ${it.size} IncomingGossipingRequestEntity") }
+                    .also { Timber.i("## Crypto Clean up ${it.size} OutgoingKeyRequestEntity") }
                     .deleteAllFromRealm()
 
-            // Clean the cancelled ones?
-            realm.where()
-                    .equalTo(OutgoingGossipingRequestEntityFields.REQUEST_STATE_STR, OutgoingGossipingRequestState.CANCELLED.name)
-                    .equalTo(OutgoingGossipingRequestEntityFields.TYPE_STR, GossipRequestType.KEY.name)
-                    .findAll()
-                    .also { Timber.i("## Crypto Clean up ${it.size} OutgoingGossipingRequestEntity") }
-                    .deleteAllFromRealm()
+            // Only keep one month history
 
-            // Only keep one week history
-            realm.where()
-                    .lessThan(GossipingEventEntityFields.AGE_LOCAL_TS, prevWeekTs)
+            val prevMonthTs = clock.epochMillis() - 4 * 7 * 24 * 60 * 60 * 1_000L
+            realm.where()
+                    .lessThan(AuditTrailEntityFields.AGE_LOCAL_TS, prevMonthTs)
                     .findAll()
-                    .also { Timber.i("## Crypto Clean up ${it.size} GossipingEventEntityFields") }
+                    .also { Timber.i("## Crypto Clean up ${it.size} AuditTrailEntity") }
                     .deleteAllFromRealm()
 
             // Can we do something for WithHeldSessionEntity?
@@ -1749,7 +1695,7 @@ internal class RealmCryptoStore @Inject constructor(
     }
 
     /**
-     * Prints out database info
+     * Prints out database info.
      */
     override fun logDbUsageInfo() {
         RealmDebugTools(realmConfiguration).logInfo("Crypto")
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreMigration.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreMigration.kt
index 32f24c5d2e..02c2a27dec 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreMigration.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreMigration.kt
@@ -33,6 +33,7 @@ import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo
 import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo013
 import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo014
 import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo015
+import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo016
 import org.matrix.android.sdk.internal.util.time.Clock
 import timber.log.Timber
 import javax.inject.Inject
@@ -41,8 +42,8 @@ internal class RealmCryptoStoreMigration @Inject constructor(
         private val clock: Clock,
 ) : RealmMigration {
     /**
-     * Forces all RealmCryptoStoreMigration instances to be equal
-     * Avoids Realm throwing when multiple instances of the migration are set
+     * Forces all RealmCryptoStoreMigration instances to be equal.
+     * Avoids Realm throwing when multiple instances of the migration are set.
      */
     override fun equals(other: Any?) = other is RealmCryptoStoreMigration
     override fun hashCode() = 5000
@@ -50,7 +51,7 @@ internal class RealmCryptoStoreMigration @Inject constructor(
     // 0, 1, 2: legacy Riot-Android
     // 3: migrate to RiotX schema
     // 4, 5, 6, 7, 8, 9: migrations from RiotX (which was previously 1, 2, 3, 4, 5, 6)
-    val schemaVersion = 15L
+    val schemaVersion = 16L
 
     override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) {
         Timber.d("Migrating Realm Crypto from $oldVersion to $newVersion")
@@ -70,5 +71,6 @@ internal class RealmCryptoStoreMigration @Inject constructor(
         if (oldVersion < 13) MigrateCryptoTo013(realm).perform()
         if (oldVersion < 14) MigrateCryptoTo014(realm).perform()
         if (oldVersion < 15) MigrateCryptoTo015(realm).perform()
+        if (oldVersion < 16) MigrateCryptoTo016(realm).perform()
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreModule.kt
index b4c94a7fd1..6696cf8281 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreModule.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreModule.kt
@@ -17,26 +17,26 @@
 package org.matrix.android.sdk.internal.crypto.store.db
 
 import io.realm.annotations.RealmModule
+import org.matrix.android.sdk.internal.crypto.store.db.model.AuditTrailEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.CrossSigningInfoEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoMetadataEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoRoomEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.DeviceInfoEntity
-import org.matrix.android.sdk.internal.crypto.store.db.model.GossipingEventEntity
-import org.matrix.android.sdk.internal.crypto.store.db.model.IncomingGossipingRequestEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.KeyInfoEntity
+import org.matrix.android.sdk.internal.crypto.store.db.model.KeyRequestReplyEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.KeysBackupDataEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.MyDeviceLastSeenInfoEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.OlmInboundGroupSessionEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.OlmSessionEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.OutboundGroupSessionInfoEntity
-import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingGossipingRequestEntity
+import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingKeyRequestEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.SharedSessionEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.TrustLevelEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.UserEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.WithHeldSessionEntity
 
 /**
- * Realm module for Crypto store classes
+ * Realm module for Crypto store classes.
  */
 @RealmModule(
         library = true,
@@ -51,9 +51,9 @@ import org.matrix.android.sdk.internal.crypto.store.db.model.WithHeldSessionEnti
             KeyInfoEntity::class,
             CrossSigningInfoEntity::class,
             TrustLevelEntity::class,
-            GossipingEventEntity::class,
-            IncomingGossipingRequestEntity::class,
-            OutgoingGossipingRequestEntity::class,
+            AuditTrailEntity::class,
+            OutgoingKeyRequestEntity::class,
+            KeyRequestReplyEntity::class,
             MyDeviceLastSeenInfoEntity::class,
             WithHeldSessionEntity::class,
             SharedSessionEntity::class,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo005.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo005.kt
index e1d7598767..8ec2932a8f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo005.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo005.kt
@@ -17,9 +17,6 @@
 package org.matrix.android.sdk.internal.crypto.store.db.migration
 
 import io.realm.DynamicRealm
-import org.matrix.android.sdk.internal.crypto.store.db.model.GossipingEventEntityFields
-import org.matrix.android.sdk.internal.crypto.store.db.model.IncomingGossipingRequestEntityFields
-import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingGossipingRequestEntityFields
 import org.matrix.android.sdk.internal.util.database.RealmMigrator
 
 internal class MigrateCryptoTo005(realm: DynamicRealm) : RealmMigrator(realm, 5) {
@@ -29,38 +26,37 @@ internal class MigrateCryptoTo005(realm: DynamicRealm) : RealmMigrator(realm, 5)
         realm.schema.remove("IncomingRoomKeyRequestEntity")
 
         // Not need to migrate existing request, just start fresh?
-
         realm.schema.create("GossipingEventEntity")
-                .addField(GossipingEventEntityFields.TYPE, String::class.java)
-                .addIndex(GossipingEventEntityFields.TYPE)
-                .addField(GossipingEventEntityFields.CONTENT, String::class.java)
-                .addField(GossipingEventEntityFields.SENDER, String::class.java)
-                .addIndex(GossipingEventEntityFields.SENDER)
-                .addField(GossipingEventEntityFields.DECRYPTION_RESULT_JSON, String::class.java)
-                .addField(GossipingEventEntityFields.DECRYPTION_ERROR_CODE, String::class.java)
-                .addField(GossipingEventEntityFields.AGE_LOCAL_TS, Long::class.java)
-                .setNullable(GossipingEventEntityFields.AGE_LOCAL_TS, true)
-                .addField(GossipingEventEntityFields.SEND_STATE_STR, String::class.java)
+                .addField("type", String::class.java)
+                .addIndex("type")
+                .addField("content", String::class.java)
+                .addField("sender", String::class.java)
+                .addIndex("sender")
+                .addField("decryptionResultJson", String::class.java)
+                .addField("decryptionErrorCode", String::class.java)
+                .addField("ageLocalTs", Long::class.java)
+                .setNullable("ageLocalTs", true)
+                .addField("sendStateStr", String::class.java)
 
         realm.schema.create("IncomingGossipingRequestEntity")
-                .addField(IncomingGossipingRequestEntityFields.REQUEST_ID, String::class.java)
-                .addIndex(IncomingGossipingRequestEntityFields.REQUEST_ID)
-                .addField(IncomingGossipingRequestEntityFields.TYPE_STR, String::class.java)
-                .addIndex(IncomingGossipingRequestEntityFields.TYPE_STR)
-                .addField(IncomingGossipingRequestEntityFields.OTHER_USER_ID, String::class.java)
-                .addField(IncomingGossipingRequestEntityFields.REQUESTED_INFO_STR, String::class.java)
-                .addField(IncomingGossipingRequestEntityFields.OTHER_DEVICE_ID, String::class.java)
-                .addField(IncomingGossipingRequestEntityFields.REQUEST_STATE_STR, String::class.java)
-                .addField(IncomingGossipingRequestEntityFields.LOCAL_CREATION_TIMESTAMP, Long::class.java)
-                .setNullable(IncomingGossipingRequestEntityFields.LOCAL_CREATION_TIMESTAMP, true)
+                .addField("requestId", String::class.java)
+                .addIndex("requestId")
+                .addField("typeStr", String::class.java)
+                .addIndex("typeStr")
+                .addField("otherUserId", String::class.java)
+                .addField("requestedInfoStr", String::class.java)
+                .addField("otherDeviceId", String::class.java)
+                .addField("requestStateStr", String::class.java)
+                .addField("localCreationTimestamp", Long::class.java)
+                .setNullable("localCreationTimestamp", true)
 
         realm.schema.create("OutgoingGossipingRequestEntity")
-                .addField(OutgoingGossipingRequestEntityFields.REQUEST_ID, String::class.java)
-                .addIndex(OutgoingGossipingRequestEntityFields.REQUEST_ID)
-                .addField(OutgoingGossipingRequestEntityFields.RECIPIENTS_DATA, String::class.java)
-                .addField(OutgoingGossipingRequestEntityFields.REQUESTED_INFO_STR, String::class.java)
-                .addField(OutgoingGossipingRequestEntityFields.TYPE_STR, String::class.java)
-                .addIndex(OutgoingGossipingRequestEntityFields.TYPE_STR)
-                .addField(OutgoingGossipingRequestEntityFields.REQUEST_STATE_STR, String::class.java)
+                .addField("requestId", String::class.java)
+                .addIndex("requestId")
+                .addField("recipientsData", String::class.java)
+                .addField("requestedInfoStr", String::class.java)
+                .addField("typeStr", String::class.java)
+                .addIndex("typeStr")
+                .addField("requestStateStr", String::class.java)
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo007.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo007.kt
index 718b9787d2..0e221e78f3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo007.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo007.kt
@@ -42,7 +42,7 @@ internal class MigrateCryptoTo007(realm: DynamicRealm) : RealmMigrator(realm, 7)
                 val jsonSignatures = crossSigningKeysMapper.serializeSignatures(objectSignatures)
                 it.setString(KeyInfoEntityFields.SIGNATURES, jsonSignatures)
             }
-        } catch (failure: Throwable) {
+        } catch (ignore: Throwable) {
         }
 
         // Migrate frozen classes
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo016.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo016.kt
new file mode 100644
index 0000000000..5a14ebf85a
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/migration/MigrateCryptoTo016.kt
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto.store.db.migration
+
+import io.realm.DynamicRealm
+import org.matrix.android.sdk.internal.crypto.store.db.model.AuditTrailEntityFields
+import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoMetadataEntityFields
+import org.matrix.android.sdk.internal.crypto.store.db.model.KeyRequestReplyEntityFields
+import org.matrix.android.sdk.internal.crypto.store.db.model.OutgoingKeyRequestEntityFields
+import org.matrix.android.sdk.internal.util.database.RealmMigrator
+
+internal class MigrateCryptoTo016(realm: DynamicRealm) : RealmMigrator(realm, 16) {
+
+    override fun doMigrate(realm: DynamicRealm) {
+        realm.schema.remove("OutgoingGossipingRequestEntity")
+        realm.schema.remove("IncomingGossipingRequestEntity")
+        realm.schema.remove("GossipingEventEntity")
+
+        // No need to migrate existing request, just start fresh
+
+        val replySchema = realm.schema.create("KeyRequestReplyEntity")
+                .addField(KeyRequestReplyEntityFields.SENDER_ID, String::class.java)
+                .addField(KeyRequestReplyEntityFields.FROM_DEVICE, String::class.java)
+                .addField(KeyRequestReplyEntityFields.EVENT_JSON, String::class.java)
+
+        realm.schema.create("OutgoingKeyRequestEntity")
+                .addField(OutgoingKeyRequestEntityFields.REQUEST_ID, String::class.java)
+                .addIndex(OutgoingKeyRequestEntityFields.REQUEST_ID)
+                .addField(OutgoingKeyRequestEntityFields.MEGOLM_SESSION_ID, String::class.java)
+                .addIndex(OutgoingKeyRequestEntityFields.MEGOLM_SESSION_ID)
+                .addRealmListField(OutgoingKeyRequestEntityFields.REPLIES.`$`, replySchema)
+                .addField(OutgoingKeyRequestEntityFields.RECIPIENTS_DATA, String::class.java)
+                .addField(OutgoingKeyRequestEntityFields.REQUEST_STATE_STR, String::class.java)
+                .addIndex(OutgoingKeyRequestEntityFields.REQUEST_STATE_STR)
+                .addField(OutgoingKeyRequestEntityFields.REQUESTED_INFO_STR, String::class.java)
+                .addField(OutgoingKeyRequestEntityFields.ROOM_ID, String::class.java)
+                .addIndex(OutgoingKeyRequestEntityFields.ROOM_ID)
+                .addField(OutgoingKeyRequestEntityFields.REQUESTED_INDEX, Integer::class.java)
+                .addField(OutgoingKeyRequestEntityFields.CREATION_TIME_STAMP, Long::class.java)
+                .setNullable(OutgoingKeyRequestEntityFields.CREATION_TIME_STAMP, true)
+
+        realm.schema.create("AuditTrailEntity")
+                .addField(AuditTrailEntityFields.AGE_LOCAL_TS, Long::class.java)
+                .setNullable(AuditTrailEntityFields.AGE_LOCAL_TS, true)
+                .addField(AuditTrailEntityFields.CONTENT_JSON, String::class.java)
+                .addField(AuditTrailEntityFields.TYPE, String::class.java)
+                .addIndex(AuditTrailEntityFields.TYPE)
+
+        realm.schema.get("CryptoMetadataEntity")
+                ?.addField(CryptoMetadataEntityFields.GLOBAL_ENABLE_KEY_GOSSIPING, Boolean::class.java)
+                ?.transform {
+                    // set the default value to true
+                    it.setBoolean(CryptoMetadataEntityFields.GLOBAL_ENABLE_KEY_GOSSIPING, true)
+                }
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXWithHeldExtension.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailEntity.kt
similarity index 60%
rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXWithHeldExtension.kt
rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailEntity.kt
index 585bcdbbde..2e0e9c8c8b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXWithHeldExtension.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailEntity.kt
@@ -1,5 +1,5 @@
 /*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
+ * Copyright 2022 The Matrix.org Foundation C.I.C.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,10 +14,15 @@
  * limitations under the License.
  */
 
-package org.matrix.android.sdk.internal.crypto.algorithms
+package org.matrix.android.sdk.internal.crypto.store.db.model
 
-import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
+import io.realm.RealmObject
+import io.realm.annotations.Index
 
-internal interface IMXWithHeldExtension {
-    fun onRoomKeyWithHeldEvent(withHeldInfo: RoomKeyWithHeldContent)
+internal open class AuditTrailEntity(
+        var ageLocalTs: Long? = null,
+        @Index var type: String? = null,
+        var contentJson: String? = null
+) : RealmObject() {
+    companion object
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailMapper.kt
new file mode 100644
index 0000000000..80ae4a8d0d
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/AuditTrailMapper.kt
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto.store.db.model
+
+import org.matrix.android.sdk.api.extensions.tryOrNull
+import org.matrix.android.sdk.api.session.crypto.model.AuditTrail
+import org.matrix.android.sdk.api.session.crypto.model.ForwardInfo
+import org.matrix.android.sdk.api.session.crypto.model.IncomingKeyRequestInfo
+import org.matrix.android.sdk.api.session.crypto.model.TrailType
+import org.matrix.android.sdk.api.session.crypto.model.UnknownInfo
+import org.matrix.android.sdk.api.session.crypto.model.WithheldInfo
+import org.matrix.android.sdk.internal.di.MoshiProvider
+
+internal object AuditTrailMapper {
+
+    fun map(entity: AuditTrailEntity): AuditTrail? {
+        val contentJson = entity.contentJson ?: return null
+        return when (entity.type) {
+            TrailType.OutgoingKeyForward.name  -> {
+                val info = tryOrNull {
+                    MoshiProvider.providesMoshi().adapter(ForwardInfo::class.java).fromJson(contentJson)
+                } ?: return null
+                AuditTrail(
+                        ageLocalTs = entity.ageLocalTs ?: 0,
+                        type = TrailType.OutgoingKeyForward,
+                        info = info
+                )
+            }
+            TrailType.OutgoingKeyWithheld.name -> {
+                val info = tryOrNull {
+                    MoshiProvider.providesMoshi().adapter(WithheldInfo::class.java).fromJson(contentJson)
+                } ?: return null
+                AuditTrail(
+                        ageLocalTs = entity.ageLocalTs ?: 0,
+                        type = TrailType.OutgoingKeyWithheld,
+                        info = info
+                )
+            }
+            TrailType.IncomingKeyRequest.name  -> {
+                val info = tryOrNull {
+                    MoshiProvider.providesMoshi().adapter(IncomingKeyRequestInfo::class.java).fromJson(contentJson)
+                } ?: return null
+                AuditTrail(
+                        ageLocalTs = entity.ageLocalTs ?: 0,
+                        type = TrailType.IncomingKeyRequest,
+                        info = info
+                )
+            }
+            TrailType.IncomingKeyForward.name  -> {
+                val info = tryOrNull {
+                    MoshiProvider.providesMoshi().adapter(ForwardInfo::class.java).fromJson(contentJson)
+                } ?: return null
+                AuditTrail(
+                        ageLocalTs = entity.ageLocalTs ?: 0,
+                        type = TrailType.IncomingKeyForward,
+                        info = info
+                )
+            }
+            else                               -> {
+                AuditTrail(
+                        ageLocalTs = entity.ageLocalTs ?: 0,
+                        type = TrailType.Unknown,
+                        info = UnknownInfo
+                )
+            }
+        }
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/CryptoMetadataEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/CryptoMetadataEntity.kt
index 35ae86db8b..63ed0e537e 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/CryptoMetadataEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/CryptoMetadataEntity.kt
@@ -33,6 +33,8 @@ internal open class CryptoMetadataEntity(
         var deviceSyncToken: String? = null,
         // Settings for blacklisting unverified devices.
         var globalBlacklistUnverifiedDevices: Boolean = false,
+        // setting to enable or disable key gossiping
+        var globalEnableKeyGossiping: Boolean = true,
         // The keys backup version currently used. Null means no backup.
         var backupVersion: String? = null,
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/GossipingEventEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/GossipingEventEntity.kt
deleted file mode 100644
index a024e092b7..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/GossipingEventEntity.kt
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto.store.db.model
-
-import com.squareup.moshi.JsonDataException
-import io.realm.RealmObject
-import io.realm.annotations.Index
-import org.matrix.android.sdk.api.session.crypto.MXCryptoError
-import org.matrix.android.sdk.api.session.crypto.model.MXEventDecryptionResult
-import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult
-import org.matrix.android.sdk.api.session.events.model.Event
-import org.matrix.android.sdk.api.session.room.send.SendState
-import org.matrix.android.sdk.internal.database.mapper.ContentMapper
-import org.matrix.android.sdk.internal.di.MoshiProvider
-import timber.log.Timber
-
-/**
- * Keep track of gossiping event received in toDevice messages
- * (room key request, or sss secret sharing, as well as cancellations)
- *
- */
-internal open class GossipingEventEntity(@Index var type: String? = "",
-                                         var content: String? = null,
-                                         @Index var sender: String? = null,
-                                         var decryptionResultJson: String? = null,
-                                         var decryptionErrorCode: String? = null,
-                                         var ageLocalTs: Long? = null) : RealmObject() {
-
-    private var sendStateStr: String = SendState.UNKNOWN.name
-
-    var sendState: SendState
-        get() {
-            return SendState.valueOf(sendStateStr)
-        }
-        set(value) {
-            sendStateStr = value.name
-        }
-
-    companion object
-
-    fun setDecryptionResult(result: MXEventDecryptionResult) {
-        val decryptionResult = OlmDecryptionResult(
-                payload = result.clearEvent,
-                senderKey = result.senderCurve25519Key,
-                keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) },
-                forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain
-        )
-        val adapter = MoshiProvider.providesMoshi().adapter(OlmDecryptionResult::class.java)
-        decryptionResultJson = adapter.toJson(decryptionResult)
-        decryptionErrorCode = null
-    }
-
-    fun toModel(): Event {
-        return Event(
-                type = this.type ?: "",
-                content = ContentMapper.map(this.content),
-                senderId = this.sender
-        ).also {
-            it.ageLocalTs = this.ageLocalTs
-            it.sendState = this.sendState
-            this.decryptionResultJson?.let { json ->
-                try {
-                    it.mxDecryptionResult = MoshiProvider.providesMoshi().adapter(OlmDecryptionResult::class.java).fromJson(json)
-                } catch (t: JsonDataException) {
-                    Timber.e(t, "Failed to parse decryption result")
-                }
-            }
-            // TODO get the full crypto error object
-            it.mCryptoError = this.decryptionErrorCode?.let { errorCode ->
-                MXCryptoError.ErrorType.valueOf(errorCode)
-            }
-        }
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/IncomingGossipingRequestEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/IncomingGossipingRequestEntity.kt
deleted file mode 100644
index f05c8853c8..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/IncomingGossipingRequestEntity.kt
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto.store.db.model
-
-import io.realm.RealmObject
-import io.realm.annotations.Index
-import org.matrix.android.sdk.api.extensions.tryOrNull
-import org.matrix.android.sdk.api.session.crypto.model.GossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.IncomingSecretShareRequest
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
-import org.matrix.android.sdk.internal.crypto.GossipRequestType
-import org.matrix.android.sdk.internal.crypto.IncomingShareRequestCommon
-
-internal open class IncomingGossipingRequestEntity(@Index var requestId: String? = "",
-                                                   @Index var typeStr: String? = null,
-                                                   var otherUserId: String? = null,
-                                                   var requestedInfoStr: String? = null,
-                                                   var otherDeviceId: String? = null,
-                                                   var localCreationTimestamp: Long? = null
-) : RealmObject() {
-
-    fun getRequestedSecretName(): String? = if (type == GossipRequestType.SECRET) {
-        requestedInfoStr
-    } else null
-
-    fun getRequestedKeyInfo(): RoomKeyRequestBody? = if (type == GossipRequestType.KEY) {
-        RoomKeyRequestBody.fromJson(requestedInfoStr)
-    } else null
-
-    var type: GossipRequestType
-        get() {
-            return tryOrNull { typeStr?.let { GossipRequestType.valueOf(it) } } ?: GossipRequestType.KEY
-        }
-        set(value) {
-            typeStr = value.name
-        }
-
-    private var requestStateStr: String = GossipingRequestState.NONE.name
-
-    var requestState: GossipingRequestState
-        get() {
-            return tryOrNull { GossipingRequestState.valueOf(requestStateStr) }
-                    ?: GossipingRequestState.NONE
-        }
-        set(value) {
-            requestStateStr = value.name
-        }
-
-    companion object
-
-    fun toIncomingGossipingRequest(): IncomingShareRequestCommon {
-        return when (type) {
-            GossipRequestType.KEY    -> {
-                IncomingRoomKeyRequest(
-                        requestBody = getRequestedKeyInfo(),
-                        deviceId = otherDeviceId,
-                        userId = otherUserId,
-                        requestId = requestId,
-                        state = requestState,
-                        localCreationTimestamp = localCreationTimestamp
-                )
-            }
-            GossipRequestType.SECRET -> {
-                IncomingSecretShareRequest(
-                        secretName = getRequestedSecretName(),
-                        deviceId = otherDeviceId,
-                        userId = otherUserId,
-                        requestId = requestId,
-                        localCreationTimestamp = localCreationTimestamp
-                )
-            }
-        }
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/KeyRequestReplyEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/KeyRequestReplyEntity.kt
new file mode 100644
index 0000000000..0c7cf79e78
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/KeyRequestReplyEntity.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto.store.db.model
+
+import io.realm.RealmObject
+import org.matrix.android.sdk.api.session.events.model.Event
+import org.matrix.android.sdk.internal.di.MoshiProvider
+
+internal open class KeyRequestReplyEntity(
+        var senderId: String? = null,
+        var fromDevice: String? = null,
+        var eventJson: String? = null
+) : RealmObject() {
+    companion object
+
+    fun getEvent(): Event? {
+        return eventJson?.let {
+            MoshiProvider.providesMoshi().adapter(Event::class.java).fromJson(it)
+        }
+    }
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/MyDeviceLastSeenInfoEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/MyDeviceLastSeenInfoEntity.kt
index 222711f9ac..74a81d5b01 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/MyDeviceLastSeenInfoEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/MyDeviceLastSeenInfoEntity.kt
@@ -20,13 +20,13 @@ import io.realm.RealmObject
 import io.realm.annotations.PrimaryKey
 
 internal open class MyDeviceLastSeenInfoEntity(
-        /**The device id*/
+        /** The device id. */
         @PrimaryKey var deviceId: String? = null,
-        /** The device display name*/
+        /** The device display name. */
         var displayName: String? = null,
         /** The last time this device has been seen. */
         var lastSeenTs: Long? = null,
-        /** The last ip address*/
+        /** The last ip address. */
         var lastSeenIp: String? = null
 ) : RealmObject() {
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingGossipingRequestEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingGossipingRequestEntity.kt
deleted file mode 100644
index 0e1278967e..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingGossipingRequestEntity.kt
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.matrix.android.sdk.internal.crypto.store.db.model
-
-import com.squareup.moshi.JsonAdapter
-import com.squareup.moshi.Types
-import io.realm.RealmObject
-import io.realm.annotations.Index
-import org.matrix.android.sdk.api.extensions.tryOrNull
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState
-import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest
-import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
-import org.matrix.android.sdk.internal.crypto.GossipRequestType
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequest
-import org.matrix.android.sdk.internal.crypto.OutgoingSecretRequest
-import org.matrix.android.sdk.internal.di.MoshiProvider
-
-internal open class OutgoingGossipingRequestEntity(
-        @Index var requestId: String? = null,
-        var recipientsData: String? = null,
-        var requestedInfoStr: String? = null,
-        @Index var typeStr: String? = null
-) : RealmObject() {
-
-    fun getRequestedSecretName(): String? = if (type == GossipRequestType.SECRET) {
-        requestedInfoStr
-    } else null
-
-    fun getRequestedKeyInfo(): RoomKeyRequestBody? = if (type == GossipRequestType.KEY) {
-        RoomKeyRequestBody.fromJson(requestedInfoStr)
-    } else null
-
-    var type: GossipRequestType
-        get() {
-            return tryOrNull { typeStr?.let { GossipRequestType.valueOf(it) } } ?: GossipRequestType.KEY
-        }
-        set(value) {
-            typeStr = value.name
-        }
-
-    private var requestStateStr: String = OutgoingGossipingRequestState.UNSENT.name
-
-    var requestState: OutgoingGossipingRequestState
-        get() {
-            return tryOrNull { OutgoingGossipingRequestState.valueOf(requestStateStr) }
-                    ?: OutgoingGossipingRequestState.UNSENT
-        }
-        set(value) {
-            requestStateStr = value.name
-        }
-
-    companion object {
-
-        private val recipientsDataMapper: JsonAdapter>> =
-                MoshiProvider
-                        .providesMoshi()
-                        .adapter>>(
-                                Types.newParameterizedType(Map::class.java, String::class.java, List::class.java)
-                        )
-    }
-
-    fun toOutgoingGossipingRequest(): OutgoingGossipingRequest {
-        return when (type) {
-            GossipRequestType.KEY    -> {
-                OutgoingRoomKeyRequest(
-                        requestBody = getRequestedKeyInfo(),
-                        recipients = getRecipients().orEmpty(),
-                        requestId = requestId ?: "",
-                        state = requestState
-                )
-            }
-            GossipRequestType.SECRET -> {
-                OutgoingSecretRequest(
-                        secretName = getRequestedSecretName(),
-                        recipients = getRecipients().orEmpty(),
-                        requestId = requestId ?: "",
-                        state = requestState
-                )
-            }
-        }
-    }
-
-    private fun getRecipients(): Map>? {
-        return this.recipientsData?.let { recipientsDataMapper.fromJson(it) }
-    }
-
-    fun setRecipients(recipients: Map>) {
-        this.recipientsData = recipientsDataMapper.toJson(recipients)
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingKeyRequestEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingKeyRequestEntity.kt
new file mode 100644
index 0000000000..7a8ba18809
--- /dev/null
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/OutgoingKeyRequestEntity.kt
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2022 The Matrix.org Foundation C.I.C.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.matrix.android.sdk.internal.crypto.store.db.model
+
+import com.squareup.moshi.JsonAdapter
+import com.squareup.moshi.Types
+import io.realm.RealmList
+import io.realm.RealmObject
+import io.realm.annotations.Index
+import org.matrix.android.sdk.api.extensions.tryOrNull
+import org.matrix.android.sdk.api.session.crypto.OutgoingKeyRequest
+import org.matrix.android.sdk.api.session.crypto.OutgoingRoomKeyRequestState
+import org.matrix.android.sdk.api.session.crypto.RequestReply
+import org.matrix.android.sdk.api.session.crypto.RequestResult
+import org.matrix.android.sdk.api.session.crypto.model.RoomKeyRequestBody
+import org.matrix.android.sdk.api.session.events.model.Event
+import org.matrix.android.sdk.api.session.events.model.EventType
+import org.matrix.android.sdk.api.session.events.model.content.RoomKeyWithHeldContent
+import org.matrix.android.sdk.api.session.events.model.toModel
+import org.matrix.android.sdk.internal.di.MoshiProvider
+
+internal open class OutgoingKeyRequestEntity(
+        @Index var requestId: String? = null,
+        var requestedIndex: Int? = null,
+        var recipientsData: String? = null,
+        var requestedInfoStr: String? = null,
+        var creationTimeStamp: Long? = null,
+        // de-normalization for better query (if not have to query all and parse json)
+        @Index var roomId: String? = null,
+        @Index var megolmSessionId: String? = null,
+
+        var replies: RealmList = RealmList()
+) : RealmObject() {
+
+    @Index private var requestStateStr: String = OutgoingRoomKeyRequestState.UNSENT.name
+
+    companion object {
+
+        private val recipientsDataMapper: JsonAdapter>> =
+                MoshiProvider
+                        .providesMoshi()
+                        .adapter(
+                                Types.newParameterizedType(Map::class.java, String::class.java, List::class.java)
+                        )
+    }
+
+    private fun getRequestedKeyInfo(): RoomKeyRequestBody? = RoomKeyRequestBody.fromJson(requestedInfoStr)
+
+    fun setRequestBody(body: RoomKeyRequestBody) {
+        requestedInfoStr = body.toJson()
+        roomId = body.roomId
+        megolmSessionId = body.sessionId
+    }
+
+    var requestState: OutgoingRoomKeyRequestState
+        get() {
+            return tryOrNull { OutgoingRoomKeyRequestState.valueOf(requestStateStr) }
+                    ?: OutgoingRoomKeyRequestState.UNSENT
+        }
+        set(value) {
+            requestStateStr = value.name
+        }
+
+    private fun getRecipients(): Map>? {
+        return this.recipientsData?.let { recipientsDataMapper.fromJson(it) }
+    }
+
+    fun setRecipients(recipients: Map>) {
+        this.recipientsData = recipientsDataMapper.toJson(recipients)
+    }
+
+    fun addReply(userId: String, fromDevice: String?, event: Event) {
+        val newReply = KeyRequestReplyEntity(
+                senderId = userId,
+                fromDevice = fromDevice,
+                eventJson = MoshiProvider.providesMoshi().adapter(Event::class.java).toJson(event)
+        )
+        replies.add(newReply)
+    }
+
+    fun toOutgoingKeyRequest(): OutgoingKeyRequest {
+        return OutgoingKeyRequest(
+                requestBody = getRequestedKeyInfo(),
+                recipients = getRecipients().orEmpty(),
+                requestId = requestId ?: "",
+                fromIndex = requestedIndex ?: 0,
+                state = requestState,
+                results = replies.mapNotNull { entity ->
+                    val userId = entity.senderId ?: return@mapNotNull null
+                    val result = entity.eventJson?.let {
+                        MoshiProvider.providesMoshi().adapter(Event::class.java).fromJson(it)
+                    }?.let { event ->
+                        eventToResult(event)
+                    } ?: return@mapNotNull null
+                    RequestReply(
+                            userId = userId,
+                            fromDevice = entity.fromDevice,
+                            result = result
+                    )
+                }
+        )
+    }
+
+    private fun eventToResult(event: Event): RequestResult? {
+        return when (event.getClearType()) {
+            EventType.ROOM_KEY_WITHHELD  -> {
+                event.content.toModel()?.code?.let {
+                    RequestResult.Failure(it)
+                }
+            }
+            EventType.FORWARDED_ROOM_KEY -> {
+                RequestResult.Success((event.content?.get("chain_index") as? Number)?.toInt() ?: 0)
+            }
+            else                         -> null
+        }
+    }
+}
+
+internal fun OutgoingKeyRequestEntity.deleteOnCascade() {
+    replies.deleteAllFromRealm()
+    deleteFromRealm()
+}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/CryptoRoomEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/CryptoRoomEntityQueries.kt
index 5750cc1f67..68c4974071 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/CryptoRoomEntityQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/CryptoRoomEntityQueries.kt
@@ -23,14 +23,14 @@ import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoRoomEntity
 import org.matrix.android.sdk.internal.crypto.store.db.model.CryptoRoomEntityFields
 
 /**
- * Get or create a room
+ * Get or create a room.
  */
 internal fun CryptoRoomEntity.Companion.getOrCreate(realm: Realm, roomId: String): CryptoRoomEntity {
     return getById(realm, roomId) ?: realm.createObject(roomId)
 }
 
 /**
- * Get a room
+ * Get a room.
  */
 internal fun CryptoRoomEntity.Companion.getById(realm: Realm, roomId: String): CryptoRoomEntity? {
     return realm.where()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/DeviceInfoEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/DeviceInfoEntityQueries.kt
index c9523d63ce..0a922e79bc 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/DeviceInfoEntityQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/DeviceInfoEntityQueries.kt
@@ -24,7 +24,7 @@ import org.matrix.android.sdk.internal.crypto.store.db.model.DeviceInfoEntityFie
 import org.matrix.android.sdk.internal.crypto.store.db.model.createPrimaryKey
 
 /**
- * Get or create a device info
+ * Get or create a device info.
  */
 internal fun DeviceInfoEntity.Companion.getOrCreate(realm: Realm, userId: String, deviceId: String): DeviceInfoEntity {
     val key = DeviceInfoEntity.createPrimaryKey(userId, deviceId)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/UserEntitiesQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/UserEntitiesQueries.kt
index 5a3b8e5397..73c3997439 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/UserEntitiesQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/query/UserEntitiesQueries.kt
@@ -24,7 +24,7 @@ import org.matrix.android.sdk.internal.crypto.store.db.model.UserEntityFields
 import org.matrix.android.sdk.internal.crypto.store.db.model.deleteOnCascade
 
 /**
- * Get or create a user
+ * Get or create a user.
  */
 internal fun UserEntity.Companion.getOrCreate(realm: Realm, userId: String): UserEntity {
     return realm.where()
@@ -34,7 +34,7 @@ internal fun UserEntity.Companion.getOrCreate(realm: Realm, userId: String): Use
 }
 
 /**
- * Delete a user
+ * Delete a user.
  */
 internal fun UserEntity.Companion.delete(realm: Realm, userId: String) {
     realm.where()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt
index 1e395796a9..394c618968 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/EncryptEventTask.kt
@@ -15,6 +15,7 @@
  */
 package org.matrix.android.sdk.internal.crypto.tasks
 
+import dagger.Lazy
 import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM
 import org.matrix.android.sdk.api.session.crypto.CryptoService
 import org.matrix.android.sdk.api.session.crypto.model.MXEncryptEventContentResult
@@ -39,7 +40,7 @@ internal interface EncryptEventTask : Task {
 
 internal class DefaultEncryptEventTask @Inject constructor(
         private val localEchoRepository: LocalEchoRepository,
-        private val cryptoService: CryptoService
+        private val cryptoService: Lazy
 ) : EncryptEventTask {
     override suspend fun execute(params: EncryptEventTask.Params): Event {
         // don't want to wait for any query
@@ -59,7 +60,7 @@ internal class DefaultEncryptEventTask @Inject constructor(
 //        try {
         // let it throws
         awaitCallback {
-            cryptoService.encryptEventContent(localMutableContent, localEvent.type, params.roomId, it)
+            cryptoService.get().encryptEventContent(localMutableContent, localEvent.type, params.roomId, it)
         }.let { result ->
             val modifiedContent = HashMap(result.eventContent)
             params.keepKeys?.forEach { toKeep ->
@@ -80,7 +81,7 @@ internal class DefaultEncryptEventTask @Inject constructor(
                         ).toContent(),
                         forwardingCurve25519KeyChain = emptyList(),
                         senderCurve25519Key = result.eventContent["sender_key"] as? String,
-                        claimedEd25519Key = cryptoService.getMyDevice().fingerprint()
+                        claimedEd25519Key = cryptoService.get().getMyDevice().fingerprint()
                 )
             } else {
                 null
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt
index 14674ef258..50efe51bc1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendEventTask.kt
@@ -15,6 +15,7 @@
  */
 package org.matrix.android.sdk.internal.crypto.tasks
 
+import org.matrix.android.sdk.api.extensions.tryOrNull
 import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.room.send.SendState
 import org.matrix.android.sdk.internal.network.GlobalErrorReceiver
@@ -46,7 +47,9 @@ internal class DefaultSendEventTask @Inject constructor(
             params.event.roomId
                     ?.takeIf { params.encrypt }
                     ?.let { roomId ->
-                        loadRoomMembersTask.execute(LoadRoomMembersTask.Params(roomId))
+                        tryOrNull {
+                            loadRoomMembersTask.execute(LoadRoomMembersTask.Params(roomId))
+                        }
                     }
 
             val event = handleEncryption(params)
@@ -66,6 +69,7 @@ internal class DefaultSendEventTask @Inject constructor(
             }
         } catch (e: Throwable) {
 //            localEchoRepository.updateSendState(params.event.eventId!!, SendState.UNDELIVERED)
+            Timber.w(e, "Unable to send the Event")
             throw e
         }
     }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt
index 44aa6d9db1..7c52c62d92 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/SendVerificationMessageTask.kt
@@ -47,7 +47,7 @@ internal class DefaultSendVerificationMessageTask @Inject constructor(
             localEchoRepository.updateSendState(localId, event.roomId, SendState.SENDING)
             val response = executeRequest(globalErrorReceiver) {
                 roomAPI.send(
-                        localId,
+                        txId = localId,
                         roomId = event.roomId ?: "",
                         content = event.content,
                         eventType = event.type ?: ""
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSignaturesTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSignaturesTask.kt
index e03e353cb1..18d8b26558 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSignaturesTask.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSignaturesTask.kt
@@ -15,7 +15,6 @@
  */
 package org.matrix.android.sdk.internal.crypto.tasks
 
-import org.matrix.android.sdk.api.failure.Failure
 import org.matrix.android.sdk.internal.crypto.api.CryptoApi
 import org.matrix.android.sdk.internal.network.GlobalErrorReceiver
 import org.matrix.android.sdk.internal.network.executeRequest
@@ -34,20 +33,15 @@ internal class DefaultUploadSignaturesTask @Inject constructor(
 ) : UploadSignaturesTask {
 
     override suspend fun execute(params: UploadSignaturesTask.Params) {
-        try {
-            val response = executeRequest(
-                    globalErrorReceiver,
-                    canRetry = true,
-                    maxRetriesCount = 10
-            ) {
-                cryptoApi.uploadSignatures(params.signatures)
-            }
-            if (response.failures?.isNotEmpty() == true) {
-                throw Throwable(response.failures.toString())
-            }
-            return
-        } catch (f: Failure) {
-            throw f
+        val response = executeRequest(
+                globalErrorReceiver,
+                canRetry = true,
+                maxRetriesCount = 10
+        ) {
+            cryptoApi.uploadSignatures(params.signatures)
+        }
+        if (response.failures?.isNotEmpty() == true) {
+            throw Throwable(response.failures.toString())
         }
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSigningKeysTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSigningKeysTask.kt
index 0a0df11bd3..e539867a04 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSigningKeysTask.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/tasks/UploadSigningKeysTask.kt
@@ -36,7 +36,7 @@ internal interface UploadSigningKeysTask : Task PRK
+     * HkdfSha256-Extract(salt, IKM) -> PRK.
      *
      * @param salt  optional salt value (a non-secret random value);
      * if not provided, it is set to a string of HashLen (size in octets) zeros.
@@ -45,7 +45,7 @@ internal object HkdfSha256 {
     }
 
     /**
-     * HkdfSha256-Expand(PRK, info, L) -> OKM
+     * HkdfSha256-Expand(PRK, info, L) -> OKM.
      *
      * @param prk a pseudorandom key of at least HashLen bytes (usually, the output from the extract step)
      * @param info optional context and application specific information (can be empty)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt
index 8ecb68560b..a9d5cf1191 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultIncomingSASDefaultVerificationTransaction.kt
@@ -23,8 +23,8 @@ import org.matrix.android.sdk.api.session.crypto.verification.IncomingSasVerific
 import org.matrix.android.sdk.api.session.crypto.verification.SasMode
 import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
 import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.internal.crypto.IncomingGossipingRequestManager
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
+import org.matrix.android.sdk.internal.crypto.SecretShareManager
 import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
 import timber.log.Timber
@@ -35,8 +35,8 @@ internal class DefaultIncomingSASDefaultVerificationTransaction(
         override val deviceId: String?,
         private val cryptoStore: IMXCryptoStore,
         crossSigningService: CrossSigningService,
-        outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        incomingGossipingRequestManager: IncomingGossipingRequestManager,
+        outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        secretShareManager: SecretShareManager,
         deviceFingerprint: String,
         transactionId: String,
         otherUserID: String,
@@ -47,8 +47,8 @@ internal class DefaultIncomingSASDefaultVerificationTransaction(
         deviceId,
         cryptoStore,
         crossSigningService,
-        outgoingGossipingRequestManager,
-        incomingGossipingRequestManager,
+        outgoingKeyRequestManager,
+        secretShareManager,
         deviceFingerprint,
         transactionId,
         otherUserID,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt
index 4bdf414295..ddb8ed232b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultOutgoingSASDefaultVerificationTransaction.kt
@@ -20,8 +20,8 @@ import org.matrix.android.sdk.api.session.crypto.verification.CancelCode
 import org.matrix.android.sdk.api.session.crypto.verification.OutgoingSasVerificationTransaction
 import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
 import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.internal.crypto.IncomingGossipingRequestManager
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
+import org.matrix.android.sdk.internal.crypto.SecretShareManager
 import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
 import timber.log.Timber
@@ -32,8 +32,8 @@ internal class DefaultOutgoingSASDefaultVerificationTransaction(
         deviceId: String?,
         cryptoStore: IMXCryptoStore,
         crossSigningService: CrossSigningService,
-        outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        incomingGossipingRequestManager: IncomingGossipingRequestManager,
+        outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        secretShareManager: SecretShareManager,
         deviceFingerprint: String,
         transactionId: String,
         otherUserId: String,
@@ -44,8 +44,8 @@ internal class DefaultOutgoingSASDefaultVerificationTransaction(
         deviceId,
         cryptoStore,
         crossSigningService,
-        outgoingGossipingRequestManager,
-        incomingGossipingRequestManager,
+        outgoingKeyRequestManager,
+        secretShareManager,
         deviceFingerprint,
         transactionId,
         otherUserId,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt
index d62ca5503d..af48283767 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationService.kt
@@ -59,9 +59,9 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageVerification
 import org.matrix.android.sdk.api.session.room.model.message.MessageVerificationStartContent
 import org.matrix.android.sdk.api.session.room.model.message.ValidVerificationDone
 import org.matrix.android.sdk.internal.crypto.DeviceListManager
-import org.matrix.android.sdk.internal.crypto.IncomingGossipingRequestManager
 import org.matrix.android.sdk.internal.crypto.MyDeviceInfoHolder
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
+import org.matrix.android.sdk.internal.crypto.SecretShareManager
 import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction
 import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationAccept
 import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationCancel
@@ -95,8 +95,8 @@ internal class DefaultVerificationService @Inject constructor(
         @UserId private val userId: String,
         @DeviceId private val deviceId: String?,
         private val cryptoStore: IMXCryptoStore,
-        private val outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        private val incomingGossipingRequestManager: IncomingGossipingRequestManager,
+        private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        private val secretShareManager: SecretShareManager,
         private val myDeviceInfoHolder: Lazy,
         private val deviceListManager: DeviceListManager,
         private val setDeviceVerificationAction: SetDeviceVerificationAction,
@@ -551,8 +551,8 @@ internal class DefaultVerificationService @Inject constructor(
                             deviceId,
                             cryptoStore,
                             crossSigningService,
-                            outgoingGossipingRequestManager,
-                            incomingGossipingRequestManager,
+                            outgoingKeyRequestManager,
+                            secretShareManager,
                             myDeviceInfoHolder.get().myDevice.fingerprint()!!,
                             startReq.transactionId,
                             otherUserId,
@@ -771,8 +771,15 @@ internal class DefaultVerificationService @Inject constructor(
             return
         }
 
+        val roomId = event.roomId
+        if (roomId == null) {
+            Timber.e("## SAS Verification missing roomId for event")
+            // TODO cancel?
+            return
+        }
+
         handleReadyReceived(event.senderId, readyReq) {
-            verificationTransportRoomMessageFactory.createTransport(event.roomId!!, it)
+            verificationTransportRoomMessageFactory.createTransport(roomId, it)
         }
     }
 
@@ -814,21 +821,15 @@ internal class DefaultVerificationService @Inject constructor(
             getExistingTransaction(userId, doneReq.transactionId)
                     ?: getOldTransaction(userId, doneReq.transactionId)
                             ?.let { vt ->
-                                val otherDeviceId = vt.otherDeviceId
+                                val otherDeviceId = vt.otherDeviceId ?: return@let
                                 if (!crossSigningService.canCrossSign()) {
-                                    outgoingGossipingRequestManager.sendSecretShareRequest(
-                                            MASTER_KEY_SSSS_NAME, mapOf(userId to listOf(otherDeviceId ?: "*"))
-                                    )
-                                    outgoingGossipingRequestManager.sendSecretShareRequest(
-                                            SELF_SIGNING_KEY_SSSS_NAME, mapOf(userId to listOf(otherDeviceId ?: "*"))
-                                    )
-                                    outgoingGossipingRequestManager.sendSecretShareRequest(
-                                            USER_SIGNING_KEY_SSSS_NAME, mapOf(userId to listOf(otherDeviceId ?: "*"))
-                                    )
+                                    cryptoCoroutineScope.launch {
+                                        secretShareManager.requestSecretTo(otherDeviceId, MASTER_KEY_SSSS_NAME)
+                                        secretShareManager.requestSecretTo(otherDeviceId, SELF_SIGNING_KEY_SSSS_NAME)
+                                        secretShareManager.requestSecretTo(otherDeviceId, USER_SIGNING_KEY_SSSS_NAME)
+                                        secretShareManager.requestSecretTo(otherDeviceId, KEYBACKUP_SECRET_SSSS_NAME)
+                                    }
                                 }
-                                outgoingGossipingRequestManager.sendSecretShareRequest(
-                                        KEYBACKUP_SECRET_SSSS_NAME, mapOf(userId to listOf(otherDeviceId ?: "*"))
-                                )
                             }
         }
     }
@@ -922,8 +923,8 @@ internal class DefaultVerificationService @Inject constructor(
                     otherUserId = senderId,
                     otherDeviceId = readyReq.fromDevice,
                     crossSigningService = crossSigningService,
-                    outgoingGossipingRequestManager = outgoingGossipingRequestManager,
-                    incomingGossipingRequestManager = incomingGossipingRequestManager,
+                    outgoingKeyRequestManager = outgoingKeyRequestManager,
+                    secretShareManager = secretShareManager,
                     cryptoStore = cryptoStore,
                     qrCodeData = qrCodeData,
                     userId = userId,
@@ -938,9 +939,25 @@ internal class DefaultVerificationService @Inject constructor(
 
         updatePendingRequest(
                 existingRequest.copy(
-                        readyInfo = readyReq
+                    readyInfo = readyReq
                 )
         )
+
+        notifyOthersOfAcceptance(readyReq.transactionId, readyReq.fromDevice)
+    }
+
+    /**
+     * Gets a list of device ids excluding the current one.
+     */
+    private fun getMyOtherDeviceIds(): List = cryptoStore.getUserDevices(userId)?.keys?.filter { it != deviceId }.orEmpty()
+
+    /**
+     * Notifies other devices that the current verification transaction is being handled by [acceptedByDeviceId].
+     */
+    private fun notifyOthersOfAcceptance(transactionId: String, acceptedByDeviceId: String) {
+        val deviceIds = getMyOtherDeviceIds().filter { it != acceptedByDeviceId }
+        val transport = verificationTransportToDeviceFactory.createTransport(null)
+        transport.cancelTransaction(transactionId, userId, deviceIds, CancelCode.AcceptedByAnotherDevice)
     }
 
     private fun createQrCodeData(requestId: String?, otherUserId: String, otherDeviceId: String?): QrCodeData? {
@@ -1124,8 +1141,8 @@ internal class DefaultVerificationService @Inject constructor(
                     deviceId,
                     cryptoStore,
                     crossSigningService,
-                    outgoingGossipingRequestManager,
-                    incomingGossipingRequestManager,
+                    outgoingKeyRequestManager,
+                    secretShareManager,
                     myDeviceInfoHolder.get().myDevice.fingerprint()!!,
                     txID,
                     otherUserId,
@@ -1188,6 +1205,7 @@ internal class DefaultVerificationService @Inject constructor(
         }
                 .distinct()
 
+        requestsForUser.add(verificationRequest)
         transport.sendVerificationRequest(methodValues, validLocalId, otherUserId, roomId, null) { syncedId, info ->
             // We need to update with the syncedID
             updatePendingRequest(
@@ -1199,7 +1217,6 @@ internal class DefaultVerificationService @Inject constructor(
             )
         }
 
-        requestsForUser.add(verificationRequest)
         dispatchRequestAdded(verificationRequest)
 
         return verificationRequest
@@ -1323,8 +1340,8 @@ internal class DefaultVerificationService @Inject constructor(
                     deviceId,
                     cryptoStore,
                     crossSigningService,
-                    outgoingGossipingRequestManager,
-                    incomingGossipingRequestManager,
+                    outgoingKeyRequestManager,
+                    secretShareManager,
                     myDeviceInfoHolder.get().myDevice.fingerprint()!!,
                     transactionId,
                     otherUserId,
@@ -1465,8 +1482,8 @@ internal class DefaultVerificationService @Inject constructor(
                         otherUserId = otherUserId,
                         otherDeviceId = otherDeviceId,
                         crossSigningService = crossSigningService,
-                        outgoingGossipingRequestManager = outgoingGossipingRequestManager,
-                        incomingGossipingRequestManager = incomingGossipingRequestManager,
+                        outgoingKeyRequestManager = outgoingKeyRequestManager,
+                        secretShareManager = secretShareManager,
                         cryptoStore = cryptoStore,
                         qrCodeData = qrCodeData,
                         userId = userId,
@@ -1484,7 +1501,7 @@ internal class DefaultVerificationService @Inject constructor(
     }
 
     /**
-     * This string must be unique for the pair of users performing verification for the duration that the transaction is valid
+     * This string must be unique for the pair of users performing verification for the duration that the transaction is valid.
      */
     private fun createUniqueIDForTransaction(otherUserId: String, otherDeviceID: String): String {
         return buildString {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt
index 692ddd0148..27bc764395 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/DefaultVerificationTransaction.kt
@@ -20,19 +20,19 @@ import org.matrix.android.sdk.api.session.crypto.crosssigning.CrossSigningServic
 import org.matrix.android.sdk.api.session.crypto.crosssigning.DeviceTrustLevel
 import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransaction
 import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
-import org.matrix.android.sdk.internal.crypto.IncomingGossipingRequestManager
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
+import org.matrix.android.sdk.internal.crypto.SecretShareManager
 import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction
 import timber.log.Timber
 
 /**
- * Generic interactive key verification transaction
+ * Generic interactive key verification transaction.
  */
 internal abstract class DefaultVerificationTransaction(
         private val setDeviceVerificationAction: SetDeviceVerificationAction,
         private val crossSigningService: CrossSigningService,
-        private val outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        private val incomingGossipingRequestManager: IncomingGossipingRequestManager,
+        private val outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        private val secretShareManager: SecretShareManager,
         private val userId: String,
         override val transactionId: String,
         override val otherUserId: String,
@@ -86,7 +86,7 @@ internal abstract class DefaultVerificationTransaction(
         }
 
         if (otherUserId == userId) {
-            incomingGossipingRequestManager.onVerificationCompleteForDevice(otherDeviceId!!)
+            secretShareManager.onVerificationCompleteForDevice(otherDeviceId!!)
 
             // If me it's reasonable to sign and upload the device signature
             // Notice that i might not have the private keys, so may not be able to do it
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt
index 00069ba122..68dd57478e 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SASDefaultVerificationTransaction.kt
@@ -23,8 +23,8 @@ import org.matrix.android.sdk.api.session.crypto.verification.SasMode
 import org.matrix.android.sdk.api.session.crypto.verification.SasVerificationTransaction
 import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
 import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.internal.crypto.IncomingGossipingRequestManager
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
+import org.matrix.android.sdk.internal.crypto.SecretShareManager
 import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
 import org.matrix.android.sdk.internal.extensions.toUnsignedInt
@@ -42,8 +42,8 @@ internal abstract class SASDefaultVerificationTransaction(
         open val deviceId: String?,
         private val cryptoStore: IMXCryptoStore,
         crossSigningService: CrossSigningService,
-        outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        incomingGossipingRequestManager: IncomingGossipingRequestManager,
+        outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        secretShareManager: SecretShareManager,
         private val deviceFingerprint: String,
         transactionId: String,
         otherUserId: String,
@@ -52,8 +52,8 @@ internal abstract class SASDefaultVerificationTransaction(
 ) : DefaultVerificationTransaction(
         setDeviceVerificationAction,
         crossSigningService,
-        outgoingGossipingRequestManager,
-        incomingGossipingRequestManager,
+        outgoingKeyRequestManager,
+        secretShareManager,
         userId,
         transactionId,
         otherUserId,
@@ -132,7 +132,7 @@ internal abstract class SASDefaultVerificationTransaction(
 
     /**
      * To be called by the client when the user has verified that
-     * both short codes do match
+     * both short codes do match.
      */
     override fun userHasVerifiedShortCode() {
         Timber.v("## SAS short code verified by user for id:$transactionId")
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SendVerificationMessageWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SendVerificationMessageWorker.kt
deleted file mode 100644
index 0a175ae3ca..0000000000
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/SendVerificationMessageWorker.kt
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright 2020 The Matrix.org Foundation C.I.C.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.matrix.android.sdk.internal.crypto.verification
-
-import android.content.Context
-import androidx.work.Data
-import androidx.work.WorkerParameters
-import com.squareup.moshi.JsonClass
-import org.matrix.android.sdk.api.failure.shouldBeRetried
-import org.matrix.android.sdk.internal.SessionManager
-import org.matrix.android.sdk.internal.crypto.tasks.SendVerificationMessageTask
-import org.matrix.android.sdk.internal.session.SessionComponent
-import org.matrix.android.sdk.internal.session.room.send.CancelSendTracker
-import org.matrix.android.sdk.internal.session.room.send.LocalEchoRepository
-import org.matrix.android.sdk.internal.worker.SessionSafeCoroutineWorker
-import org.matrix.android.sdk.internal.worker.SessionWorkerParams
-import timber.log.Timber
-import javax.inject.Inject
-
-/**
- * Possible previous worker: None
- * Possible next worker    : None
- */
-internal class SendVerificationMessageWorker(context: Context, params: WorkerParameters, sessionManager: SessionManager) :
-        SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) {
-
-    @JsonClass(generateAdapter = true)
-    internal data class Params(
-            override val sessionId: String,
-            val eventId: String,
-            override val lastFailureMessage: String? = null
-    ) : SessionWorkerParams
-
-    @Inject lateinit var sendVerificationMessageTask: SendVerificationMessageTask
-    @Inject lateinit var localEchoRepository: LocalEchoRepository
-    @Inject lateinit var cancelSendTracker: CancelSendTracker
-
-    override fun injectWith(injector: SessionComponent) {
-        injector.inject(this)
-    }
-
-    override suspend fun doSafeWork(params: Params): Result {
-        val localEvent = localEchoRepository.getUpToDateEcho(params.eventId) ?: return buildErrorResult(params, "Event not found")
-        val localEventId = localEvent.eventId ?: ""
-        val roomId = localEvent.roomId ?: ""
-
-        if (cancelSendTracker.isCancelRequestedFor(localEventId, roomId)) {
-            return Result.success()
-                    .also {
-                        cancelSendTracker.markCancelled(localEventId, roomId)
-                        Timber.e("## SendEvent: Event sending has been cancelled $localEventId")
-                    }
-        }
-
-        return try {
-            val resultEventId = sendVerificationMessageTask.execute(
-                    SendVerificationMessageTask.Params(
-                            event = localEvent
-                    )
-            )
-
-            Result.success(Data.Builder().putString(localEventId, resultEventId).build())
-        } catch (throwable: Throwable) {
-            if (throwable.shouldBeRetried()) {
-                Result.retry()
-            } else {
-                buildErrorResult(params, throwable.localizedMessage ?: "error")
-            }
-        }
-    }
-
-    override fun buildErrorParams(params: Params, message: String): Params {
-        return params.copy(lastFailureMessage = params.lastFailureMessage ?: message)
-    }
-}
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt
index 79aabba59d..3ddb0ca758 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoAccept.kt
@@ -17,28 +17,28 @@ package org.matrix.android.sdk.internal.crypto.verification
 
 internal interface VerificationInfoAccept : VerificationInfo {
     /**
-     * The key agreement protocol that Bob’s device has selected to use, out of the list proposed by Alice’s device
+     * The key agreement protocol that Bob’s device has selected to use, out of the list proposed by Alice’s device.
      */
     val keyAgreementProtocol: String?
 
     /**
-     * The hash algorithm that Bob’s device has selected to use, out of the list proposed by Alice’s device
+     * The hash algorithm that Bob’s device has selected to use, out of the list proposed by Alice’s device.
      */
     val hash: String?
 
     /**
-     * The message authentication code that Bob’s device has selected to use, out of the list proposed by Alice’s device
+     * The message authentication code that Bob’s device has selected to use, out of the list proposed by Alice’s device.
      */
     val messageAuthenticationCode: String?
 
     /**
-     * An array of short authentication string methods that Bob’s client (and Bob) understands.  Must be a subset of the list proposed by Alice’s device
+     * An array of short authentication string methods that Bob’s client (and Bob) understands.  Must be a subset of the list proposed by Alice’s device.
      */
     val shortAuthenticationStrings: List?
 
     /**
      * The hash (encoded as unpadded base64) of the concatenation of the device’s ephemeral public key (QB, encoded as unpadded base64)
-     *  and the canonical JSON representation of the m.key.verification.start message.
+     * and the canonical JSON representation of the m.key.verification.start message.
      */
     var commitment: String?
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoCancel.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoCancel.kt
index 35c05ac058..20e2cdcd33 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoCancel.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoCancel.kt
@@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.crypto.verification
 
 internal interface VerificationInfoCancel : VerificationInfo {
     /**
-     * machine-readable reason for cancelling, see [CancelCode]
+     * machine-readable reason for cancelling, see [CancelCode].
      */
     val code: String?
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoKey.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoKey.kt
index 23c117d844..2885b81a12 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoKey.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoKey.kt
@@ -20,7 +20,7 @@ package org.matrix.android.sdk.internal.crypto.verification
  */
 internal interface VerificationInfoKey : VerificationInfo {
     /**
-     * The device’s ephemeral public key, as an unpadded base64 string
+     * The device’s ephemeral public key, as an unpadded base64 string.
      */
     val key: String?
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoMac.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoMac.kt
index 5515acc2f1..d6f1d7e4db 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoMac.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoMac.kt
@@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.crypto.verification
 
 internal interface VerificationInfoMac : VerificationInfo {
     /**
-     * A map of key ID to the MAC of the key, as an unpadded base64 string, calculated using the MAC key
+     * A map of key ID to the MAC of the key, as an unpadded base64 string, calculated using the MAC key.
      */
     val mac: Map?
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoReady.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoReady.kt
index 327c09dabf..2e397eee08 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoReady.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoReady.kt
@@ -27,12 +27,12 @@ import org.matrix.android.sdk.api.session.crypto.verification.ValidVerificationI
 
 internal interface VerificationInfoReady : VerificationInfo {
     /**
-     * The ID of the device that sent the m.key.verification.ready message
+     * The ID of the device that sent the m.key.verification.ready message.
      */
     val fromDevice: String?
 
     /**
-     * An array of verification methods that the device supports
+     * An array of verification methods that the device supports.
      */
     val methods: List?
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt
index 40c96dfa95..d71bd7359e 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationInfoStart.kt
@@ -24,7 +24,7 @@ internal interface VerificationInfoStart : VerificationInfo?
 
     /**
-     * Shared secret, when starting verification with QR code
+     * Shared secret, when starting verification with QR code.
      */
     val sharedSecret: String?
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt
index ec4e1aa65c..303b6c5839 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationMessageProcessor.kt
@@ -15,13 +15,9 @@
  */
 package org.matrix.android.sdk.internal.crypto.verification
 
-import io.realm.Realm
-import org.matrix.android.sdk.api.session.crypto.MXCryptoError
-import org.matrix.android.sdk.api.session.crypto.model.OlmDecryptionResult
 import org.matrix.android.sdk.api.session.crypto.verification.VerificationService
 import org.matrix.android.sdk.api.session.events.model.Event
 import org.matrix.android.sdk.api.session.events.model.EventType
-import org.matrix.android.sdk.api.session.events.model.LocalEcho
 import org.matrix.android.sdk.api.session.events.model.toModel
 import org.matrix.android.sdk.api.session.room.model.message.MessageContent
 import org.matrix.android.sdk.api.session.room.model.message.MessageRelationContent
@@ -29,22 +25,18 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageType
 import org.matrix.android.sdk.api.session.room.model.message.MessageVerificationReadyContent
 import org.matrix.android.sdk.api.session.room.model.message.MessageVerificationRequestContent
 import org.matrix.android.sdk.api.session.room.model.message.MessageVerificationStartContent
-import org.matrix.android.sdk.internal.crypto.EventDecryptor
-import org.matrix.android.sdk.internal.database.model.EventInsertType
 import org.matrix.android.sdk.internal.di.DeviceId
 import org.matrix.android.sdk.internal.di.UserId
-import org.matrix.android.sdk.internal.session.EventInsertLiveProcessor
 import org.matrix.android.sdk.internal.util.time.Clock
 import timber.log.Timber
 import javax.inject.Inject
 
 internal class VerificationMessageProcessor @Inject constructor(
-        private val eventDecryptor: EventDecryptor,
-        private val clock: Clock,
         private val verificationService: DefaultVerificationService,
         @UserId private val userId: String,
-        @DeviceId private val deviceId: String?
-) : EventInsertLiveProcessor {
+        @DeviceId private val deviceId: String?,
+        private val clock: Clock,
+) {
 
     private val transactionsHandledByOtherDevice = ArrayList()
 
@@ -60,40 +52,20 @@ internal class VerificationMessageProcessor @Inject constructor(
             EventType.ENCRYPTED
     )
 
-    override fun shouldProcess(eventId: String, eventType: String, insertType: EventInsertType): Boolean {
-        if (insertType != EventInsertType.INCREMENTAL_SYNC) {
-            return false
-        }
-        return allowedTypes.contains(eventType) && !LocalEcho.isLocalEchoId(eventId)
+    fun shouldProcess(eventType: String): Boolean {
+        return allowedTypes.contains(eventType)
     }
 
-    override suspend fun process(realm: Realm, event: Event) {
-        Timber.v("## SAS Verification live observer: received msgId: ${event.eventId} msgtype: ${event.type} from ${event.senderId}")
+    suspend fun process(event: Event) {
+        Timber.v("## SAS Verification live observer: received msgId: ${event.eventId} msgtype: ${event.getClearType()} from ${event.senderId}")
 
         // If the request is in the future by more than 5 minutes or more than 10 minutes in the past,
         // the message should be ignored by the receiver.
 
-        if (!VerificationService.isValidRequest(event.ageLocalTs ?: event.originServerTs, clock.epochMillis())) return Unit.also {
-            Timber.d("## SAS Verification live observer: msgId: ${event.eventId} is outdated")
+        if (event.ageLocalTs != null && !VerificationService.isValidRequest(event.ageLocalTs, clock.epochMillis())) return Unit.also {
+            Timber.d("## SAS Verification live observer: msgId: ${event.eventId} is outdated age:$event.ageLocalTs ms")
         }
 
-        // decrypt if needed?
-        if (event.isEncrypted() && event.mxDecryptionResult == null) {
-            // TODO use a global event decryptor? attache to session and that listen to new sessionId?
-            // for now decrypt sync
-            try {
-                val result = eventDecryptor.decryptEvent(event, "")
-                event.mxDecryptionResult = OlmDecryptionResult(
-                        payload = result.clearEvent,
-                        senderKey = result.senderCurve25519Key,
-                        keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) },
-                        forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain
-                )
-            } catch (e: MXCryptoError) {
-                Timber.e("## SAS Failed to decrypt event: ${event.eventId}")
-                verificationService.onPotentiallyInterestingEventRoomFailToDecrypt(event)
-            }
-        }
         Timber.v("## SAS Verification live observer: received msgId: ${event.eventId} type: ${event.getClearType()}")
 
         // Relates to is not encrypted
@@ -102,7 +74,6 @@ internal class VerificationMessageProcessor @Inject constructor(
         if (event.senderId == userId) {
             // If it's send from me, we need to keep track of Requests or Start
             // done from another device of mine
-
             if (EventType.MESSAGE == event.getClearType()) {
                 val msgType = event.getClearContent().toModel()?.msgType
                 if (MessageType.MSGTYPE_VERIFICATION_REQUEST == msgType) {
@@ -137,6 +108,8 @@ internal class VerificationMessageProcessor @Inject constructor(
                     transactionsHandledByOtherDevice.remove(it)
                     verificationService.onRoomRequestHandledByOtherDevice(event)
                 }
+            } else if (EventType.ENCRYPTED == event.getClearType()) {
+                verificationService.onPotentiallyInterestingEventRoomFailToDecrypt(event)
             }
 
             Timber.v("## SAS Verification ignoring message sent by me: ${event.eventId} type: ${event.getClearType()}")
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt
index c326dd0fc3..8538e5a5af 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransport.kt
@@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxStat
 internal interface VerificationTransport {
 
     /**
-     * Sends a message
+     * Sends a message.
      */
     fun  sendToOther(type: String,
                         verificationInfo: VerificationInfo,
@@ -49,11 +49,16 @@ internal interface VerificationTransport {
                           otherUserDeviceId: String?,
                           code: CancelCode)
 
+    fun cancelTransaction(transactionId: String,
+                          otherUserId: String,
+                          otherUserDeviceIds: List,
+                          code: CancelCode)
+
     fun done(transactionId: String,
              onDone: (() -> Unit)?)
 
     /**
-     * Creates an accept message suitable for this transport
+     * Creates an accept message suitable for this transport.
      */
     fun createAccept(tid: String,
                      keyAgreementProtocol: String,
@@ -66,7 +71,7 @@ internal interface VerificationTransport {
                   pubKey: String): VerificationInfoKey
 
     /**
-     * Create start for SAS verification
+     * Create start for SAS verification.
      */
     fun createStartForSas(fromDevice: String,
                           transactionId: String,
@@ -76,7 +81,7 @@ internal interface VerificationTransport {
                           shortAuthenticationStrings: List): VerificationInfoStart
 
     /**
-     * Create start for QR code verification
+     * Create start for QR code verification.
      */
     fun createStartForQrCode(fromDevice: String,
                              transactionId: String,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt
index 325a6f0ba2..03df849d22 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessage.kt
@@ -15,14 +15,8 @@
  */
 package org.matrix.android.sdk.internal.crypto.verification
 
-import androidx.lifecycle.Observer
-import androidx.work.BackoffPolicy
-import androidx.work.Data
-import androidx.work.ExistingWorkPolicy
-import androidx.work.Operation
-import androidx.work.WorkInfo
 import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.asCoroutineDispatcher
 import kotlinx.coroutines.launch
 import org.matrix.android.sdk.api.session.crypto.verification.CancelCode
 import org.matrix.android.sdk.api.session.crypto.verification.ValidVerificationInfoRequest
@@ -45,27 +39,28 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageVerification
 import org.matrix.android.sdk.api.session.room.model.relation.RelationDefaultContent
 import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_RECIPROCATE
 import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_SAS
-import org.matrix.android.sdk.internal.di.WorkManagerProvider
+import org.matrix.android.sdk.internal.crypto.tasks.SendVerificationMessageTask
 import org.matrix.android.sdk.internal.session.room.send.LocalEchoEventFactory
+import org.matrix.android.sdk.internal.task.SemaphoreCoroutineSequencer
 import org.matrix.android.sdk.internal.util.time.Clock
-import org.matrix.android.sdk.internal.worker.SessionSafeCoroutineWorker
-import org.matrix.android.sdk.internal.worker.WorkerParamsFactory
 import timber.log.Timber
-import java.util.UUID
-import java.util.concurrent.TimeUnit
+import java.util.concurrent.Executors
 
 internal class VerificationTransportRoomMessage(
-        private val workManagerProvider: WorkManagerProvider,
-        private val sessionId: String,
+        private val sendVerificationMessageTask: SendVerificationMessageTask,
         private val userId: String,
         private val userDeviceId: String?,
         private val roomId: String,
         private val localEchoEventFactory: LocalEchoEventFactory,
         private val tx: DefaultVerificationTransaction?,
-        private val coroutineScope: CoroutineScope,
+        cryptoCoroutineScope: CoroutineScope,
         private val clock: Clock,
 ) : VerificationTransport {
 
+    private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
+    private val verificationSenderScope = CoroutineScope(cryptoCoroutineScope.coroutineContext + dispatcher)
+    private val sequencer = SemaphoreCoroutineSequencer()
+
     override fun  sendToOther(type: String,
                                  verificationInfo: VerificationInfo,
                                  nextState: VerificationTxState,
@@ -79,70 +74,22 @@ internal class VerificationTransportRoomMessage(
                 content = verificationInfo.toEventContent()!!
         )
 
-        val workerParams = WorkerParamsFactory.toData(
-                SendVerificationMessageWorker.Params(
-                        sessionId = sessionId,
-                        eventId = event.eventId ?: ""
-                )
-        )
-        val enqueueInfo = enqueueSendWork(workerParams)
-
-        // I cannot just listen to the given work request, because when used in a uniqueWork,
-        // The callback is called while it is still Running ...
-
-//        Futures.addCallback(enqueueInfo.first.result, object : FutureCallback {
-//            override fun onSuccess(result: Operation.State.SUCCESS?) {
-//                if (onDone != null) {
-//                    onDone()
-//                } else {
-//                    tx?.state = nextState
-//                }
-//            }
-//
-//            override fun onFailure(t: Throwable) {
-//                Timber.e("## SAS verification [${tx?.transactionId}] failed to send toDevice in state : ${tx?.state}, reason: ${t.localizedMessage}")
-//                tx?.cancel(onErrorReason)
-//            }
-//        }, listenerExecutor)
-
-        val workLiveData = workManagerProvider.workManager
-                .getWorkInfosForUniqueWorkLiveData(uniqueQueueName())
-
-        val observer = object : Observer> {
-            override fun onChanged(workInfoList: List?) {
-                workInfoList
-                        ?.firstOrNull { it.id == enqueueInfo.second }
-                        ?.let { wInfo ->
-                            when (wInfo.state) {
-                                WorkInfo.State.FAILED    -> {
-                                    tx?.cancel(onErrorReason)
-                                    workLiveData.removeObserver(this)
-                                }
-                                WorkInfo.State.SUCCEEDED -> {
-                                    if (SessionSafeCoroutineWorker.hasFailed(wInfo.outputData)) {
-                                        Timber.e("## SAS verification [${tx?.transactionId}] failed to send verification message in state : ${tx?.state}")
-                                        tx?.cancel(onErrorReason)
-                                    } else {
-                                        if (onDone != null) {
-                                            onDone()
-                                        } else {
-                                            tx?.state = nextState
-                                        }
-                                    }
-                                    workLiveData.removeObserver(this)
-                                }
-                                else                     -> {
-                                    // nop
-                                }
-                            }
-                        }
+        verificationSenderScope.launch {
+            sequencer.post {
+                try {
+                    val params = SendVerificationMessageTask.Params(event)
+                    sendVerificationMessageTask.executeRetry(params, 5)
+                    // Do I need to update local echo state to sent?
+                    if (onDone != null) {
+                        onDone()
+                    } else {
+                        tx?.state = nextState
+                    }
+                } catch (failure: Throwable) {
+                    tx?.cancel(onErrorReason)
+                }
             }
         }
-
-        // TODO listen to DB to get synced info
-        coroutineScope.launch(Dispatchers.Main) {
-            workLiveData.observeForever(observer)
-        }
     }
 
     override fun sendVerificationRequest(supportedMethods: List,
@@ -173,60 +120,24 @@ internal class VerificationTransportRoomMessage(
         val content = info.toContent()
 
         val event = createEventAndLocalEcho(
-                localId,
-                EventType.MESSAGE,
-                roomId,
-                content
+                localId = localId,
+                type = EventType.MESSAGE,
+                roomId = roomId,
+                content = content
         )
 
-        val workerParams = WorkerParamsFactory.toData(
-                SendVerificationMessageWorker.Params(
-                        sessionId = sessionId,
-                        eventId = event.eventId ?: ""
-                )
-        )
-
-        val workRequest = workManagerProvider.matrixOneTimeWorkRequestBuilder()
-                .setConstraints(WorkManagerProvider.workConstraints)
-                .setInputData(workerParams)
-                .setBackoffCriteria(BackoffPolicy.LINEAR, WorkManagerProvider.BACKOFF_DELAY_MILLIS, TimeUnit.MILLISECONDS)
-                .build()
-
-        workManagerProvider.workManager
-                .beginUniqueWork("${roomId}_VerificationWork", ExistingWorkPolicy.APPEND_OR_REPLACE, workRequest)
-                .enqueue()
-
-        // I cannot just listen to the given work request, because when used in a uniqueWork,
-        // The callback is called while it is still Running ...
-
-        val workLiveData = workManagerProvider.workManager
-                .getWorkInfosForUniqueWorkLiveData("${roomId}_VerificationWork")
-
-        val observer = object : Observer> {
-            override fun onChanged(workInfoList: List?) {
-                workInfoList
-                        ?.filter { it.state == WorkInfo.State.SUCCEEDED }
-                        ?.firstOrNull { it.id == workRequest.id }
-                        ?.let { wInfo ->
-                            if (SessionSafeCoroutineWorker.hasFailed(wInfo.outputData)) {
-                                callback(null, null)
-                            } else {
-                                val eventId = wInfo.outputData.getString(localId)
-                                if (eventId != null) {
-                                    callback(eventId, validInfo)
-                                } else {
-                                    callback(null, null)
-                                }
-                            }
-                            workLiveData.removeObserver(this)
-                        }
+        verificationSenderScope.launch {
+            val params = SendVerificationMessageTask.Params(event)
+            sequencer.post {
+                try {
+                    val eventId = sendVerificationMessageTask.executeRetry(params, 5)
+                    // Do I need to update local echo state to sent?
+                    callback(eventId, validInfo)
+                } catch (failure: Throwable) {
+                    callback(null, null)
+                }
             }
         }
-
-        // TODO listen to DB to get synced info
-        coroutineScope.launch(Dispatchers.Main) {
-            workLiveData.observeForever(observer)
-        }
     }
 
     override fun cancelTransaction(transactionId: String, otherUserId: String, otherUserDeviceId: String?, code: CancelCode) {
@@ -236,15 +147,22 @@ internal class VerificationTransportRoomMessage(
                 roomId = roomId,
                 content = MessageVerificationCancelContent.create(transactionId, code).toContent()
         )
-        val workerParams = WorkerParamsFactory.toData(
-                SendVerificationMessageWorker.Params(
-                        sessionId = sessionId,
-                        eventId = event.eventId ?: ""
-                )
-        )
-        enqueueSendWork(workerParams)
+
+        verificationSenderScope.launch {
+            sequencer.post {
+                try {
+                    val params = SendVerificationMessageTask.Params(event)
+                    sendVerificationMessageTask.executeRetry(params, 5)
+                } catch (failure: Throwable) {
+                    Timber.w(failure, "Failed to cancel verification transaction")
+                }
+            }
+        }
     }
 
+    override fun cancelTransaction(transactionId: String, otherUserId: String, otherUserDeviceIds: List, code: CancelCode) =
+            cancelTransaction(transactionId, otherUserId, null, code)
+
     override fun done(transactionId: String,
                       onDone: (() -> Unit)?) {
         Timber.d("## SAS sending done for $transactionId")
@@ -258,47 +176,21 @@ internal class VerificationTransportRoomMessage(
                         )
                 ).toContent()
         )
-        val workerParams = WorkerParamsFactory.toData(
-                SendVerificationMessageWorker.Params(
-                        sessionId = sessionId,
-                        eventId = event.eventId ?: ""
-                )
-        )
-        val enqueueInfo = enqueueSendWork(workerParams)
-
-        val workLiveData = workManagerProvider.workManager
-                .getWorkInfosForUniqueWorkLiveData(uniqueQueueName())
-        val observer = object : Observer> {
-            override fun onChanged(workInfoList: List?) {
-                workInfoList
-                        ?.filter { it.state == WorkInfo.State.SUCCEEDED }
-                        ?.firstOrNull { it.id == enqueueInfo.second }
-                        ?.let { _ ->
-                            onDone?.invoke()
-                            workLiveData.removeObserver(this)
-                        }
+        verificationSenderScope.launch {
+            sequencer.post {
+                try {
+                    val params = SendVerificationMessageTask.Params(event)
+                    sendVerificationMessageTask.executeRetry(params, 5)
+                } catch (failure: Throwable) {
+                    Timber.w(failure, "Failed to complete (done) verification")
+                    // should we call onDone?
+                } finally {
+                    onDone?.invoke()
+                }
             }
         }
-
-        // TODO listen to DB to get synced info
-        coroutineScope.launch(Dispatchers.Main) {
-            workLiveData.observeForever(observer)
-        }
     }
 
-    private fun enqueueSendWork(workerParams: Data): Pair {
-        val workRequest = workManagerProvider.matrixOneTimeWorkRequestBuilder()
-                .setConstraints(WorkManagerProvider.workConstraints)
-                .setInputData(workerParams)
-                .setBackoffCriteria(BackoffPolicy.LINEAR, WorkManagerProvider.BACKOFF_DELAY_MILLIS, TimeUnit.MILLISECONDS)
-                .build()
-        return workManagerProvider.workManager
-                .beginUniqueWork(uniqueQueueName(), ExistingWorkPolicy.APPEND_OR_REPLACE, workRequest)
-                .enqueue() to workRequest.id
-    }
-
-    private fun uniqueQueueName() = "${roomId}_VerificationWork"
-
     override fun createAccept(tid: String,
                               keyAgreementProtocol: String,
                               hash: String,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessageFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessageFactory.kt
index b1b7ad7a98..345948e608 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessageFactory.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportRoomMessageFactory.kt
@@ -16,39 +16,35 @@
 
 package org.matrix.android.sdk.internal.crypto.verification
 
+import kotlinx.coroutines.CoroutineScope
+import org.matrix.android.sdk.internal.crypto.tasks.SendVerificationMessageTask
 import org.matrix.android.sdk.internal.di.DeviceId
-import org.matrix.android.sdk.internal.di.SessionId
 import org.matrix.android.sdk.internal.di.UserId
-import org.matrix.android.sdk.internal.di.WorkManagerProvider
 import org.matrix.android.sdk.internal.session.room.send.LocalEchoEventFactory
-import org.matrix.android.sdk.internal.task.TaskExecutor
 import org.matrix.android.sdk.internal.util.time.Clock
 import javax.inject.Inject
 
 internal class VerificationTransportRoomMessageFactory @Inject constructor(
-        private val workManagerProvider: WorkManagerProvider,
-        @SessionId
-        private val sessionId: String,
+        private val sendVerificationMessageTask: SendVerificationMessageTask,
         @UserId
         private val userId: String,
         @DeviceId
         private val deviceId: String?,
         private val localEchoEventFactory: LocalEchoEventFactory,
-        private val taskExecutor: TaskExecutor,
+        private val cryptoCoroutineScope: CoroutineScope,
         private val clock: Clock,
 ) {
 
     fun createTransport(roomId: String, tx: DefaultVerificationTransaction?): VerificationTransportRoomMessage {
         return VerificationTransportRoomMessage(
-                workManagerProvider,
-                sessionId,
-                userId,
-                deviceId,
-                roomId,
-                localEchoEventFactory,
-                tx,
-                taskExecutor.executorScope,
-                clock
+                sendVerificationMessageTask = sendVerificationMessageTask,
+                userId = userId,
+                userDeviceId = deviceId,
+                roomId = roomId,
+                localEchoEventFactory = localEchoEventFactory,
+                tx = tx,
+                cryptoCoroutineScope = cryptoCoroutineScope,
+                clock = clock,
         )
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt
index bc24ef2966..974adf3888 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/VerificationTransportToDevice.kt
@@ -193,6 +193,27 @@ internal class VerificationTransportToDevice(
                 .executeBy(taskExecutor)
     }
 
+    override fun cancelTransaction(transactionId: String, otherUserId: String, otherUserDeviceIds: List, code: CancelCode) {
+        Timber.d("## SAS canceling transaction $transactionId for reason $code")
+        val cancelMessage = KeyVerificationCancel.create(transactionId, code)
+        val contentMap = MXUsersDevicesMap()
+        val messages = otherUserDeviceIds.associateWith { cancelMessage }
+        contentMap.setObjects(otherUserId, messages)
+        sendToDeviceTask
+                .configureWith(SendToDeviceTask.Params(EventType.KEY_VERIFICATION_CANCEL, contentMap)) {
+                    this.callback = object : MatrixCallback {
+                        override fun onSuccess(data: Unit) {
+                            Timber.v("## SAS verification [$transactionId] canceled for reason ${code.value}")
+                        }
+
+                        override fun onFailure(failure: Throwable) {
+                            Timber.e(failure, "## SAS verification [$transactionId] failed to cancel.")
+                        }
+                    }
+                }
+                .executeBy(taskExecutor)
+    }
+
     override fun createAccept(tid: String,
                               keyAgreementProtocol: String,
                               hash: String,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt
index 1793cd123b..b1ad4d87b6 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt
@@ -22,8 +22,8 @@ import org.matrix.android.sdk.api.session.crypto.verification.QrCodeVerification
 import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState
 import org.matrix.android.sdk.api.session.events.model.EventType
 import org.matrix.android.sdk.api.util.fromBase64
-import org.matrix.android.sdk.internal.crypto.IncomingGossipingRequestManager
-import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager
+import org.matrix.android.sdk.internal.crypto.OutgoingKeyRequestManager
+import org.matrix.android.sdk.internal.crypto.SecretShareManager
 import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction
 import org.matrix.android.sdk.internal.crypto.crosssigning.fromBase64Safe
 import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore
@@ -37,8 +37,8 @@ internal class DefaultQrCodeVerificationTransaction(
         override val otherUserId: String,
         override var otherDeviceId: String?,
         private val crossSigningService: CrossSigningService,
-        outgoingGossipingRequestManager: OutgoingGossipingRequestManager,
-        incomingGossipingRequestManager: IncomingGossipingRequestManager,
+        outgoingKeyRequestManager: OutgoingKeyRequestManager,
+        secretShareManager: SecretShareManager,
         private val cryptoStore: IMXCryptoStore,
         // Not null only if other user is able to scan QR code
         private val qrCodeData: QrCodeData?,
@@ -48,8 +48,8 @@ internal class DefaultQrCodeVerificationTransaction(
 ) : DefaultVerificationTransaction(
         setDeviceVerificationAction,
         crossSigningService,
-        outgoingGossipingRequestManager,
-        incomingGossipingRequestManager,
+        outgoingKeyRequestManager,
+        secretShareManager,
         userId,
         transactionId,
         otherUserId,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/QrCodeData.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/QrCodeData.kt
index 34a9525194..f308807e04 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/QrCodeData.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/QrCodeData.kt
@@ -21,34 +21,34 @@ package org.matrix.android.sdk.internal.crypto.verification.qrcode
  */
 internal sealed class QrCodeData(
         /**
-         * the event ID or transaction_id of the associated verification
+         * the event ID or transaction_id of the associated verification.
          */
         open val transactionId: String,
         /**
-         * First key (32 bytes, in base64 no padding)
+         * First key (32 bytes, in base64 no padding).
          */
         val firstKey: String,
         /**
-         * Second key (32 bytes, in base64 no padding)
+         * Second key (32 bytes, in base64 no padding).
          */
         val secondKey: String,
         /**
-         * a random shared secret (in base64 no padding)
+         * a random shared secret (in base64 no padding).
          */
         open val sharedSecret: String
 ) {
     /**
-     * verifying another user with cross-signing
-     * QR code verification mode: 0x00
+     * Verifying another user with cross-signing
+     * QR code verification mode: 0x00.
      */
     data class VerifyingAnotherUser(
             override val transactionId: String,
             /**
-             * the user's own master cross-signing public key
+             * the user's own master cross-signing public key.
              */
             val userMasterCrossSigningPublicKey: String,
             /**
-             * what the device thinks the other user's master cross-signing key is
+             * what the device thinks the other user's master cross-signing key is.
              */
             val otherUserMasterCrossSigningPublicKey: String,
             override val sharedSecret: String
@@ -61,16 +61,16 @@ internal sealed class QrCodeData(
 
     /**
      * self-verifying in which the current device does trust the master key
-     * QR code verification mode: 0x01
+     * QR code verification mode: 0x01.
      */
     data class SelfVerifyingMasterKeyTrusted(
             override val transactionId: String,
             /**
-             * the user's own master cross-signing public key
+             * the user's own master cross-signing public key.
              */
             val userMasterCrossSigningPublicKey: String,
             /**
-             * what the device thinks the other device's device key is
+             * what the device thinks the other device's device key is.
              */
             val otherDeviceKey: String,
             override val sharedSecret: String
@@ -83,16 +83,16 @@ internal sealed class QrCodeData(
 
     /**
      * self-verifying in which the current device does not yet trust the master key
-     * QR code verification mode: 0x02
+     * QR code verification mode: 0x02.
      */
     data class SelfVerifyingMasterKeyNotTrusted(
             override val transactionId: String,
             /**
-             * the current device's device key
+             * the current device's device key.
              */
             val deviceKey: String,
             /**
-             * what the device thinks the user's master cross-signing key is
+             * what the device thinks the user's master cross-signing key is.
              */
             val userMasterCrossSigningPublicKey: String,
             override val sharedSecret: String
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt
index 7c622146d3..392c1a7185 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmKeysUtils.kt
@@ -53,7 +53,7 @@ internal class RealmKeysUtils @Inject constructor(context: Context,
     }
 
     /**
-     * Check if there is already a key for this alias
+     * Check if there is already a key for this alias.
      */
     private fun hasKeyForDatabase(alias: String): Boolean {
         return sharedPreferences.contains("${ENCRYPTED_KEY_PREFIX}_$alias")
@@ -77,8 +77,8 @@ internal class RealmKeysUtils @Inject constructor(context: Context,
     }
 
     /**
-     * Retrieves the key for this database
-     * throws if something goes wrong
+     * Retrieves the key for this database.
+     * Throws if something goes wrong.
      */
     private fun extractKeyForDatabase(alias: String): ByteArray {
         val encryptedB64 = sharedPreferences.getString("${ENCRYPTED_KEY_PREFIX}_$alias", null)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmSessionStoreMigration.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmSessionStoreMigration.kt
index 04a6e83ea1..55bccfd1ec 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmSessionStoreMigration.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/RealmSessionStoreMigration.kt
@@ -54,8 +54,8 @@ internal class RealmSessionStoreMigration @Inject constructor(
         private val normalizer: Normalizer
 ) : RealmMigration {
     /**
-     * Forces all RealmSessionStoreMigration instances to be equal
-     * Avoids Realm throwing when multiple instances of the migration are set
+     * Forces all RealmSessionStoreMigration instances to be equal.
+     * Avoids Realm throwing when multiple instances of the migration are set.
      */
     override fun equals(other: Any?) = other is RealmSessionStoreMigration
     override fun hashCode() = 1000
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt
index 4fdedabd70..caaf6b8110 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ChunkEntityHelper.kt
@@ -166,7 +166,7 @@ private fun ChunkEntity.addTimelineEventFromMerge(realm: Realm, timelineEventEnt
 }
 
 /**
- * Upon copy of the timeline events we should update the latestMessage TimelineEventEntity with the new one
+ * Upon copy of the timeline events we should update the latestMessage TimelineEventEntity with the new one.
  */
 private fun handleThreadSummary(realm: Realm, oldEventId: String, newTimelineEventEntity: TimelineEventEntity) {
     EventEntity
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt
index 03b1948302..db3647c3fa 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadEventsHelper.kt
@@ -83,7 +83,7 @@ internal fun EventEntity.findRootThreadEvent(): EventEntity? =
         }
 
 /**
- * Mark or update the current event a root thread event
+ * Mark or update the current event a root thread event.
  */
 internal fun EventEntity.markEventAsRoot(
         inThreadMessages: Int,
@@ -94,8 +94,8 @@ internal fun EventEntity.markEventAsRoot(
 }
 
 /**
- * Count the number of threads for the provided root thread eventId, and finds the latest event message
- * note: Redactions are handled by RedactionEventProcessor
+ * Count the number of threads for the provided root thread eventId, and finds the latest event message.
+ * Note: Redactions are handled by RedactionEventProcessor.
  * @param rootThreadEventId The root eventId that will find the number of threads
  * @return A ThreadSummary containing the counted threads and the latest event message
  */
@@ -150,7 +150,7 @@ internal fun countInThreadMessages(realm: Realm, roomId: String, rootThreadEvent
                 }.size
 
 /**
- * Mapping string to UnsignedData using Moshi
+ * Mapping string to UnsignedData using Moshi.
  */
 private fun String.toUnsignedData(): UnsignedData? =
         try {
@@ -162,7 +162,7 @@ private fun String.toUnsignedData(): UnsignedData? =
 
 /**
  * Lets compare them in case user is moving forward in the timeline and we cannot know the
- * exact chunk sequence while currentChunk is not yet committed in the DB
+ * exact chunk sequence while currentChunk is not yet committed in the DB.
  */
 private fun findMostRecentEvent(result: TimelineEventEntity, currentChunkLatestEvent: TimelineEventEntity?): TimelineEventEntity {
     currentChunkLatestEvent ?: return result
@@ -175,7 +175,7 @@ private fun findMostRecentEvent(result: TimelineEventEntity, currentChunkLatestE
 }
 
 /**
- * Find the latest event of the current chunk
+ * Find the latest event of the current chunk.
  */
 private fun findLatestSortedChunkEvent(chunk: ChunkEntity, rootThreadEventId: String): TimelineEventEntity? =
         chunk.timelineEvents.sort(TimelineEventEntityFields.DISPLAY_INDEX, Sort.DESCENDING)?.firstOrNull {
@@ -183,7 +183,7 @@ private fun findLatestSortedChunkEvent(chunk: ChunkEntity, rootThreadEventId: St
         }
 
 /**
- * Find all TimelineEventEntity that are root threads for the specified room
+ * Find all TimelineEventEntity that are root threads for the specified room.
  * @param roomId The room that all stored root threads will be returned
  */
 internal fun TimelineEventEntity.Companion.findAllThreadsForRoomId(realm: Realm, roomId: String): RealmQuery =
@@ -194,7 +194,7 @@ internal fun TimelineEventEntity.Companion.findAllThreadsForRoomId(realm: Realm,
                 .sort("${TimelineEventEntityFields.ROOT.THREAD_SUMMARY_LATEST_MESSAGE}.${TimelineEventEntityFields.ROOT.ORIGIN_SERVER_TS}", Sort.DESCENDING)
 
 /**
- * Map each root thread TimelineEvent with the equivalent decrypted text edition/replacement
+ * Map each root thread TimelineEvent with the equivalent decrypted text edition/replacement.
  */
 internal fun List.mapEventsWithEdition(realm: Realm, roomId: String): List =
         this.map {
@@ -217,7 +217,7 @@ internal fun List.mapEventsWithEdition(realm: Realm, roomId: Stri
         }
 
 /**
- * Returns a list of all the marked unread threads that exists for the specified room
+ * Returns a list of all the marked unread threads that exists for the specified room.
  * @param roomId The roomId that the user is currently in
  */
 internal fun TimelineEventEntity.Companion.findAllLocalThreadNotificationsForRoomId(realm: Realm, roomId: String): RealmQuery =
@@ -231,7 +231,7 @@ internal fun TimelineEventEntity.Companion.findAllLocalThreadNotificationsForRoo
                 .endGroup()
 
 /**
- * Returns whether or not the given user is participating in a current thread
+ * Returns whether or not the given user is participating in a current thread.
  * @param roomId the room that the thread exists
  * @param rootThreadEventId the thread that the search will be done
  * @param senderId the user that will try to find participation
@@ -246,7 +246,7 @@ internal fun TimelineEventEntity.Companion.isUserParticipatingInThread(realm: Re
                 ?: false
 
 /**
- * Returns whether or not the given user is mentioned in a current thread
+ * Returns whether or not the given user is mentioned in a current thread.
  * @param roomId the room that the thread exists
  * @param rootThreadEventId the thread that the search will be done
  * @param userId the user that will try to find if there is a mention
@@ -262,7 +262,7 @@ internal fun TimelineEventEntity.Companion.isUserMentionedInThread(realm: Realm,
                 ?: false
 
 /**
- * Find the read receipt for the current user
+ * Find the read receipt for the current user.
  */
 internal fun findMyReadReceipt(realm: Realm, roomId: String, userId: String): String? =
         ReadReceiptEntity.where(realm, roomId = roomId, userId = userId)
@@ -270,7 +270,7 @@ internal fun findMyReadReceipt(realm: Realm, roomId: String, userId: String): St
                 ?.eventId
 
 /**
- * Returns whether or not the user is mentioned in the event
+ * Returns whether or not the user is mentioned in the event.
  */
 internal fun isUserMentioned(currentUserId: String, timelineEventEntity: TimelineEventEntity?): Boolean {
     return timelineEventEntity?.root?.asDomain()?.isUserMentioned(currentUserId) == true
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt
index d052a7dea4..3bf574c207 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/helper/ThreadSummaryHelper.kt
@@ -65,7 +65,7 @@ internal fun ThreadSummaryEntity.updateThreadSummary(
 }
 
 /**
- * Updates the root thread event properties
+ * Updates the root thread event properties.
  */
 internal fun ThreadSummaryEntity.updateThreadSummaryRootEvent(
         rootThreadEventEntity: EventEntity,
@@ -84,7 +84,7 @@ internal fun ThreadSummaryEntity.updateThreadSummaryRootEvent(
 }
 
 /**
- * Updates the latest thread event properties
+ * Updates the latest thread event properties.
  */
 internal fun ThreadSummaryEntity.updateThreadSummaryLatestEvent(
         latestThreadEventEntity: EventEntity?,
@@ -241,7 +241,7 @@ private fun decryptIfNeeded(cryptoService: CryptoService?, eventEntity: EventEnt
 }
 
 /**
- * Request decryption
+ * Request decryption.
  */
 private fun requestDecryption(eventDecryptor: TimelineEventDecryptor?, event: Event?) {
     eventDecryptor ?: return
@@ -255,7 +255,7 @@ private fun requestDecryption(eventDecryptor: TimelineEventDecryptor?, event: Ev
 }
 
 /**
- * If we don't have any new state on this user, get it from db
+ * If we don't have any new state on this user, get it from db.
  */
 private fun HashMap.addSenderState(realm: Realm, roomId: String, senderId: String) {
     getOrPut(senderId) {
@@ -267,7 +267,7 @@ private fun HashMap.addSenderState(realm: Realm, roo
 }
 
 /**
- * Create an EventEntity for the root thread event or get an existing one
+ * Create an EventEntity for the root thread event or get an existing one.
  */
 private fun createEventEntity(realm: Realm, roomId: String, event: Event, currentTimeMillis: Long): EventEntity {
     val ageLocalTs = event.unsignedData?.age?.let { currentTimeMillis - it }
@@ -294,15 +294,15 @@ private fun createLatestEventEntity(
 }
 
 /**
- * Returned the latest event message, if any
+ * Returned the latest event message, if any.
  */
 private fun getLatestEvent(rootThreadEvent: Event): Event? {
     return rootThreadEvent.unsignedData?.relations?.latestThread?.event
 }
 
 /**
- * Find all ThreadSummaryEntity for the specified roomId, sorted by origin server
- * note: Sorting cannot be provided by server, so we have to use that unstable property
+ * Find all ThreadSummaryEntity for the specified roomId, sorted by origin server.
+ * note: Sorting cannot be provided by server, so we have to use that unstable property.
  * @param roomId The id of the room
  */
 internal fun ThreadSummaryEntity.Companion.findAllThreadsForRoomId(realm: Realm, roomId: String): RealmQuery =
@@ -311,7 +311,7 @@ internal fun ThreadSummaryEntity.Companion.findAllThreadsForRoomId(realm: Realm,
                 .sort(ThreadSummaryEntityFields.LATEST_THREAD_EVENT_ENTITY.ORIGIN_SERVER_TS, Sort.DESCENDING)
 
 /**
- * Enhance each [ThreadSummary] root and latest event with the equivalent decrypted text edition/replacement
+ * Enhance each [ThreadSummary] root and latest event with the equivalent decrypted text edition/replacement.
  */
 internal fun List.enhanceWithEditions(realm: Realm, roomId: String): List =
         this.map {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt
index 737c4b4608..a00a2a8ee1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/DraftMapper.kt
@@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.room.send.UserDraft
 import org.matrix.android.sdk.internal.database.model.DraftEntity
 
 /**
- * DraftEntity <-> UserDraft
+ * DraftEntity <-> UserDraft.
  */
 internal object DraftMapper {
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/HomeServerCapabilitiesMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/HomeServerCapabilitiesMapper.kt
index 2e33988a22..20af43530c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/HomeServerCapabilitiesMapper.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/mapper/HomeServerCapabilitiesMapper.kt
@@ -28,7 +28,7 @@ import org.matrix.android.sdk.internal.session.homeserver.RoomVersions
 import org.matrix.android.sdk.internal.session.room.version.DefaultRoomVersionService
 
 /**
- * HomeServerCapabilitiesEntity -> HomeSeverCapabilities
+ * HomeServerCapabilitiesEntity -> HomeSeverCapabilities.
  */
 internal object HomeServerCapabilitiesMapper {
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo026.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo026.kt
index 35a6135ba2..5bab93cb04 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo026.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo026.kt
@@ -29,7 +29,7 @@ import org.matrix.android.sdk.internal.util.database.RealmMigrator
 /**
  * Migrating to:
  * Live thread list: using enhanced /messages api MSC3440
- * Live thread timeline: using /relations api
+ * Live thread timeline: using /relations api.
  */
 internal class MigrateSessionTo026(realm: DynamicRealm) : RealmMigrator(realm, 26) {
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo027.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo027.kt
index fdd8c46d02..40189c0f46 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo027.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo027.kt
@@ -24,7 +24,7 @@ import org.matrix.android.sdk.internal.util.database.RealmMigrator
 
 /**
  * Migrating to:
- * Live location sharing aggregated summary
+ * Live location sharing aggregated summary.
  */
 internal class MigrateSessionTo027(realm: DynamicRealm) : RealmMigrator(realm, 27) {
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo028.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo028.kt
index 1d0c638d7b..ed9b90d288 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo028.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/migration/MigrateSessionTo028.kt
@@ -22,7 +22,7 @@ import org.matrix.android.sdk.internal.util.database.RealmMigrator
 
 /**
  * Migrating to:
- * Live location sharing aggregated summary
+ * Live location sharing aggregated summary.
  */
 internal class MigrateSessionTo028(realm: DynamicRealm) : RealmMigrator(realm, 28) {
 
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt
index 822bc1bd8f..8399d82d5d 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/ChunkEntity.kt
@@ -69,7 +69,7 @@ internal fun ChunkEntity.deleteOnCascade(
 }
 
 /**
- * Delete the chunk along with the thread events that were temporarily created
+ * Delete the chunk along with the thread events that were temporarily created.
  */
 internal fun ChunkEntity.deleteAndClearThreadEvents() {
     assertIsManaged()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EditAggregatedSummaryEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EditAggregatedSummaryEntity.kt
index 0ed927a6b8..61acd51dd4 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EditAggregatedSummaryEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EditAggregatedSummaryEntity.kt
@@ -20,7 +20,7 @@ import io.realm.RealmObject
 import io.realm.annotations.RealmClass
 
 /**
- * Keep all the editions of a message
+ * Keep all the editions of a message.
  */
 internal open class EditAggregatedSummaryEntity(
         // The list of the editions used to build the summary (might be out of sync if chunked received from message chunk)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventAnnotationsSummaryEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventAnnotationsSummaryEntity.kt
index c3abd8b028..645998d0c0 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventAnnotationsSummaryEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/EventAnnotationsSummaryEntity.kt
@@ -33,7 +33,7 @@ internal open class EventAnnotationsSummaryEntity(
 ) : RealmObject() {
 
     /**
-     * Cleanup undesired editions, done by users different from the originalEventSender
+     * Cleanup undesired editions, done by users different from the originalEventSender.
      */
     fun cleanUp(originalEventSenderId: String?) {
         originalEventSenderId ?: return
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/FilterEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/FilterEntity.kt
index 96014d29ad..e138e305c7 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/FilterEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/FilterEntity.kt
@@ -19,8 +19,8 @@ package org.matrix.android.sdk.internal.database.model
 import io.realm.RealmObject
 
 /**
- * Contain a map between Json filter string and filterId (from Homeserver)
- * Currently there is only one object in this table
+ * Contain a map between Json filter string and filterId (from Homeserver).
+ * Currently there is only one object in this table.
  */
 internal open class FilterEntity(
         // The serialized FilterBody
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PendingThreePidEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PendingThreePidEntity.kt
index 98c38c8969..bcf64e0da8 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PendingThreePidEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PendingThreePidEntity.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.database.model
 import io.realm.RealmObject
 
 /**
- * This class is used to store pending threePid data, when user wants to add a threePid to his account
+ * This class is used to store pending threePid data, when user wants to add a threePid to his account.
  */
 internal open class PendingThreePidEntity(
         var email: String? = null,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PollResponseAggregatedSummaryEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PollResponseAggregatedSummaryEntity.kt
index 0000a558ac..d759bd3cd9 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PollResponseAggregatedSummaryEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/PollResponseAggregatedSummaryEntity.kt
@@ -19,7 +19,7 @@ import io.realm.RealmList
 import io.realm.RealmObject
 
 /**
- * Keep the latest state of a poll
+ * Keep the latest state of a poll.
  */
 internal open class PollResponseAggregatedSummaryEntity(
         // For now we persist this a JSON for greater flexibility
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SessionRealmModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SessionRealmModule.kt
index be5a500956..890c2300f8 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SessionRealmModule.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/SessionRealmModule.kt
@@ -22,7 +22,7 @@ import org.matrix.android.sdk.internal.database.model.presence.UserPresenceEntit
 import org.matrix.android.sdk.internal.database.model.threads.ThreadSummaryEntity
 
 /**
- * Realm module for Session
+ * Realm module for Session.
  */
 @RealmModule(
         library = true,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt
index 06a6349350..2c778f9797 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/UserDraftsEntity.kt
@@ -22,7 +22,7 @@ import io.realm.RealmResults
 import io.realm.annotations.LinkingObjects
 
 /**
- * Create a specific table to be able to do direct query on it and keep the draft ordered
+ * Create a specific table to be able to do direct query on it and keep the draft ordered.
  */
 internal open class UserDraftsEntity(var userDrafts: RealmList = RealmList()
 ) : RealmObject() {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/livelocation/LiveLocationShareAggregatedSummaryEntity.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/livelocation/LiveLocationShareAggregatedSummaryEntity.kt
index 1376839f93..4d0d2c5c64 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/livelocation/LiveLocationShareAggregatedSummaryEntity.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/model/livelocation/LiveLocationShareAggregatedSummaryEntity.kt
@@ -36,7 +36,7 @@ internal open class LiveLocationShareAggregatedSummaryEntity(
         var endOfLiveTimestampMillis: Long? = null,
 
         /**
-         * For now we persist this as a JSON for greater flexibility
+         * For now we persist this as a JSON for greater flexibility.
          * @see [org.matrix.android.sdk.api.session.room.model.message.MessageBeaconLocationDataContent]
          */
         var lastLocationContent: String? = null,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/FilterEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/FilterEntityQueries.kt
index 3968169e08..903282bac4 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/FilterEntityQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/FilterEntityQueries.kt
@@ -23,14 +23,14 @@ import org.matrix.android.sdk.internal.database.model.FilterEntity
 import org.matrix.android.sdk.internal.session.filter.FilterFactory
 
 /**
- * Get the current filter
+ * Get the current filter.
  */
 internal fun FilterEntity.Companion.get(realm: Realm): FilterEntity? {
     return realm.where().findFirst()
 }
 
 /**
- * Get the current filter, create one if it does not exist
+ * Get the current filter, create one if it does not exist.
  */
 internal fun FilterEntity.Companion.getOrCreate(realm: Realm): FilterEntity {
     return get(realm) ?: realm.createObject()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/HomeServerCapabilitiesQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/HomeServerCapabilitiesQueries.kt
index 4f8ac20e94..2cb6faafb7 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/HomeServerCapabilitiesQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/HomeServerCapabilitiesQueries.kt
@@ -22,14 +22,14 @@ import io.realm.kotlin.where
 import org.matrix.android.sdk.internal.database.model.HomeServerCapabilitiesEntity
 
 /**
- * Get the current HomeServerCapabilitiesEntity, return null if it does not exist
+ * Get the current HomeServerCapabilitiesEntity, return null if it does not exist.
  */
 internal fun HomeServerCapabilitiesEntity.Companion.get(realm: Realm): HomeServerCapabilitiesEntity? {
     return realm.where().findFirst()
 }
 
 /**
- * Get the current HomeServerCapabilitiesEntity, create one if it does not exist
+ * Get the current HomeServerCapabilitiesEntity, create one if it does not exist.
  */
 internal fun HomeServerCapabilitiesEntity.Companion.getOrCreate(realm: Realm): HomeServerCapabilitiesEntity {
     return get(realm) ?: realm.createObject()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PreviewUrlCacheEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PreviewUrlCacheEntityQueries.kt
index a139c17439..32ea7a1ba6 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PreviewUrlCacheEntityQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/PreviewUrlCacheEntityQueries.kt
@@ -23,7 +23,7 @@ import org.matrix.android.sdk.internal.database.model.PreviewUrlCacheEntity
 import org.matrix.android.sdk.internal.database.model.PreviewUrlCacheEntityFields
 
 /**
- * Get the current PreviewUrlCacheEntity, return null if it does not exist
+ * Get the current PreviewUrlCacheEntity, return null if it does not exist.
  */
 internal fun PreviewUrlCacheEntity.Companion.get(realm: Realm, url: String): PreviewUrlCacheEntity? {
     return realm.where()
@@ -32,7 +32,7 @@ internal fun PreviewUrlCacheEntity.Companion.get(realm: Realm, url: String): Pre
 }
 
 /**
- * Get the current PreviewUrlCacheEntity, create one if it does not exist
+ * Get the current PreviewUrlCacheEntity, create one if it does not exist.
  */
 internal fun PreviewUrlCacheEntity.Companion.getOrCreate(realm: Realm, url: String): PreviewUrlCacheEntity {
     return get(realm, url) ?: realm.createObject(url)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RawCacheQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RawCacheQueries.kt
index ac5e29e1de..634c3b26f2 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RawCacheQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/RawCacheQueries.kt
@@ -23,7 +23,7 @@ import org.matrix.android.sdk.internal.database.model.RawCacheEntity
 import org.matrix.android.sdk.internal.database.model.RawCacheEntityFields
 
 /**
- * Get the current RawCacheEntity, return null if it does not exist
+ * Get the current RawCacheEntity, return null if it does not exist.
  */
 internal fun RawCacheEntity.Companion.get(realm: Realm, url: String): RawCacheEntity? {
     return realm.where()
@@ -32,7 +32,7 @@ internal fun RawCacheEntity.Companion.get(realm: Realm, url: String): RawCacheEn
 }
 
 /**
- * Get the current RawCacheEntity, create one if it does not exist
+ * Get the current RawCacheEntity, create one if it does not exist.
  */
 internal fun RawCacheEntity.Companion.getOrCreate(realm: Realm, url: String): RawCacheEntity {
     return get(realm, url) ?: realm.createObject(url)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt
index 6c587dfcae..1a832a29bb 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/ReadQueries.kt
@@ -61,7 +61,7 @@ private fun TimelineEventEntity.isBeforeLatestReadReceipt(realm: Realm, roomId:
 
 /**
  * Missing events can be caused by the latest timeline chunk no longer contain an older event or
- * by fast lane eagerly displaying events before the database has finished updating
+ * by fast lane eagerly displaying events before the database has finished updating.
  */
 private fun hasReadMissingEvent(realm: Realm, latestChunkEntity: ChunkEntity, roomId: String, userId: String, eventId: String): Boolean {
     return realm.doesEventExistInChunkHistory(eventId) && realm.hasReadReceiptInLatestChunk(latestChunkEntity, roomId, userId)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt
index 215ab34f95..1654a33806 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventEntityQueries.kt
@@ -143,7 +143,7 @@ internal fun RealmQuery.filterSendStates(sendStates: List): RealmResults {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventFilter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventFilter.kt
index a7317506a0..7a65623b76 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventFilter.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/query/TimelineEventFilter.kt
@@ -17,11 +17,11 @@
 package org.matrix.android.sdk.internal.database.query
 
 /**
- * Query strings used to filter the timeline events regarding the Json raw string of the Event
+ * Query strings used to filter the timeline events regarding the Json raw string of the Event.
  */
 internal object TimelineEventFilter {
     /**
-     * To apply to Event.content
+     * To apply to Event.content.
      */
     internal object Content {
         internal const val EDIT = """{*"m.relates_to"*"rel_type":*"m.replace"*}"""
@@ -30,14 +30,14 @@ internal object TimelineEventFilter {
     }
 
     /**
-     * To apply to Event.decryptionResultJson
+     * To apply to Event.decryptionResultJson.
      */
     internal object DecryptedContent {
         internal const val URL = """{*"file":*"url":*}"""
     }
 
     /**
-     * To apply to Event.unsigned
+     * To apply to Event.unsigned.
      */
     internal object Unsigned {
         internal const val REDACTED = """{*"redacted_because":*}"""
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/tools/RealmDebugTools.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/tools/RealmDebugTools.kt
index 103e84dea6..dc20549eb3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/tools/RealmDebugTools.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/database/tools/RealmDebugTools.kt
@@ -25,7 +25,7 @@ internal class RealmDebugTools(
         private val realmConfiguration: RealmConfiguration
 ) {
     /**
-     * Log info about the DB
+     * Log info about the DB.
      */
     fun logInfo(baseName: String) {
         buildString {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixScope.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixScope.kt
index b027d47144..21e324c05f 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixScope.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/MatrixScope.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.di
 import javax.inject.Scope
 
 /**
- * Use the annotation @MatrixScope to annotate classes we want the SDK to instantiate only once
+ * Use the annotation @MatrixScope to annotate classes we want the SDK to instantiate only once.
  */
 @Scope
 @MustBeDocumented
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/StringQualifiers.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/StringQualifiers.kt
index d74a8dce57..05ba6e408c 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/StringQualifiers.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/StringQualifiers.kt
@@ -19,28 +19,28 @@ package org.matrix.android.sdk.internal.di
 import javax.inject.Qualifier
 
 /**
- * Used to inject the userId
+ * Used to inject the userId.
  */
 @Qualifier
 @Retention(AnnotationRetention.RUNTIME)
 internal annotation class UserId
 
 /**
- * Used to inject the deviceId
+ * Used to inject the deviceId.
  */
 @Qualifier
 @Retention(AnnotationRetention.RUNTIME)
 internal annotation class DeviceId
 
 /**
- * Used to inject the md5 of the userId
+ * Used to inject the md5 of the userId.
  */
 @Qualifier
 @Retention(AnnotationRetention.RUNTIME)
 internal annotation class UserMd5
 
 /**
- * Used to inject the sessionId, which is defined as md5(userId|deviceId)
+ * Used to inject the sessionId, which is defined as md5(userId|deviceId).
  */
 @Qualifier
 @Retention(AnnotationRetention.RUNTIME)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt
index 60760be29f..c59936af94 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/di/WorkManagerProvider.kt
@@ -50,14 +50,14 @@ internal class WorkManagerProvider @Inject constructor(
     }
 
     /**
-     * Create a OneTimeWorkRequestBuilder, with the Matrix SDK tag
+     * Create a OneTimeWorkRequestBuilder, with the Matrix SDK tag.
      */
     inline fun  matrixOneTimeWorkRequestBuilder() =
             OneTimeWorkRequestBuilder()
                     .addTag(tag)
 
     /**
-     * Create a PeriodicWorkRequestBuilder, with the Matrix SDK tag
+     * Create a PeriodicWorkRequestBuilder, with the Matrix SDK tag.
      */
     inline fun  matrixPeriodicWorkRequestBuilder(repeatInterval: Long,
                                                                                repeatIntervalTimeUnit: TimeUnit) =
@@ -65,7 +65,7 @@ internal class WorkManagerProvider @Inject constructor(
                     .addTag(tag)
 
     /**
-     * Cancel all works instantiated by the Matrix SDK for the current session, and not those from the SDK client, or for other sessions
+     * Cancel all works instantiated by the Matrix SDK for the current session, and not those from the SDK client, or for other sessions.
      */
     fun cancelAllWorks() {
         workManager.let {
@@ -101,7 +101,7 @@ internal class WorkManagerProvider @Inject constructor(
         private const val MATRIX_SDK_TAG_PREFIX = "MatrixSDK-"
 
         /**
-         * Default constraints: connected network
+         * Default constraints: connected network.
          */
         val workConstraints = Constraints.Builder()
                 .setRequiredNetworkType(NetworkType.CONNECTED)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/Primitives.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/Primitives.kt
index 290f06142c..c08dfa02e8 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/Primitives.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/Primitives.kt
@@ -17,6 +17,6 @@
 package org.matrix.android.sdk.internal.extensions
 
 /**
- * Convert a signed byte to a int value
+ * Convert a signed byte to a int value.
  */
 internal fun Byte.toUnsignedInt() = toInt() and 0xff
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/RealmExtensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/RealmExtensions.kt
index 28b9f64188..00cbe0aa85 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/RealmExtensions.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/extensions/RealmExtensions.kt
@@ -26,7 +26,7 @@ internal fun RealmObject.assertIsManaged() {
 }
 
 /**
- * Clear a RealmList by deleting all its items calling the provided lambda
+ * Clear a RealmList by deleting all its items calling the provided lambda.
  */
 internal fun  RealmList.clearWith(delete: (T) -> Unit) {
     while (!isEmpty()) {
@@ -35,7 +35,7 @@ internal fun  RealmList.clearWith(delete: (T) -> Unit) {
 }
 
 /**
- * Schedule a refresh of the HomeServers capabilities
+ * Schedule a refresh of the HomeServers capabilities.
  */
 internal fun RealmObjectSchema?.forceRefreshOfHomeServerCapabilities(): RealmObjectSchema? {
     return this?.transform { obj ->
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/riot/WellKnown.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/riot/WellKnown.kt
index 087f99ba7e..a754a0da96 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/riot/WellKnown.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/legacy/riot/WellKnown.kt
@@ -63,7 +63,7 @@ class WellKnown {
     var integrations: Map? = null
 
     /**
-     * Returns the list of integration managers proposed
+     * Returns the list of integration managers proposed.
      */
     fun getIntegrationManagers(): List {
         val managers = ArrayList()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt
index 3d2b2bfbfb..65bf3fcadf 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/NetworkConnectivityChecker.kt
@@ -27,7 +27,7 @@ import javax.inject.Inject
 
 internal interface NetworkConnectivityChecker {
     /**
-     * Returns true when internet is available
+     * Returns true when internet is available.
      */
     @WorkerThread
     fun hasInternetAccess(forcePing: Boolean): Boolean
@@ -59,7 +59,7 @@ internal class DefaultNetworkConnectivityChecker @Inject constructor(private val
     }
 
     /**
-     * Returns true when internet is available
+     * Returns true when internet is available.
      */
     @WorkerThread
     override fun hasInternetAccess(forcePing: Boolean): Boolean {
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt
index 60055be9ec..5268ea851d 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitExtensions.kt
@@ -53,21 +53,21 @@ internal suspend fun okhttp3.Call.awaitResponse(): okhttp3.Response {
 }
 
 /**
- * Convert a retrofit Response to a Failure, and eventually parse errorBody to convert it to a MatrixError
+ * Convert a retrofit Response to a Failure, and eventually parse errorBody to convert it to a [MatrixError].
  */
 internal fun  Response.toFailure(globalErrorReceiver: GlobalErrorReceiver?): Failure {
     return toFailure(errorBody(), code(), globalErrorReceiver)
 }
 
 /**
- * Convert a HttpException to a Failure, and eventually parse errorBody to convert it to a MatrixError
+ * Convert a HttpException to a Failure, and eventually parse errorBody to convert it to a [MatrixError].
  */
 internal fun HttpException.toFailure(globalErrorReceiver: GlobalErrorReceiver?): Failure {
     return toFailure(response()?.errorBody(), code(), globalErrorReceiver)
 }
 
 /**
- * Convert a okhttp3 Response to a Failure, and eventually parse errorBody to convert it to a MatrixError
+ * Convert a okhttp3 Response to a Failure, and eventually parse errorBody to convert it to a [MatrixError].
  */
 internal fun okhttp3.Response.toFailure(globalErrorReceiver: GlobalErrorReceiver?): Failure {
     return toFailure(body, code, globalErrorReceiver)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitFactory.kt
index 0a797c8bc0..b2eea84b07 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitFactory.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/RetrofitFactory.kt
@@ -29,7 +29,7 @@ import javax.inject.Inject
 internal class RetrofitFactory @Inject constructor(private val moshi: Moshi) {
 
     /**
-     * Use only for authentication service
+     * Use only for authentication service.
      */
     fun create(okHttpClient: OkHttpClient, baseUrl: String): Retrofit {
         return Retrofit.Builder()
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/CheckNumberType.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/CheckNumberType.kt
index 6efa347d3a..8b54978279 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/CheckNumberType.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/parsing/CheckNumberType.kt
@@ -33,7 +33,7 @@ internal interface CheckNumberType {
     companion object {
         val JSON_ADAPTER_FACTORY = object : JsonAdapter.Factory {
             @Nullable
-            override fun create(type: Type, annotations: Set?, moshi: Moshi): JsonAdapter<*>? {
+            override fun create(type: Type, annotations: Set, moshi: Moshi): JsonAdapter<*>? {
                 if (type !== Any::class.java) {
                     return null
                 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/CertUtil.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/CertUtil.kt
index d8bdc5fc2b..2ef40fe2a3 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/CertUtil.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/network/ssl/CertUtil.kt
@@ -33,7 +33,7 @@ import javax.net.ssl.TrustManagerFactory
 import javax.net.ssl.X509TrustManager
 
 /**
- * Various utility classes for dealing with X509Certificates
+ * Various utility classes for dealing with X509Certificates.
  */
 internal object CertUtil {
 
@@ -43,7 +43,7 @@ internal object CertUtil {
     private val hexArray = "0123456789ABCDEF".toCharArray()
 
     /**
-     * Generates the SHA-256 fingerprint of the given certificate
+     * Generates the SHA-256 fingerprint of the given certificate.
      *
      * @param cert the certificate.
      * @return the finger print
@@ -55,7 +55,7 @@ internal object CertUtil {
     }
 
     /**
-     * Generates the SHA-1 fingerprint of the given certificate
+     * Generates the SHA-1 fingerprint of the given certificate.
      *
      * @param cert the certificated
      * @return the SHA1 fingerprint
@@ -109,7 +109,7 @@ internal object CertUtil {
 
     /**
      * Recursively checks the exception to see if it was caused by an
-     * UnrecognizedCertificateException
+     * UnrecognizedCertificateException.
      *
      * @param root the throwable.
      * @return The UnrecognizedCertificateException if exists, else null.
@@ -250,7 +250,7 @@ internal object CertUtil {
         builder.supportsTlsExtensions(hsConfig.shouldAcceptTlsExtensions)
         val list = ArrayList()
         list.add(builder.build())
-        // TODO: we should display a warning if user enter an http url
+        // TODO we should display a warning if user enter an http url
         if (hsConfig.allowHttpExtension || hsConfig.homeServerUriBase.toString().startsWith("http://")) {
             list.add(ConnectionSpec.CLEARTEXT)
         }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmMigration.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmMigration.kt
index 8dffac5fa0..a9dfd47b5a 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmMigration.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmMigration.kt
@@ -24,8 +24,8 @@ import javax.inject.Inject
 
 internal class GlobalRealmMigration @Inject constructor() : RealmMigration {
     /**
-     * Forces all GlobalRealmMigration instances to be equal
-     * Avoids Realm throwing when multiple instances of the migration are set
+     * Forces all GlobalRealmMigration instances to be equal.
+     * Avoids Realm throwing when multiple instances of the migration are set.
      */
     override fun equals(other: Any?) = other is GlobalRealmMigration
     override fun hashCode() = 2000
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmModule.kt
index c95e4316e2..2d9ec8e820 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmModule.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/raw/GlobalRealmModule.kt
@@ -21,7 +21,7 @@ import org.matrix.android.sdk.internal.database.model.KnownServerUrlEntity
 import org.matrix.android.sdk.internal.database.model.RawCacheEntity
 
 /**
- * Realm module for global classes
+ * Realm module for global classes.
  */
 @RealmModule(
         library = true,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt
index 78f1c84f3d..760aa41081 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/DefaultFileService.kt
@@ -72,12 +72,12 @@ internal class DefaultFileService @Inject constructor(
 
     /**
      * Retain ongoing downloads to avoid re-downloading and already downloading file
-     * map of mxCurl to callbacks
+     * map of mxCurl to callbacks.
      */
     private val ongoing = mutableMapOf>()
 
     /**
-     * Download file in the cache folder, and eventually decrypt it
+     * Download file in the cache folder, and eventually decrypt it.
      * TODO looks like files are copied 3 times
      */
     override suspend fun downloadFile(fileName: String,
@@ -88,7 +88,7 @@ internal class DefaultFileService @Inject constructor(
 
         Timber.v("## FileService downloadFile $url")
 
-        // TODO: Remove use of `synchronized` in suspend function.
+        // TODO Remove use of `synchronized` in suspend function.
         val existingDownload = synchronized(ongoing) {
             val existing = ongoing[url]
             if (existing != null) {
@@ -312,7 +312,7 @@ internal class DefaultFileService @Inject constructor(
 
     /**
      * Use this URI and pass it to intent using flag Intent.FLAG_GRANT_READ_URI_PERMISSION
-     * (if not other app won't be able to access it)
+     * (if not other app won't be able to access it).
      */
     override fun getTemporarySharableURI(mxcUrl: String?,
                                          fileName: String,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt
index fb9b2da6c1..050480e6c9 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionComponent.kt
@@ -21,12 +21,8 @@ import dagger.Component
 import org.matrix.android.sdk.api.MatrixCoroutineDispatchers
 import org.matrix.android.sdk.api.auth.data.SessionParams
 import org.matrix.android.sdk.api.session.Session
-import org.matrix.android.sdk.internal.crypto.CancelGossipRequestWorker
 import org.matrix.android.sdk.internal.crypto.CryptoModule
-import org.matrix.android.sdk.internal.crypto.SendGossipRequestWorker
-import org.matrix.android.sdk.internal.crypto.SendGossipWorker
 import org.matrix.android.sdk.internal.crypto.crosssigning.UpdateTrustWorker
-import org.matrix.android.sdk.internal.crypto.verification.SendVerificationMessageWorker
 import org.matrix.android.sdk.internal.di.MatrixComponent
 import org.matrix.android.sdk.internal.federation.FederationModule
 import org.matrix.android.sdk.internal.network.NetworkConnectivityChecker
@@ -133,14 +129,6 @@ internal interface SessionComponent {
 
     fun inject(worker: AddPusherWorker)
 
-    fun inject(worker: SendVerificationMessageWorker)
-
-    fun inject(worker: SendGossipRequestWorker)
-
-    fun inject(worker: CancelGossipRequestWorker)
-
-    fun inject(worker: SendGossipWorker)
-
     fun inject(worker: UpdateTrustWorker)
 
     @Component.Factory
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt
index d48aa4f8cd..9208ff219b 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/SessionModule.kt
@@ -49,7 +49,6 @@ import org.matrix.android.sdk.api.util.md5
 import org.matrix.android.sdk.internal.crypto.secrets.DefaultSharedSecretStorageService
 import org.matrix.android.sdk.internal.crypto.tasks.DefaultRedactEventTask
 import org.matrix.android.sdk.internal.crypto.tasks.RedactEventTask
-import org.matrix.android.sdk.internal.crypto.verification.VerificationMessageProcessor
 import org.matrix.android.sdk.internal.database.EventInsertLiveObserver
 import org.matrix.android.sdk.internal.database.RealmSessionProvider
 import org.matrix.android.sdk.internal.database.SessionRealmConfigurationFactory
@@ -88,8 +87,6 @@ import org.matrix.android.sdk.internal.session.integrationmanager.IntegrationMan
 import org.matrix.android.sdk.internal.session.openid.DefaultOpenIdService
 import org.matrix.android.sdk.internal.session.permalinks.DefaultPermalinkService
 import org.matrix.android.sdk.internal.session.room.EventRelationsAggregationProcessor
-import org.matrix.android.sdk.internal.session.room.aggregation.livelocation.DefaultLiveLocationAggregationProcessor
-import org.matrix.android.sdk.internal.session.room.aggregation.livelocation.LiveLocationAggregationProcessor
 import org.matrix.android.sdk.internal.session.room.aggregation.poll.DefaultPollAggregationProcessor
 import org.matrix.android.sdk.internal.session.room.aggregation.poll.PollAggregationProcessor
 import org.matrix.android.sdk.internal.session.room.create.RoomCreateEventProcessor
@@ -320,10 +317,6 @@ internal abstract class SessionModule {
     @IntoSet
     abstract fun bindRoomCreateEventProcessor(processor: RoomCreateEventProcessor): EventInsertLiveProcessor
 
-    @Binds
-    @IntoSet
-    abstract fun bindVerificationMessageProcessor(processor: VerificationMessageProcessor): EventInsertLiveProcessor
-
     @Binds
     @IntoSet
     abstract fun bindCallEventProcessor(processor: CallEventProcessor): EventInsertLiveProcessor
@@ -395,9 +388,6 @@ internal abstract class SessionModule {
     @Binds
     abstract fun bindEventSenderProcessor(processor: EventSenderProcessorCoroutine): EventSenderProcessor
 
-    @Binds
-    abstract fun bindLiveLocationAggregationProcessor(processor: DefaultLiveLocationAggregationProcessor): LiveLocationAggregationProcessor
-
     @Binds
     abstract fun bindPollAggregationProcessor(processor: DefaultPollAggregationProcessor): PollAggregationProcessor
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/AccountAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/AccountAPI.kt
index a04d0f2686..4bd3b6360d 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/AccountAPI.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/account/AccountAPI.kt
@@ -30,7 +30,7 @@ internal interface AccountAPI {
     suspend fun changePassword(@Body params: ChangePasswordParams)
 
     /**
-     * Deactivate the user account
+     * Deactivate the user account.
      *
      * @param params the deactivate account params
      */
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/GetTurnServerTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/GetTurnServerTask.kt
index d53ddb7371..1313fcaa62 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/GetTurnServerTask.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/GetTurnServerTask.kt
@@ -22,16 +22,16 @@ import org.matrix.android.sdk.internal.network.executeRequest
 import org.matrix.android.sdk.internal.task.Task
 import javax.inject.Inject
 
-internal abstract class GetTurnServerTask : Task {
-    object Params
-}
+internal abstract class GetTurnServerTask : Task
 
-internal class DefaultGetTurnServerTask @Inject constructor(private val voipAPI: VoipApi,
-                                                            private val globalErrorReceiver: GlobalErrorReceiver) : GetTurnServerTask() {
+internal class DefaultGetTurnServerTask @Inject constructor(
+        private val voipApi: VoipApi,
+        private val globalErrorReceiver: GlobalErrorReceiver
+) : GetTurnServerTask() {
 
-    override suspend fun execute(params: Params): TurnServerResponse {
+    override suspend fun execute(params: Unit): TurnServerResponse {
         return executeRequest(globalErrorReceiver) {
-            voipAPI.getTurnServer()
+            voipApi.getTurnServer()
         }
     }
 }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/TurnServerDataSource.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/TurnServerDataSource.kt
index 8e2ac5e17e..126a581fa4 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/TurnServerDataSource.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/call/TurnServerDataSource.kt
@@ -39,7 +39,7 @@ internal class TurnServerDataSource @Inject constructor(private val turnServerTa
     }
 
     suspend fun getTurnServer(): TurnServerResponse {
-        return cachedTurnServerResponse.data ?: turnServerTask.execute(GetTurnServerTask.Params).also {
+        return cachedTurnServerResponse.data ?: turnServerTask.execute(Unit).also {
             cachedTurnServerResponse.data = it
         }
     }
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageExifTagRemover.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageExifTagRemover.kt
index 239a768498..3fa9ffb0e1 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageExifTagRemover.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/ImageExifTagRemover.kt
@@ -31,9 +31,8 @@ import java.io.FileOutputStream
 import javax.inject.Inject
 
 /**
- * This class is responsible for removing Exif tags from image files
+ * This class is responsible for removing Exif tags from image files.
  */
-
 internal class ImageExifTagRemover @Inject constructor(
         private val temporaryFileCreator: TemporaryFileCreator,
         private val coroutineDispatchers: MatrixCoroutineDispatchers
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt
index d3de807b23..5a00c4b5b4 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/content/UploadContentWorker.kt
@@ -62,8 +62,8 @@ private data class NewAttachmentAttributes(
 )
 
 /**
- * Possible previous worker: None
- * Possible next worker    : Always [MultipleEventSendingDispatcherWorker]
+ * Possible previous worker: None.
+ * Possible next worker    : Always [MultipleEventSendingDispatcherWorker].
  */
 internal class UploadContentWorker(val context: Context, params: WorkerParameters, sessionManager: SessionManager) :
         SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) {
@@ -318,7 +318,7 @@ internal class UploadContentWorker(val context: Context, params: WorkerParameter
     )
 
     /**
-     * If appropriate, it will create and upload a thumbnail
+     * If appropriate, it will create and upload a thumbnail.
      */
     private suspend fun dealWithThumbnail(params: Params): UploadThumbnailResult? {
         return thumbnailExtractor.extractThumbnail(params.attachment)
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerRealmModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerRealmModule.kt
index 85c1947a80..1872bb72a9 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerRealmModule.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/db/ContentScannerRealmModule.kt
@@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.session.contentscanner.db
 import io.realm.annotations.RealmModule
 
 /**
- * Realm module for content scanner classes
+ * Realm module for content scanner classes.
  */
 @RealmModule(
         library = true,
diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/model/ScanResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/model/ScanResponse.kt
index f783fe0a6c..85d7f2e094 100644
--- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/model/ScanResponse.kt
+++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/contentscanner/model/ScanResponse.kt
@@ -20,10 +20,14 @@ import com.squareup.moshi.Json
 import com.squareup.moshi.JsonClass
 
 /**
+ * Example:
+ * 
  * {
  *      "clean": true,
  *      "info": "File clean at 6/7/2018, 6:02:40 PM"
  *  }
+ * 
+ * . */ @JsonClass(generateAdapter = true) internal data class ScanResponse( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt index 16c57baafc..19b9130fc4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/directory/DirectoryAPI.kt @@ -61,7 +61,7 @@ internal interface DirectoryAPI { @Body body: AddRoomAliasBody) /** - * Delete a room alias + * Delete a room alias. * @param roomAlias the room alias. */ @DELETE(NetworkConstants.URI_API_PREFIX_PATH_R0 + "directory/room/{roomAlias}") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt index 2809dea23b..dab801360f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterApi.kt @@ -25,7 +25,7 @@ import retrofit2.http.Path internal interface FilterApi { /** - * Upload FilterBody to get a filter_id which can be used for /sync requests + * Upload FilterBody to get a filter_id which can be used for /sync requests. * * @param userId the user id * @param body the Json representation of a FilterBody object @@ -35,7 +35,7 @@ internal interface FilterApi { @Body body: Filter): FilterResponse /** - * Gets a filter with a given filterId from the homeserver + * Gets a filter with a given filterId from the homeserver. * * @param userId the user id * @param filterId the filterID diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterRepository.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterRepository.kt index df61539547..f40231c8cf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterRepository.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterRepository.kt @@ -19,22 +19,22 @@ package org.matrix.android.sdk.internal.session.filter internal interface FilterRepository { /** - * Return true if the filterBody has changed, or need to be sent to the server + * Return true if the filterBody has changed, or need to be sent to the server. */ suspend fun storeFilter(filter: Filter, roomEventFilter: RoomEventFilter): Boolean /** - * Set the filterId of this filter + * Set the filterId of this filter. */ suspend fun storeFilterId(filter: Filter, filterId: String) /** - * Return filter json or filter id + * Return filter json or filter id. */ suspend fun getFilter(): String /** - * Return the room filter + * Return the room filter. */ suspend fun getRoomFilter(): String } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterUtil.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterUtil.kt index bd7f0ad402..562fea88b6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterUtil.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/FilterUtil.kt @@ -81,8 +81,7 @@ internal object FilterUtil { } */ /** - * Compute a new filter to enable or disable the lazy loading - * + * Compute a new filter to enable or disable the lazy loading. * * If lazy loading is on, the filter will looks like * {"room":{"state":{"lazy_load_members":true})} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/RoomFilter.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/RoomFilter.kt index 585d013eae..72b1af52b8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/RoomFilter.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/RoomFilter.kt @@ -40,7 +40,7 @@ internal data class RoomFilter( */ @Json(name = "ephemeral") val ephemeral: RoomEventFilter? = null, /** - * Include rooms that the user has left in the sync, default false + * Include rooms that the user has left in the sync, default false. */ @Json(name = "include_leave") val includeLeave: Boolean? = null, /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt index 3cac89ce28..e9d5b876a8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/filter/SaveFilterTask.kt @@ -24,7 +24,7 @@ import org.matrix.android.sdk.internal.task.Task import javax.inject.Inject /** - * Save a filter, in db and if any changes, upload to the server + * Save a filter, in db and if any changes, upload to the server. */ internal interface SaveFilterTask : Task { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataWorker.kt index 716859f195..21582cb4be 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GetGroupDataWorker.kt @@ -26,8 +26,8 @@ import org.matrix.android.sdk.internal.worker.SessionWorkerParams import javax.inject.Inject /** - * Possible previous worker: None - * Possible next worker : None + * Possible previous worker: None. + * Possible next worker : None. */ internal class GetGroupDataWorker(context: Context, params: WorkerParameters, sessionManager: SessionManager) : SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GroupAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GroupAPI.kt index 58dcc57dd6..c9d25b9104 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GroupAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/GroupAPI.kt @@ -26,7 +26,7 @@ import retrofit2.http.Path internal interface GroupAPI { /** - * Request a group summary + * Request a group summary. * * @param groupId the group id */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryRoomsSection.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryRoomsSection.kt index 8f9b29ed0a..87d07167ce 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryRoomsSection.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryRoomsSection.kt @@ -29,6 +29,6 @@ internal data class GroupSummaryRoomsSection( @Json(name = "rooms") val rooms: List = emptyList() - // @TODO: Check the meaning and the usage of these categories. This dictionary is empty FTM. + // TODO Check the meaning and the usage of these categories. This dictionary is empty FTM. // public Map categories; ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryUsersSection.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryUsersSection.kt index 799aa8a5b1..63608c582a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryUsersSection.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/group/model/GroupSummaryUsersSection.kt @@ -30,6 +30,6 @@ internal data class GroupSummaryUsersSection( @Json(name = "users") val users: List = emptyList() - // @TODO: Check the meaning and the usage of these roles. This dictionary is empty FTM. + // TODO Check the meaning and the usage of these roles. This dictionary is empty FTM. // public Map roles; ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/CapabilitiesAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/CapabilitiesAPI.kt index 7de0cc9592..f658cda973 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/CapabilitiesAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/CapabilitiesAPI.kt @@ -22,19 +22,19 @@ import retrofit2.http.GET internal interface CapabilitiesAPI { /** - * Request the homeserver capabilities + * Request the homeserver capabilities. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "capabilities") suspend fun getCapabilities(): GetCapabilitiesResult /** - * Request the versions + * Request the versions. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_ + "versions") suspend fun getVersions(): Versions /** - * Ping the homeserver. We do not care about the returned data, so there is no use to parse them + * Ping the homeserver. We do not care about the returned data, so there is no use to parse them. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_ + "versions") suspend fun ping() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetCapabilitiesResult.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetCapabilitiesResult.kt index 55526b41db..95ff44807c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetCapabilitiesResult.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetCapabilitiesResult.kt @@ -67,8 +67,8 @@ internal data class Capabilities( @Json(name = "m.room_versions") val roomVersions: RoomVersions? = null, /** - * Capability to indicate if the server supports MSC3440 Threading - * True if the user can use m.thread relation, false otherwise + * Capability to indicate if the server supports MSC3440 Threading. + * True if the user can use m.thread relation, false otherwise. */ @Json(name = "m.thread") val threads: BooleanCapability? = null @@ -98,6 +98,8 @@ internal data class RoomVersions( val available: JsonDict? = null, /** + * Example: + *
          *  "room_capabilities": {
          *      "knock" : {
          *              "preferred": "7",
@@ -108,6 +110,7 @@ internal data class RoomVersions(
          *              "support" : ["8", "9"]
          *      }
          * }
+         * 
. */ @Json(name = "org.matrix.msc3244.room_capabilities") val roomCapabilities: JsonDict? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt index e9097e4d03..b1a518724c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/homeserver/GetHomeServerCapabilitiesTask.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.session.homeserver import com.zhuinden.monarchy.Monarchy -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.wellknown.WellknownResult import org.matrix.android.sdk.api.extensions.orFalse @@ -93,10 +93,14 @@ internal class DefaultGetHomeServerCapabilitiesTask @Inject constructor( } }.getOrNull() + // Domain may include a port (eg, matrix.org:8080) + // Per https://spec.matrix.org/latest/client-server-api/#well-known-uri we should extract the hostname from the server name + // So we take everything before the last : as the domain for the well-known task. + // NB: This is not always the same endpoint as capabilities / mediaConfig uses. val wellknownResult = runCatching { getWellknownTask.execute( GetWellknownTask.Params( - domain = userId.getDomain(), + domain = userId.getServerName().substringBeforeLast(":"), homeServerConnectionConfig = homeServerConnectionConfig ) ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt index 7ca8758677..aef86ed08e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAPI.kt @@ -34,8 +34,8 @@ import retrofit2.http.Path import retrofit2.http.Query /** - * Ref: https://matrix.org/docs/spec/identity_service/latest - * This contain the requests which need an identity server token + * Ref: https://matrix.org/docs/spec/identity_service/latest. + * This contain the requests which need an identity server token. */ internal interface IdentityAPI { /** @@ -69,8 +69,8 @@ internal interface IdentityAPI { suspend fun lookup(@Body body: IdentityLookUpParams): IdentityLookUpResponse /** - * Create a session to change the bind status of an email to an identity server - * The identity server will also send an email + * Create a session to change the bind status of an email to an identity server. + * The identity server will also send an email. * * @param body * @return the sid @@ -79,8 +79,8 @@ internal interface IdentityAPI { suspend fun requestTokenToBindEmail(@Body body: IdentityRequestTokenForEmailBody): IdentityRequestTokenResponse /** - * Create a session to change the bind status of an phone number to an identity server - * The identity server will also send an SMS on the ThreePid provided + * Create a session to change the bind status of an phone number to an identity server. + * The identity server will also send an SMS on the ThreePid provided. * * @param body * @return the sid @@ -99,9 +99,9 @@ internal interface IdentityAPI { @Body body: IdentityRequestOwnershipParams): SuccessResult /** - * https://matrix.org/docs/spec/identity_service/r0.3.0#post-matrix-identity-v2-sign-ed25519 + * https://matrix.org/docs/spec/identity_service/r0.3.0#post-matrix-identity-v2-sign-ed25519. * - * Have to rely on V1 for now + * Have to rely on V1 for now. */ @POST(NetworkConstants.URI_IDENTITY_PATH_V1 + "sign-ed25519") suspend fun signInvitationDetails( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAuthAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAuthAPI.kt index f77eb296aa..85791f59a3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAuthAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/IdentityAuthAPI.kt @@ -24,14 +24,14 @@ import retrofit2.http.GET import retrofit2.http.POST /** - * Ref: https://matrix.org/docs/spec/identity_service/latest - * This contain the requests which do not need an identity server token + * Ref: https://matrix.org/docs/spec/identity_service/latest. + * This contain the requests which do not need an identity server token. */ internal interface IdentityAuthAPI { /** - * https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery - * Simple ping call to check if server exists and is alive + * https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery. + * Simple ping call to check if server exists and is alive. * * Ref: https://matrix.org/docs/spec/identity_service/unstable#status-check * https://matrix.org/docs/spec/identity_service/latest#get-matrix-identity-v2 @@ -42,7 +42,7 @@ internal interface IdentityAuthAPI { suspend fun ping() /** - * Ping v1 will be used to check outdated identity server + * Ping v1 will be used to check outdated identity server. */ @GET("_matrix/identity/api/v1") suspend fun pingV1() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/data/IdentityStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/data/IdentityStore.kt index 0e05224be5..51d4ed7c6d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/data/IdentityStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/data/IdentityStore.kt @@ -32,7 +32,7 @@ internal interface IdentityStore { fun setHashDetails(hashDetailResponse: IdentityHashDetailResponse) /** - * Store details about a current binding + * Store details about a current binding. */ fun storePendingBinding(threePid: ThreePid, data: IdentityPendingBinding) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt index 5152e33743..aecf21678c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityDataEntityQuery.kt @@ -22,7 +22,7 @@ import io.realm.kotlin.createObject import io.realm.kotlin.where /** - * Only one object can be stored at a time + * Only one object can be stored at a time. */ internal fun IdentityDataEntity.Companion.get(realm: Realm): IdentityDataEntity? { return realm.where().findFirst() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityRealmModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityRealmModule.kt index 5e9068ecf7..a5ec6061ba 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityRealmModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/IdentityRealmModule.kt @@ -19,7 +19,7 @@ package org.matrix.android.sdk.internal.session.identity.db import io.realm.annotations.RealmModule /** - * Realm module for identity server classes + * Realm module for identity server classes. */ @RealmModule( library = true, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/RealmIdentityStoreMigration.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/RealmIdentityStoreMigration.kt index 0c279d8a7e..e731f9f347 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/RealmIdentityStoreMigration.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/db/RealmIdentityStoreMigration.kt @@ -24,8 +24,8 @@ import javax.inject.Inject internal class RealmIdentityStoreMigration @Inject constructor() : RealmMigration { /** - * Forces all RealmIdentityStoreMigration instances to be equal - * Avoids Realm throwing when multiple instances of the migration are set + * Forces all RealmIdentityStoreMigration instances to be equal. + * Avoids Realm throwing when multiple instances of the migration are set. */ override fun equals(other: Any?) = other is RealmIdentityStoreMigration override fun hashCode() = 3000 diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/model/SignInvitationBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/model/SignInvitationBody.kt index 6998257263..465d296e94 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/model/SignInvitationBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/identity/model/SignInvitationBody.kt @@ -16,14 +16,16 @@ package org.matrix.android.sdk.internal.session.identity.model +import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) internal data class SignInvitationBody( - /**The Matrix user ID of the user accepting the invitation.*/ + /** The Matrix user ID of the user accepting the invitation.*/ val mxid: String, - /**The token from the call to store- invite..*/ + /** The token from the call to store- invite..*/ val token: String, /** The private key, encoded as Unpadded base64. */ - val private_key: String + @Json(name = "private_key") + val privateKey: String ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/DefaultSyncStatusService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/DefaultSyncStatusService.kt index c138c1a40e..2aa0be80c9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/DefaultSyncStatusService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/DefaultSyncStatusService.kt @@ -41,7 +41,7 @@ internal class DefaultSyncStatusService @Inject constructor() : } /** - * Create a rootTask + * Create a rootTask. */ fun startRoot(initSyncStep: InitSyncStep, totalProgress: Int) { @@ -51,7 +51,7 @@ internal class DefaultSyncStatusService @Inject constructor() : } /** - * Add a child to the leaf + * Add a child to the leaf. */ override fun startTask(initSyncStep: InitSyncStep, totalProgress: Int, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/TaskInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/TaskInfo.kt index 3e4cce2e1f..fef16bf1d7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/TaskInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/initsync/TaskInfo.kt @@ -29,7 +29,7 @@ internal class TaskInfo(val initSyncStep: InitSyncStep, private val offset = parent?.currentProgress ?: 0F /** - * Get the further child + * Get the further child. */ fun leaf(): TaskInfo { var last = this @@ -40,7 +40,7 @@ internal class TaskInfo(val initSyncStep: InitSyncStep, } /** - * Set progress of this task and update the parent progress iteratively + * Set progress of this task and update the parent progress iteratively. */ fun setProgress(progress: Float) { Timber.v("setProgress: $progress / $totalProgress") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/AllowedWidgetsContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/AllowedWidgetsContent.kt index 8d0e8c930d..ebf14c602c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/AllowedWidgetsContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/AllowedWidgetsContent.kt @@ -22,18 +22,20 @@ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) internal data class AllowedWidgetsContent( /** - * Map of stateEventId to Allowed + * Map of stateEventId to Allowed. */ @Json(name = "widgets") val widgets: Map = emptyMap(), /** - * Map of native widgetType to a map of domain to Allowed + * Map of native widgetType to a map of domain to Allowed. + *
          * {
          *      "jitsi" : {
          *            "jitsi.domain.org"  : true,
          *            "jitsi.other.org"  : false
          *      }
          * }
+         * 
*/ @Json(name = "native_widgets") val native: Map> = emptyMap() ) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt index 1b96931c6c..8034e5b974 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/integrationmanager/IntegrationManager.kt @@ -124,7 +124,7 @@ internal class IntegrationManager @Inject constructor(matrixConfiguration: Matri } /** - * Returns false if the user as disabled integration manager feature + * Returns false if the user as disabled integration manager feature. */ fun isIntegrationEnabled(): Boolean { val integrationProvisioningData = accountDataDataSource.getAccountDataEvent(UserAccountDataTypes.TYPE_INTEGRATION_PROVISIONING) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/PreviewUrlMapper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/PreviewUrlMapper.kt index 551dc29b92..06fbf802ae 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/PreviewUrlMapper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/media/PreviewUrlMapper.kt @@ -20,7 +20,7 @@ import org.matrix.android.sdk.api.session.media.PreviewUrlData import org.matrix.android.sdk.internal.database.model.PreviewUrlCacheEntity /** - * PreviewUrlCacheEntity -> PreviewUrlData + * PreviewUrlCacheEntity -> PreviewUrlData. */ internal fun PreviewUrlCacheEntity.toDomain() = PreviewUrlData( url = urlFromServer ?: url, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt index 0aeb0467de..f9da7b66f6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/PermalinkFactory.kt @@ -126,7 +126,7 @@ internal class PermalinkFactory @Inject constructor( } /** - * Escape '/' in id, because it is used as a separator + * Escape '/' in id, because it is used as a separator. * * @param id the id to escape * @return the escaped id @@ -136,7 +136,7 @@ internal class PermalinkFactory @Inject constructor( } /** - * Unescape '/' in id + * Unescape '/' in id. * * @param id the id to escape * @return the escaped id diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/ViaParameterFinder.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/ViaParameterFinder.kt index d20cf8f140..edc45fe945 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/ViaParameterFinder.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/permalinks/ViaParameterFinder.kt @@ -16,7 +16,7 @@ package org.matrix.android.sdk.internal.session.permalinks -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.toModel @@ -55,9 +55,9 @@ internal class ViaParameterFinder @Inject constructor( } fun computeViaParams(userId: String, roomId: String, max: Int): List { - val userHomeserver = userId.getDomain() + val userHomeserver = userId.getServerName() return getUserIdsOfJoinedMembers(roomId) - .map { it.getDomain() } + .map { it.getServerName() } .groupBy { it } .mapValues { it.value.size } .toMutableMap() @@ -68,7 +68,7 @@ internal class ViaParameterFinder @Inject constructor( } /** - * Get a set of userIds of joined members of a room + * Get a set of userIds of joined members of a room. */ private fun getUserIdsOfJoinedMembers(roomId: String): Set { return roomGetterProvider.get().getRoom(roomId) @@ -92,7 +92,7 @@ internal class ViaParameterFinder @Inject constructor( .orEmpty() .toSet() - return userThatCanInvite.map { it.getDomain() } + return userThatCanInvite.map { it.getServerName() } .groupBy { it } .mapValues { it.value.size } .toMutableMap() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/model/PresenceContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/model/PresenceContent.kt index b1ca512652..abad91bad2 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/model/PresenceContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/presence/model/PresenceContent.kt @@ -21,7 +21,7 @@ import com.squareup.moshi.JsonClass import org.matrix.android.sdk.api.session.presence.model.PresenceEnum /** - * Class representing the EventType.PRESENCE event content + * Class representing the EventType.PRESENCE event content. */ @JsonClass(generateAdapter = true) internal data class PresenceContent( @@ -38,7 +38,7 @@ internal data class PresenceContent( */ @Json(name = "status_msg") val statusMessage: String? = null, /** - * Whether the user is currently active + * Whether the user is currently active. */ @Json(name = "currently_active") val isCurrentlyActive: Boolean = false, /** diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AccountThreePidsResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AccountThreePidsResponse.kt index 0a792397f8..6d2b3c480d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AccountThreePidsResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/AccountThreePidsResponse.kt @@ -19,7 +19,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing the ThreePids response + * Class representing the ThreePids response. */ @JsonClass(generateAdapter = true) internal data class AccountThreePidsResponse( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/ProfileAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/ProfileAPI.kt index 4b56db9f13..4d4506be76 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/ProfileAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/profile/ProfileAPI.kt @@ -46,7 +46,7 @@ internal interface ProfileAPI { suspend fun getThreePIDs(): AccountThreePidsResponse /** - * Change user display name + * Change user display name. */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "profile/{userId}/displayname") suspend fun setDisplayName(@Path("userId") userId: String, @@ -86,7 +86,7 @@ internal interface ProfileAPI { suspend fun addMsisdn(@Body body: AddMsisdnBody): AddMsisdnResponse /** - * Validate Msisdn code (same model than for identity server API) + * Validate Msisdn code (same model than for identity server API). */ @POST suspend fun validateMsisdn(@Url url: String, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesResponse.kt index de03819629..5f35c919fc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesResponse.kt @@ -26,13 +26,13 @@ import org.matrix.android.sdk.api.session.pushrules.rest.RuleSet @JsonClass(generateAdapter = true) internal data class GetPushRulesResponse( /** - * Global rules, account level applying to all devices + * Global rules, account level applying to all devices. */ @Json(name = "global") val global: RuleSet, /** - * Device specific rules, apply only to current device + * Device specific rules, apply only to current device. */ @Json(name = "device") val device: RuleSet? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesTask.kt index 8cf861d285..8e7078292b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/GetPushRulesTask.kt @@ -25,7 +25,7 @@ internal interface GetPushRulesTask : Task { } /** - * We keep this task, but it should not be used anymore, the push rules comes from the sync response + * We keep this task, but it should not be used anymore, the push rules comes from the sync response. */ internal class DefaultGetPushRulesTask @Inject constructor( private val pushRulesApi: PushRulesApi, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/JsonPusher.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/JsonPusher.kt index 8dc0954694..71a1ea8c66 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/JsonPusher.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/JsonPusher.kt @@ -22,7 +22,6 @@ import java.security.InvalidParameterException /** * Example: - * * * { * "pushers": [ @@ -40,6 +39,7 @@ import java.security.InvalidParameterException * }] * } * + * . */ @JsonClass(generateAdapter = true) internal data class JsonPusher( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt index dab6d37317..40b4ee269a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/PushRulesApi.kt @@ -25,13 +25,13 @@ import retrofit2.http.Path internal interface PushRulesApi { /** - * Get all push rules + * Get all push rules. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "pushrules/") suspend fun getAllRules(): GetPushRulesResponse /** - * Update the ruleID enable status + * Update the ruleID enable status. * * @param kind the notification kind (sender, room...) * @param ruleId the ruleId @@ -43,7 +43,7 @@ internal interface PushRulesApi { @Body enabledBody: EnabledBody) /** - * Update the ruleID action + * Update the ruleID action. * Ref: https://matrix.org/docs/spec/client_server/latest#put-matrix-client-r0-pushrules-scope-kind-ruleid-actions * * @param kind the notification kind (sender, room...) @@ -56,7 +56,7 @@ internal interface PushRulesApi { @Body actions: Any) /** - * Delete a rule + * Delete a rule. * * @param kind the notification kind (sender, room...) * @param ruleId the ruleId @@ -66,7 +66,7 @@ internal interface PushRulesApi { @Path("ruleId") ruleId: String) /** - * Add the ruleID enable status + * Add the ruleID enable status. * * @param kind the notification kind (sender, room...) * @param ruleId the ruleId. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/SavePushRulesTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/SavePushRulesTask.kt index ff685e9281..88c78aa460 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/SavePushRulesTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/pushers/SavePushRulesTask.kt @@ -27,7 +27,7 @@ import org.matrix.android.sdk.internal.util.awaitTransaction import javax.inject.Inject /** - * Save the push rules in DB + * Save the push rules in DB. */ internal interface SavePushRulesTask : Task { data class Params(val pushRules: GetPushRulesResponse) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt index 4945c69c20..5d2a1477fc 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/EventRelationsAggregationProcessor.kt @@ -188,9 +188,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( } } in EventType.BEACON_LOCATION_DATA -> { - event.getClearContent().toModel(catchError = true)?.let { - liveLocationAggregationProcessor.handleBeaconLocationData(realm, event, it, roomId, isLocalEcho) - } + handleBeaconLocationData(event, realm, roomId, isLocalEcho) } } } else if (encryptedEventContent?.relatesTo?.type == RelationType.ANNOTATION) { @@ -259,6 +257,9 @@ internal class EventRelationsAggregationProcessor @Inject constructor( liveLocationAggregationProcessor.handleBeaconInfo(realm, event, it, roomId, isLocalEcho) } } + in EventType.BEACON_LOCATION_DATA -> { + handleBeaconLocationData(event, realm, roomId, isLocalEcho) + } else -> Timber.v("UnHandled event ${event.eventId}") } } catch (t: Throwable) { @@ -359,7 +360,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( } /** - * Check if the edition is on the latest thread event, and update it accordingly + * Check if the edition is on the latest thread event, and update it accordingly. * @param editedEvent The event that will be changed * @param replaceEvent The new event */ @@ -475,7 +476,7 @@ internal class EventRelationsAggregationProcessor @Inject constructor( } /** - * Called when an event is deleted + * Called when an event is deleted. */ private fun handleRedactionOfReplace(realm: Realm, redacted: EventEntity, @@ -580,4 +581,17 @@ internal class EventRelationsAggregationProcessor @Inject constructor( verifSummary.sourceEvents.add(event.eventId) } } + + private fun handleBeaconLocationData(event: Event, realm: Realm, roomId: String, isLocalEcho: Boolean) { + event.getClearContent().toModel(catchError = true)?.let { + liveLocationAggregationProcessor.handleBeaconLocationData( + realm, + event, + it, + roomId, + event.getRelationContent()?.eventId, + isLocalEcho + ) + } + } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt index 65ef94999f..72f56ddf68 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAPI.kt @@ -92,7 +92,7 @@ internal interface RoomAPI { ): PaginationResponse /** - * Get all members of a room + * Get all members of a room. * * @param roomId the room id where to get the members * @param syncToken the sync token (optional) @@ -136,7 +136,7 @@ internal interface RoomAPI { @Query("filter") filter: String? = null): EventContextResponse /** - * Retrieve an event from its room id / events id + * Retrieve an event from its room id / events id. * * @param roomId the room id * @param eventId the event Id @@ -156,7 +156,7 @@ internal interface RoomAPI { @Body markers: Map) /** - * Send receipt to a room + * Send receipt to a room. */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/receipt/{receiptType}/{eventId}") suspend fun sendReceipt(@Path("roomId") roomId: String, @@ -185,7 +185,7 @@ internal interface RoomAPI { @Body body: ThreePidInviteBody) /** - * Send a generic state event + * Send a generic state event. * * @param roomId the room id. * @param stateEventType the state event type @@ -198,7 +198,7 @@ internal interface RoomAPI { ): SendResponse /** - * Send a generic state event + * Send a generic state event. * * @param roomId the room id. * @param stateEventType the state event type @@ -220,7 +220,7 @@ internal interface RoomAPI { suspend fun getRoomState(@Path("roomId") roomId: String): List /** - * Paginate relations for event based in normal topological order + * Paginate relations for event based in normal topological order. * @param relationType filter for this relation type * @param eventType filter for this event type */ @@ -235,7 +235,7 @@ internal interface RoomAPI { ): RelationsResponse /** - * Paginate relations for thread events based in normal topological order + * Paginate relations for thread events based in normal topological order. * @param relationType filter for this relation type */ @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "rooms/{roomId}/relations/{eventId}/{relationType}") @@ -337,14 +337,14 @@ internal interface RoomAPI { suspend fun getAliases(@Path("roomId") roomId: String): GetAliasesResponse /** - * Inform that the user is starting to type or has stopped typing + * Inform that the user is starting to type or has stopped typing. */ @PUT(NetworkConstants.URI_API_PREFIX_PATH_R0 + "rooms/{roomId}/typing/{userId}") suspend fun sendTypingState(@Path("roomId") roomId: String, @Path("userId") userId: String, @Body body: TypingBody) - /** + /* * Room tagging */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAvatarResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAvatarResolver.kt index 60ad83ee05..29a303475b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAvatarResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomAvatarResolver.kt @@ -34,7 +34,7 @@ import javax.inject.Inject internal class RoomAvatarResolver @Inject constructor(@UserId private val userId: String) { /** - * Compute the room avatar url + * Compute the room avatar url. * @param realm: the current instance of realm * @param roomId the roomId of the room to resolve avatar * @return the room avatar url, can be a fallback to a room member avatar or null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt index 5e90076b8a..f3845f1f15 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/RoomModule.kt @@ -108,14 +108,14 @@ import retrofit2.Retrofit import javax.inject.Qualifier /** - * Used to inject the simple commonmark Parser + * Used to inject the simple commonmark Parser. */ @Qualifier @Retention(AnnotationRetention.RUNTIME) internal annotation class SimpleCommonmarkParser /** - * Used to inject the advanced commonmark Parser + * Used to inject the advanced commonmark Parser. */ @Qualifier @Retention(AnnotationRetention.RUNTIME) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/DefaultLiveLocationAggregationProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/DefaultLiveLocationAggregationProcessor.kt deleted file mode 100644 index 997e31a109..0000000000 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/DefaultLiveLocationAggregationProcessor.kt +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2022 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.android.sdk.internal.session.room.aggregation.livelocation - -import io.realm.Realm -import org.matrix.android.sdk.api.extensions.orTrue -import org.matrix.android.sdk.api.session.events.model.Event -import org.matrix.android.sdk.api.session.events.model.toContent -import org.matrix.android.sdk.api.session.events.model.toModel -import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconInfoContent -import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconLocationDataContent -import org.matrix.android.sdk.internal.database.mapper.ContentMapper -import org.matrix.android.sdk.internal.database.model.livelocation.LiveLocationShareAggregatedSummaryEntity -import org.matrix.android.sdk.internal.database.query.getOrCreate -import timber.log.Timber -import javax.inject.Inject - -internal class DefaultLiveLocationAggregationProcessor @Inject constructor() : LiveLocationAggregationProcessor { - - override fun handleBeaconInfo(realm: Realm, event: Event, content: MessageBeaconInfoContent, roomId: String, isLocalEcho: Boolean) { - if (event.senderId.isNullOrEmpty() || isLocalEcho) { - return - } - - val targetEventId = if (content.isLive.orTrue()) { - event.eventId - } else { - // when live is set to false, we use the id of the event that should have been replaced - event.unsignedData?.replacesState - } - - if (targetEventId.isNullOrEmpty()) { - Timber.w("no target event id found for the beacon content") - return - } - - val aggregatedSummary = LiveLocationShareAggregatedSummaryEntity.getOrCreate( - realm = realm, - roomId = roomId, - eventId = targetEventId - ) - - Timber.d("updating summary of id=$targetEventId with isLive=${content.isLive}") - - aggregatedSummary.endOfLiveTimestampMillis = content.getBestTimestampMillis()?.let { it + (content.timeout ?: 0) } - aggregatedSummary.isActive = content.isLive - } - - override fun handleBeaconLocationData(realm: Realm, event: Event, content: MessageBeaconLocationDataContent, roomId: String, isLocalEcho: Boolean) { - if (event.senderId.isNullOrEmpty() || isLocalEcho) { - return - } - - val targetEventId = content.relatesTo?.eventId - - if (targetEventId.isNullOrEmpty()) { - Timber.w("no target event id found for the live location content") - return - } - - val aggregatedSummary = LiveLocationShareAggregatedSummaryEntity.getOrCreate( - realm = realm, - roomId = roomId, - eventId = targetEventId - ) - val updatedLocationTimestamp = content.getBestTimestampMillis() ?: 0 - val currentLocationTimestamp = ContentMapper - .map(aggregatedSummary.lastLocationContent) - .toModel() - ?.getBestTimestampMillis() - ?: 0 - - if (updatedLocationTimestamp.isMoreRecentThan(currentLocationTimestamp)) { - Timber.d("updating last location of the summary of id=$targetEventId") - aggregatedSummary.lastLocationContent = ContentMapper.map(content.toContent()) - } - } - - private fun Long.isMoreRecentThan(timestamp: Long) = this > timestamp -} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt index c0be96f83d..76b7a4ec8e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/aggregation/livelocation/LiveLocationAggregationProcessor.kt @@ -17,24 +17,83 @@ package org.matrix.android.sdk.internal.session.room.aggregation.livelocation import io.realm.Realm +import org.matrix.android.sdk.api.extensions.orTrue import org.matrix.android.sdk.api.session.events.model.Event +import org.matrix.android.sdk.api.session.events.model.toContent +import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconInfoContent import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconLocationDataContent +import org.matrix.android.sdk.internal.database.mapper.ContentMapper +import org.matrix.android.sdk.internal.database.model.livelocation.LiveLocationShareAggregatedSummaryEntity +import org.matrix.android.sdk.internal.database.query.getOrCreate +import timber.log.Timber +import javax.inject.Inject -internal interface LiveLocationAggregationProcessor { - fun handleBeaconInfo( - realm: Realm, - event: Event, - content: MessageBeaconInfoContent, - roomId: String, - isLocalEcho: Boolean, - ) +internal class LiveLocationAggregationProcessor @Inject constructor() { + + fun handleBeaconInfo(realm: Realm, event: Event, content: MessageBeaconInfoContent, roomId: String, isLocalEcho: Boolean) { + if (event.senderId.isNullOrEmpty() || isLocalEcho) { + return + } + + val targetEventId = if (content.isLive.orTrue()) { + event.eventId + } else { + // when live is set to false, we use the id of the event that should have been replaced + event.unsignedData?.replacesState + } + + if (targetEventId.isNullOrEmpty()) { + Timber.w("no target event id found for the beacon content") + return + } + + val aggregatedSummary = LiveLocationShareAggregatedSummaryEntity.getOrCreate( + realm = realm, + roomId = roomId, + eventId = targetEventId + ) + + Timber.d("updating summary of id=$targetEventId with isLive=${content.isLive}") + + aggregatedSummary.endOfLiveTimestampMillis = content.getBestTimestampMillis()?.let { it + (content.timeout ?: 0) } + aggregatedSummary.isActive = content.isLive + } fun handleBeaconLocationData( realm: Realm, event: Event, content: MessageBeaconLocationDataContent, roomId: String, - isLocalEcho: Boolean, - ) + relatedEventId: String?, + isLocalEcho: Boolean + ) { + if (event.senderId.isNullOrEmpty() || isLocalEcho) { + return + } + + if (relatedEventId.isNullOrEmpty()) { + Timber.w("no related event id found for the live location content") + return + } + + val aggregatedSummary = LiveLocationShareAggregatedSummaryEntity.getOrCreate( + realm = realm, + roomId = roomId, + eventId = relatedEventId + ) + val updatedLocationTimestamp = content.getBestTimestampMillis() ?: 0 + val currentLocationTimestamp = ContentMapper + .map(aggregatedSummary.lastLocationContent) + .toModel() + ?.getBestTimestampMillis() + ?: 0 + + if (updatedLocationTimestamp.isMoreRecentThan(currentLocationTimestamp)) { + Timber.d("updating last location of the summary of id=$relatedEventId") + aggregatedSummary.lastLocationContent = ContentMapper.map(content.toContent()) + } + } + + private fun Long.isMoreRecentThan(timestamp: Long) = this > timestamp } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/RoomAliasAvailabilityChecker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/RoomAliasAvailabilityChecker.kt index 7c137a8102..fa19b4f9cf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/RoomAliasAvailabilityChecker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/alias/RoomAliasAvailabilityChecker.kt @@ -16,7 +16,7 @@ package org.matrix.android.sdk.internal.session.room.alias -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.failure.Failure import org.matrix.android.sdk.api.session.room.alias.RoomAliasError import org.matrix.android.sdk.internal.di.UserId @@ -65,6 +65,6 @@ internal class RoomAliasAvailabilityChecker @Inject constructor( } companion object { - internal fun String.toFullLocalAlias(userId: String) = "#" + this + ":" + userId.getDomain() + internal fun String.toFullLocalAlias(userId: String) = "#" + this + ":" + userId.getServerName() } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt index 69352688e3..cffa632768 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/create/CreateRoomBody.kt @@ -25,7 +25,7 @@ import org.matrix.android.sdk.api.session.room.model.create.CreateRoomPreset import org.matrix.android.sdk.internal.session.room.membership.threepid.ThreePidInviteBody /** - * Parameter to create a room + * Parameter to create a room. */ @JsonClass(generateAdapter = true) internal data class CreateRoomBody( @@ -108,7 +108,7 @@ internal data class CreateRoomBody( val isDirect: Boolean?, /** - * The power level content to override in the default power level event + * The power level content to override in the default power level event. */ @Json(name = "power_level_content_override") val powerLevelContentOverride: PowerLevelsContent?, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt index bd9f2ecc36..59e0f81ece 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomDisplayNameResolver.kt @@ -38,7 +38,7 @@ import org.matrix.android.sdk.internal.util.Normalizer import javax.inject.Inject /** - * This class computes room display name + * This class computes room display name. */ internal class RoomDisplayNameResolver @Inject constructor( matrixConfiguration: MatrixConfiguration, @@ -50,7 +50,7 @@ internal class RoomDisplayNameResolver @Inject constructor( private val roomDisplayNameFallbackProvider = matrixConfiguration.roomDisplayNameFallbackProvider /** - * Compute the room display name + * Compute the room display name. * * @param realm: the current instance of realm * @param roomId: the roomId to resolve the name of. @@ -157,7 +157,7 @@ internal class RoomDisplayNameResolver @Inject constructor( return (name ?: roomId).toRoomName() } - /** See [org.matrix.android.sdk.api.session.room.sender.SenderInfo.disambiguatedDisplayName] */ + /** See [org.matrix.android.sdk.api.session.room.sender.SenderInfo.disambiguatedDisplayName]. */ private fun resolveRoomMemberName(roomMemberSummary: RoomMemberSummaryEntity, roomMemberHelper: RoomMemberHelper): String { val isUnique = roomMemberHelper.isUniqueDisplayName(roomMemberSummary.displayName) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt index 9ce8db25a5..40228fe8c9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/RoomMemberHelper.kt @@ -104,7 +104,7 @@ internal class RoomMemberHelper(private val realm: Realm, } /** - * Return all the roomMembers ids which are joined or invited to the room + * Return all the roomMembers ids which are joined or invited to the room. * * @return a roomMember id list of joined or invited members. */ @@ -113,7 +113,7 @@ internal class RoomMemberHelper(private val realm: Realm, } /** - * Return all the roomMembers ids which are joined to the room + * Return all the roomMembers ids which are joined to the room. * * @return a roomMember id list of joined members. */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/joining/JoinRoomTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/joining/JoinRoomTask.kt index 6306f3c6fe..4c631c2182 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/joining/JoinRoomTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/membership/joining/JoinRoomTask.kt @@ -18,6 +18,7 @@ package org.matrix.android.sdk.internal.session.room.membership.joining import io.realm.RealmConfiguration import kotlinx.coroutines.TimeoutCancellationException +import org.matrix.android.sdk.api.MatrixCoroutineDispatchers import org.matrix.android.sdk.api.session.events.model.toContent import org.matrix.android.sdk.api.session.identity.model.SignInvitationResult import org.matrix.android.sdk.api.session.room.failure.JoinRoomFailure @@ -53,6 +54,7 @@ internal class DefaultJoinRoomTask @Inject constructor( private val readMarkersTask: SetReadMarkersTask, @SessionDatabase private val realmConfiguration: RealmConfiguration, + private val coroutineDispatcher: MatrixCoroutineDispatchers, private val roomChangeMembershipStateDataSource: RoomChangeMembershipStateDataSource, private val globalErrorReceiver: GlobalErrorReceiver, private val clock: Clock, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt index 8d35a8fea4..dabdd04f60 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/relation/threads/FetchThreadTimelineTask.kt @@ -192,7 +192,7 @@ internal class DefaultFetchThreadTimelineTask @Inject constructor( // TODO Reuse this function to all the app /** - * If we don't have any new state on this user, get it from db + * If we don't have any new state on this user, get it from db. */ private fun HashMap.addSenderState(realm: Realm, roomId: String, senderId: String) { getOrPut(senderId) { @@ -204,7 +204,7 @@ internal class DefaultFetchThreadTimelineTask @Inject constructor( } /** - * Create an EventEntity to be added in the TimelineEventEntity + * Create an EventEntity to be added in the TimelineEventEntity. */ private fun createEventEntity(roomId: String, event: Event, realm: Realm): EventEntity { val ageLocalTs = event.unsignedData?.age?.let { clock.epochMillis() - it } @@ -212,7 +212,7 @@ internal class DefaultFetchThreadTimelineTask @Inject constructor( } /** - * Invoke the event decryption mechanism for a specific event + * Invoke the event decryption mechanism for a specific event. */ private suspend fun decryptIfNeeded(event: Event, roomId: String) { try { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt index 9baaa9cd82..8529365858 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/DefaultSendService.kt @@ -307,7 +307,7 @@ internal class DefaultSendService @AssistedInject constructor( } /** - * We use the roomId of the local echo event + * We use the roomId of the local echo event. */ private fun internalSendMedia(allLocalEchoes: List, attachment: ContentAttachmentData, compressBeforeSending: Boolean): Cancelable { val cancelableBag = CancelableBag() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt index d019ffada6..d39088bd6d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoEventFactory.kt @@ -506,7 +506,7 @@ internal class LocalEchoEventFactory @Inject constructor( } /** - * Enhance sticker to support threads fallback if needed + * Enhance sticker to support threads fallback if needed. */ private fun enhanceStickerIfNeeded(type: String, content: Content?): Content? { var newContent: Content? = null @@ -526,7 +526,7 @@ internal class LocalEchoEventFactory @Inject constructor( } /** - * Creates a thread event related to the already existing root event + * Creates a thread event related to the already existing root event. */ fun createThreadTextEvent( rootThreadEventId: String, @@ -553,7 +553,7 @@ internal class LocalEchoEventFactory @Inject constructor( } /** - * Creates a reply to a regular timeline Event or a thread Event if needed + * Creates a reply to a regular timeline Event or a thread Event if needed. */ fun createReplyTextEvent(roomId: String, eventReplied: TimelineEvent, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt index 9fd45b917f..bed590fd09 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/LocalEchoRepository.kt @@ -221,7 +221,7 @@ internal class LocalEchoRepository @Inject constructor( } /** - * Returns the latest known thread event message, or the rootThreadEventId if no other event found + * Returns the latest known thread event message, or the rootThreadEventId if no other event found. */ fun getLatestThreadEvent(rootThreadEventId: String): String { return realmSessionProvider.withRealm { realm -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParser.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParser.kt index 05585a4cb5..6a9f86893f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParser.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MarkdownParser.kt @@ -78,7 +78,7 @@ internal class MarkdownParser @Inject constructor( text != htmlText && htmlText != "

${text.trim()}

\n" /** - * The parser makes some mistakes, so deal with it here + * The parser makes some mistakes, so deal with it here. */ private fun String.postTreatment(): String { return this diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MultipleEventSendingDispatcherWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MultipleEventSendingDispatcherWorker.kt index ecc8149255..2afca6e554 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MultipleEventSendingDispatcherWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/MultipleEventSendingDispatcherWorker.kt @@ -33,10 +33,10 @@ import timber.log.Timber import javax.inject.Inject /** - * This worker creates a new work for each events passed in parameter + * This worker creates a new work for each events passed in parameter. * - * Possible previous worker: Always [UploadContentWorker] - * Possible next worker : None, but it will post new work to send events, encrypted or not + * Possible previous worker: Always [UploadContentWorker]. + * Possible next worker : None, but it will post new work to send events, encrypted or not. */ internal class MultipleEventSendingDispatcherWorker(context: Context, params: WorkerParameters, sessionManager: SessionManager) : SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/NoMerger.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/NoMerger.kt index b56b283171..6dbd8682d7 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/NoMerger.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/NoMerger.kt @@ -19,7 +19,7 @@ import androidx.work.Data import androidx.work.InputMerger /** - * InputMerger which takes only the first input, to ensure an appended work will only have the specified parameters + * InputMerger which takes only the first input, to ensure an appended work will only have the specified parameters. */ internal class NoMerger : InputMerger() { override fun merge(inputs: MutableList): Data { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt index db8d1b5674..1c0da4839a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/RedactEventWorker.kt @@ -30,8 +30,8 @@ import org.matrix.android.sdk.internal.worker.WorkerParamsFactory import javax.inject.Inject /** - * Possible previous worker: None - * Possible next worker : None + * Possible previous worker: None. + * Possible next worker : None. */ internal class RedactEventWorker(context: Context, params: WorkerParameters, sessionManager: SessionManager) : SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/SendEventWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/SendEventWorker.kt index ddbe8a61a0..bea6069dd6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/SendEventWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/SendEventWorker.kt @@ -36,8 +36,8 @@ import javax.inject.Inject // private const val MAX_NUMBER_OF_RETRY_BEFORE_FAILING = 3 /** - * Possible previous worker: [EncryptEventWorker] or first worker - * Possible next worker : None + * Possible previous worker: [EncryptEventWorker] or first worker. + * Possible next worker : None. */ internal class SendEventWorker(context: Context, params: WorkerParameters, sessionManager: SessionManager) : SessionSafeCoroutineWorker(context, params, sessionManager, Params::class.java) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt index a1d3e2c0ac..8ef631ad36 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/EventSenderProcessorCoroutine.kt @@ -64,12 +64,12 @@ internal class EventSenderProcessorCoroutine @Inject constructor( private val waitForNetworkSequencer = SemaphoreCoroutineSequencer() /** - * sequencers use QueuedTask.queueIdentifier as key + * sequencers use QueuedTask.queueIdentifier as key. */ private val sequencers = ConcurrentHashMap() /** - * cancelableBag use QueuedTask.taskIdentifier as key + * cancelableBag use QueuedTask.taskIdentifier as key. */ private val cancelableBag = ConcurrentHashMap() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/TaskInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/TaskInfo.kt index a7863470f7..e216e5109f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/TaskInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/send/queue/TaskInfo.kt @@ -24,8 +24,8 @@ import org.matrix.android.sdk.internal.di.SerializeNulls import org.matrix.android.sdk.internal.network.parsing.RuntimeJsonAdapterFactory /** - * Info that need to be persisted by the sender thread - * With polymorphic moshi parsing + * Info that need to be persisted by the sender thread. + * With polymorphic moshi parsing. */ internal interface TaskInfo { val type: String diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt index e5c7a75cb6..60231892e1 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/DefaultStateService.kt @@ -136,7 +136,7 @@ internal class DefaultStateService @AssistedInject constructor(@Assisted private if (joinRules != null) { val body = if (joinRules == RoomJoinRules.RESTRICTED) { RoomJoinRulesContent( - _joinRules = RoomJoinRules.RESTRICTED.value, + joinRulesStr = RoomJoinRules.RESTRICTED.value, allowList = allowList ).toContent() } else { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/SafePowerLevelContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/SafePowerLevelContent.kt index 1f2ec09367..b0c795950e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/SafePowerLevelContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/state/SafePowerLevelContent.kt @@ -23,8 +23,11 @@ import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent import org.matrix.android.sdk.api.util.JsonDict +/** + * Serializable object. + */ @JsonClass(generateAdapter = true) -internal data class SerializablePowerLevelsContent( +internal data class SafePowerLevelContent( @Json(name = "ban") val ban: Int?, @Json(name = "kick") val kick: Int?, @Json(name = "invite") val invite: Int?, @@ -41,7 +44,7 @@ internal data class SerializablePowerLevelsContent( internal fun JsonDict.toSafePowerLevelsContentDict(): JsonDict { return toModel() ?.let { content -> - SerializablePowerLevelsContent( + SafePowerLevelContent( ban = content.ban, kick = content.kick, invite = content.invite, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt index 52879d7121..496bc7097f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/GraphUtils.kt @@ -71,7 +71,7 @@ internal class Graph { } /** - * Depending on the chosen starting point the background edge might change + * Depending on the chosen starting point the background edge might change. */ fun findBackwardEdges(startFrom: GraphNode? = null): List { val backwardEdges = mutableSetOf() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt index 3af579d050..611d6dc65e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/summary/RoomSummaryUpdater.kt @@ -212,7 +212,7 @@ internal class RoomSummaryUpdater @Inject constructor( } /** - * Should be called at the end of the room sync, to check and validate all parent/child relations + * Should be called at the end of the room sync, to check and validate all parent/child relations. */ fun validateSpaceRelationship(realm: Realm) { measureTimeMillis { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt index 18fbe73c09..fad21c0918 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimeline.kt @@ -39,6 +39,7 @@ import org.matrix.android.sdk.api.settings.LightweightSettingsStorage import org.matrix.android.sdk.internal.database.mapper.TimelineEventMapper import org.matrix.android.sdk.internal.session.room.membership.LoadRoomMembersTask import org.matrix.android.sdk.internal.session.room.relation.threads.FetchThreadTimelineTask +import org.matrix.android.sdk.internal.session.room.state.StateEventDataSource import org.matrix.android.sdk.internal.session.sync.handler.room.ReadReceiptHandler import org.matrix.android.sdk.internal.session.sync.handler.room.ThreadsAwarenessHandler import org.matrix.android.sdk.internal.task.SemaphoreCoroutineSequencer @@ -59,6 +60,7 @@ internal class DefaultTimeline( private val settings: TimelineSettings, private val coroutineDispatchers: MatrixCoroutineDispatchers, private val clock: Clock, + stateEventDataSource: StateEventDataSource, paginationTask: PaginationTask, getEventTask: GetContextOfEventTask, fetchTokenAndPaginateTask: FetchTokenAndPaginateTask, @@ -106,7 +108,9 @@ internal class DefaultTimeline( onEventsUpdated = this::sendSignalToPostSnapshot, onEventsDeleted = this::onEventsDeleted, onLimitedTimeline = this::onLimitedTimeline, - onNewTimelineEvents = this::onNewTimelineEvents + onNewTimelineEvents = this::onNewTimelineEvents, + stateEventDataSource = stateEventDataSource, + matrixCoroutineDispatchers = coroutineDispatchers, ) private var strategy: LoadTimelineStrategy = buildStrategy(LoadTimelineStrategy.Mode.Live) @@ -291,7 +295,6 @@ internal class DefaultTimeline( } } - @Suppress("EXPERIMENTAL_API_USAGE") private fun listenToPostSnapshotSignals() { postSnapshotSignalFlow .sample(150) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimelineService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimelineService.kt index 6d63b24cf5..53c0253876 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimelineService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/DefaultTimelineService.kt @@ -32,6 +32,7 @@ import org.matrix.android.sdk.internal.database.mapper.TimelineEventMapper import org.matrix.android.sdk.internal.di.SessionDatabase import org.matrix.android.sdk.internal.session.room.membership.LoadRoomMembersTask import org.matrix.android.sdk.internal.session.room.relation.threads.FetchThreadTimelineTask +import org.matrix.android.sdk.internal.session.room.state.StateEventDataSource import org.matrix.android.sdk.internal.session.sync.handler.room.ReadReceiptHandler import org.matrix.android.sdk.internal.session.sync.handler.room.ThreadsAwarenessHandler import org.matrix.android.sdk.internal.util.time.Clock @@ -53,6 +54,7 @@ internal class DefaultTimelineService @AssistedInject constructor( private val coroutineDispatchers: MatrixCoroutineDispatchers, private val timelineEventDataSource: TimelineEventDataSource, private val clock: Clock, + private val stateEventDataSource: StateEventDataSource, ) : TimelineService { @AssistedFactory @@ -78,7 +80,8 @@ internal class DefaultTimelineService @AssistedInject constructor( getEventTask = contextOfEventTask, threadsAwarenessHandler = threadsAwarenessHandler, lightweightSettingsStorage = lightweightSettingsStorage, - clock = clock + clock = clock, + stateEventDataSource = stateEventDataSource, ) } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LiveRoomStateListener.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LiveRoomStateListener.kt new file mode 100644 index 0000000000..b2692bf805 --- /dev/null +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LiveRoomStateListener.kt @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 The Matrix.org Foundation C.I.C. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.internal.session.room.timeline + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext +import org.matrix.android.sdk.api.query.QueryStringValue +import org.matrix.android.sdk.api.session.events.model.Event +import org.matrix.android.sdk.api.session.events.model.EventType +import org.matrix.android.sdk.api.session.room.model.RoomMemberContent +import org.matrix.android.sdk.internal.session.events.getFixedRoomMemberContent +import org.matrix.android.sdk.internal.session.room.state.StateEventDataSource + +/** + * Helper to observe and query the live room state. + */ +internal class LiveRoomStateListener( + roomId: String, + stateEventDataSource: StateEventDataSource, + private val mainDispatcher: CoroutineDispatcher, +) { + private val roomStateObserver = Observer> { stateEvents -> + stateEvents.map { event -> + val memberContent = event.getFixedRoomMemberContent() ?: return@map + val stateKey = event.stateKey ?: return@map + liveRoomState[stateKey] = memberContent + } + } + private val stateEventsLiveData: LiveData> by lazy { + stateEventDataSource.getStateEventsLive( + roomId = roomId, + eventTypes = setOf(EventType.STATE_ROOM_MEMBER), + stateKey = QueryStringValue.NoCondition, + ) + } + + private val liveRoomState = mutableMapOf() + + suspend fun start() = withContext(mainDispatcher) { + stateEventsLiveData.observeForever(roomStateObserver) + } + + suspend fun stop() = withContext(mainDispatcher) { + if (stateEventsLiveData.hasActiveObservers()) { + stateEventsLiveData.removeObserver(roomStateObserver) + } + } + + fun getLiveState(stateKey: String): RoomMemberContent? = liveRoomState[stateKey] +} diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt index bcf202962c..4f65f85ce4 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/LoadTimelineStrategy.kt @@ -23,6 +23,7 @@ import io.realm.RealmConfiguration import io.realm.RealmResults import io.realm.kotlin.createObject import kotlinx.coroutines.CompletableDeferred +import org.matrix.android.sdk.api.MatrixCoroutineDispatchers import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.failure.Failure import org.matrix.android.sdk.api.failure.MatrixError @@ -41,6 +42,7 @@ import org.matrix.android.sdk.internal.database.query.findAllIncludingEvents import org.matrix.android.sdk.internal.database.query.findLastForwardChunkOfThread import org.matrix.android.sdk.internal.database.query.where import org.matrix.android.sdk.internal.session.room.relation.threads.FetchThreadTimelineTask +import org.matrix.android.sdk.internal.session.room.state.StateEventDataSource import org.matrix.android.sdk.internal.session.sync.handler.room.ThreadsAwarenessHandler import org.matrix.android.sdk.internal.util.time.Clock import timber.log.Timber @@ -100,7 +102,9 @@ internal class LoadTimelineStrategy constructor( val onEventsUpdated: (Boolean) -> Unit, val onEventsDeleted: () -> Unit, val onLimitedTimeline: () -> Unit, - val onNewTimelineEvents: (List) -> Unit + val onNewTimelineEvents: (List) -> Unit, + val stateEventDataSource: StateEventDataSource, + val matrixCoroutineDispatchers: MatrixCoroutineDispatchers, ) private var getContextLatch: CompletableDeferred? = null @@ -165,7 +169,13 @@ internal class LoadTimelineStrategy constructor( onEventsUpdated = dependencies.onEventsUpdated ) - fun onStart() { + private val liveRoomStateListener = LiveRoomStateListener( + roomId, + dependencies.stateEventDataSource, + dependencies.matrixCoroutineDispatchers.main + ) + + suspend fun onStart() { dependencies.eventDecryptor.start() dependencies.timelineInput.listeners.add(timelineInputListener) val realm = dependencies.realm.get() @@ -174,9 +184,13 @@ internal class LoadTimelineStrategy constructor( it.addChangeListener(chunkEntityListener) timelineChunk = it.createTimelineChunk() } + + if (dependencies.timelineSettings.useLiveSenderInfo) { + liveRoomStateListener.start() + } } - fun onStop() { + suspend fun onStop() { dependencies.eventDecryptor.destroy() dependencies.timelineInput.listeners.remove(timelineInputListener) chunkEntity?.removeChangeListener(chunkEntityListener) @@ -188,6 +202,9 @@ internal class LoadTimelineStrategy constructor( if (mode is Mode.Thread) { clearThreadChunkEntity(dependencies.realm.get(), mode.rootThreadEventId) } + if (dependencies.timelineSettings.useLiveSenderInfo) { + liveRoomStateListener.stop() + } } suspend fun loadMore(count: Int, direction: Timeline.Direction, fetchOnServerIfNeeded: Boolean = true): LoadMoreResult { @@ -222,7 +239,22 @@ internal class LoadTimelineStrategy constructor( } fun buildSnapshot(): List { - return buildSendingEvents() + timelineChunk?.builtItems(includesNext = true, includesPrev = true).orEmpty() + val events = buildSendingEvents() + timelineChunk?.builtItems(includesNext = true, includesPrev = true).orEmpty() + return if (dependencies.timelineSettings.useLiveSenderInfo) { + events.map(this::applyLiveRoomState) + } else { + events + } + } + + private fun applyLiveRoomState(event: TimelineEvent): TimelineEvent { + val updatedState = liveRoomStateListener.getLiveState(event.senderInfo.userId) + return if (updatedState != null) { + val updatedSenderInfo = event.senderInfo.copy(avatarUrl = updatedState.avatarUrl, displayName = updatedState.displayName) + event.copy(senderInfo = updatedSenderInfo) + } else { + event + } } private fun buildSendingEvents(): List { @@ -255,7 +287,7 @@ internal class LoadTimelineStrategy constructor( /** * Clear any existing thread chunk entity and create a new one, with the - * rootThreadEventId included + * rootThreadEventId included. */ private fun recreateThreadChunkEntity(realm: Realm, rootThreadEventId: String) { realm.executeTransaction { @@ -275,7 +307,7 @@ internal class LoadTimelineStrategy constructor( } /** - * Clear any existing thread chunk + * Clear any existing thread chunk. */ private fun clearThreadChunkEntity(realm: Realm, rootThreadEventId: String) { realm.executeTransaction { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt index 8541c478ba..6a5f9da8a6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/TimelineChunk.kt @@ -136,6 +136,7 @@ internal class TimelineChunk( val prevEvents = prevChunk?.builtItems(includesNext = false, includesPrev = true).orEmpty() deepBuiltItems.addAll(prevEvents) } + return deepBuiltItems } @@ -238,7 +239,7 @@ internal class TimelineChunk( } /** - * Simple log that displays the number and timeline of loaded events + * Simple log that displays the number and timeline of loaded events. */ private fun logLoadedFromStorage(loadedFromStorage: LoadedFromStorage, direction: Timeline.Direction) { Timber.v( @@ -380,7 +381,7 @@ internal class TimelineChunk( /** * This function is responsible to fetch and store the root event of a thread event - * in order to be able to display the event to the user appropriately + * in order to be able to display the event to the user appropriately. */ private suspend fun fetchRootThreadEventsIfNeeded(offsetResults: List) { val eventEntityList = offsetResults diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt index 828e01955a..66bb04400b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/timeline/UIEchoManager.kt @@ -44,7 +44,7 @@ internal class UIEchoManager( } /** - * Due to lag of DB updates, we keep some UI echo of some properties to update timeline faster + * Due to lag of DB updates, we keep some UI echo of some properties to update timeline faster. */ private val inMemorySendingStates = Collections.synchronizedMap(HashMap()) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/typing/DefaultTypingService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/typing/DefaultTypingService.kt index b76829e893..38ccd19020 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/typing/DefaultTypingService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/room/typing/DefaultTypingService.kt @@ -31,7 +31,7 @@ import timber.log.Timber * Rules: * - user is typing: notify the homeserver (true), at least once every 10s * - user stop typing: after 10s delay: notify the homeserver (false) - * - user empty the text composer or quit the timeline screen: notify the homeserver (false) + * - user empty the text composer or quit the timeline screen: notify the homeserver (false). */ internal class DefaultTypingService @AssistedInject constructor( @Assisted private val roomId: String, @@ -53,7 +53,7 @@ internal class DefaultTypingService @AssistedInject constructor( private var lastRequestTimestamp: Long = 0 /** - * Notify to the server that the user is typing and schedule the auto typing off + * Notify to the server that the user is typing and schedule the auto typing off. */ override fun userIsTyping() { val now = SystemClock.elapsedRealtime() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchTask.kt index fcaf3b60a7..f785ed4266 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/SearchTask.kt @@ -112,7 +112,7 @@ internal class DefaultSearchTask @Inject constructor( } /** - * Find local events if exists in order to enhance the result with thread summary + * Find local events if exists in order to enhance the result with thread summary. */ private fun findRootThreadEventsFromDB(searchResponseItemList: List?): List? { return realmSessionProvider.withRealm { realm -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/request/SearchRequestRoomEvents.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/request/SearchRequestRoomEvents.kt index 6064381808..e78c170a32 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/request/SearchRequestRoomEvents.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/search/request/SearchRequestRoomEvents.kt @@ -55,7 +55,7 @@ internal data class SearchRequestRoomEvents( * Requests the server return the current state for each room returned. */ @Json(name = "include_state") - val include_state: Boolean? = null + val includeState: Boolean? = null /** * Requests that the server partitions the result set based on the provided list of keys. diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt index 267023d186..07a5cbe5a0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/securestorage/SecretStoringUtils.kt @@ -129,7 +129,7 @@ internal class SecretStoringUtils @Inject constructor( } /** - * Decrypt a secret that was encrypted by #securelyStoreString() + * Decrypt a secret that was encrypted by #securelyStoreString(). */ @SuppressLint("NewApi") @Throws(Exception::class) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt index fda9b4b5bc..d8daa55e15 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceApi.kt @@ -40,7 +40,7 @@ internal interface SpaceApi { @Query("from") from: String?): SpacesResponse /** - * Unstable version of [getSpaceHierarchy] + * Unstable version of [getSpaceHierarchy]. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_UNSTABLE + "org.matrix.msc2946/rooms/{roomId}/hierarchy") suspend fun getSpaceHierarchyUnstable( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceChildSummaryResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceChildSummaryResponse.kt index b6a9c73d36..e3f8977ac5 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceChildSummaryResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/space/SpaceChildSummaryResponse.kt @@ -97,7 +97,7 @@ internal data class SpaceChildSummaryResponse( val avatarUrl: String? = null, /** - * Undocumented item + * Undocumented item. */ @Json(name = "m.federate") val isFederated: Boolean = false diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/InitialSyncStatusRepository.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/InitialSyncStatusRepository.kt index 8e0c3422b9..e90df3d39d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/InitialSyncStatusRepository.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/InitialSyncStatusRepository.kt @@ -45,7 +45,7 @@ internal interface InitialSyncStatusRepository { } /** - * This class handle the current status of an initial sync and persist it on the disk, to be robust against crash + * This class handle the current status of an initial sync and persist it on the disk, to be robust against crash. */ internal class FileInitialSyncStatusRepository( directory: File, @@ -95,7 +95,7 @@ internal class FileInitialSyncStatusRepository( } /** - * File -> Cache + * File -> Cache. */ private fun readFile() { cache = file @@ -104,7 +104,7 @@ internal class FileInitialSyncStatusRepository( } /** - * Cache -> File + * Cache -> File. */ private fun writeFile() { file.delete() diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/RoomSyncEphemeralTemporaryStore.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/RoomSyncEphemeralTemporaryStore.kt index ef9f468c86..0e48cddc2d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/RoomSyncEphemeralTemporaryStore.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/RoomSyncEphemeralTemporaryStore.kt @@ -48,7 +48,7 @@ internal class RoomSyncEphemeralTemporaryStoreFile @Inject constructor( private val roomSyncEphemeralAdapter = moshi.adapter(RoomSyncEphemeral::class.java) /** - * Write RoomSyncEphemeral to a file + * Write RoomSyncEphemeral to a file. */ override fun write(roomId: String, roomSyncEphemeralJson: String) { Timber.w("INIT_SYNC Store ephemeral events for room $roomId") @@ -56,7 +56,7 @@ internal class RoomSyncEphemeralTemporaryStoreFile @Inject constructor( } /** - * Read RoomSyncEphemeral from a file, or null if there is no file to read + * Read RoomSyncEphemeral from a file, or null if there is no file to read. */ override fun read(roomId: String): RoomSyncEphemeral? { return getFile(roomId) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt index 73ec0aa7ef..6c8a71f35e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncAPI.kt @@ -28,7 +28,7 @@ import retrofit2.http.Streaming internal interface SyncAPI { /** - * Set all the timeouts to 1 minute by default + * Set all the timeouts to 1 minute by default. */ @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sync") suspend fun sync(@QueryMap params: Map, @@ -38,7 +38,7 @@ internal interface SyncAPI { ): SyncResponse /** - * Set all the timeouts to 1 minute by default + * Set all the timeouts to 1 minute by default. */ @Streaming @GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sync") diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt index 42cd972e0c..ce41a4568c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/SyncPresence.kt @@ -29,6 +29,7 @@ import org.matrix.android.sdk.api.session.presence.model.PresenceEnum internal enum class SyncPresence(val value: String) { Offline("offline"), Online("online"), + Busy("busy"), Unavailable("unavailable"); companion object { @@ -36,6 +37,7 @@ internal enum class SyncPresence(val value: String) { return when (presenceEnum) { PresenceEnum.ONLINE -> Online PresenceEnum.OFFLINE -> Offline + PresenceEnum.BUSY -> Busy PresenceEnum.UNAVAILABLE -> Unavailable } } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt index 429f498533..dd95762166 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/CryptoSyncHandler.kt @@ -60,7 +60,7 @@ internal class CryptoSyncHandler @Inject constructor(private val cryptoService: } /** - * Decrypt an encrypted event + * Decrypt an encrypted event. * * @param event the event to decrypt * @param timelineId the timeline identifier diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/PresenceSyncHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/PresenceSyncHandler.kt index 6a7af1dda4..0d4c06339b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/PresenceSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/PresenceSyncHandler.kt @@ -52,7 +52,7 @@ internal class PresenceSyncHandler @Inject constructor(private val matrixConfigu } /** - * Store user presence to DB and update Direct Rooms and Room Member Summaries accordingly + * Store user presence to DB and update Direct Rooms and Room Member Summaries accordingly. */ private fun storePresenceToDB(realm: Realm, userPresenceEntity: UserPresenceEntity) = realm.copyToRealmOrUpdate(userPresenceEntity)?.apply { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt index 5437a015fd..c5d14afac0 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/RoomSyncHandler.kt @@ -213,7 +213,7 @@ internal class RoomSyncHandler @Inject constructor( val isInitialSync = insertType == EventInsertType.INITIAL_SYNC val ephemeralResult = (roomSync.ephemeral as? LazyRoomSyncEphemeral.Parsed) - ?._roomSyncEphemeral + ?.roomSyncEphemeral ?.events ?.takeIf { it.isNotEmpty() } ?.let { handleEphemeral(realm, roomId, it, insertType == EventInsertType.INITIAL_SYNC, aggregator) } @@ -382,7 +382,10 @@ internal class RoomSyncHandler @Inject constructor( val roomMemberContentsByUser = HashMap() val optimizedThreadSummaryMap = hashMapOf() - for (event in eventList) { + for (rawEvent in eventList) { + // It's annoying roomId is not there, but lot of code rely on it. + // And had to do it now as copy would delete all decryption results.. + val event = rawEvent.copy(roomId = roomId) if (event.eventId == null || event.senderId == null || event.type == null) { continue } @@ -454,7 +457,7 @@ internal class RoomSyncHandler @Inject constructor( } } // Give info to crypto module - cryptoService.onLiveEvent(roomEntity.roomId, event) + cryptoService.onLiveEvent(roomEntity.roomId, event, isInitialSync) // Try to remove local echo event.unsignedData?.transactionId?.also { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt index 7b7df57bc5..03e076c217 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/handler/room/ThreadsAwarenessHandler.kt @@ -73,7 +73,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( private val cacheEventRootId = hashSetOf() /** - * Fetch root thread events if they are missing from the local storage + * Fetch root thread events if they are missing from the local storage. * @param syncResponse the sync response */ suspend fun fetchRootThreadEventsIfNeeded(syncResponse: SyncResponse) { @@ -92,7 +92,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * Fetch root thread events if they are missing from the local storage + * Fetch root thread events if they are missing from the local storage. * @param eventList a list with the events to examine */ suspend fun fetchRootThreadEventsIfNeeded(eventList: List) { @@ -115,7 +115,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * Fetch multiple unique events using the fetchEvent function + * Fetch multiple unique events using the fetchEvent function. */ private suspend fun fetchThreadsEvents(threadsToFetch: Map) { val eventEntityList = threadsToFetch.mapNotNull { (eventId, roomId) -> @@ -153,7 +153,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * Handle events mainly coming from the RoomSyncHandler + * Handle events mainly coming from the RoomSyncHandler. * @return The content to inject in the roomSyncHandler live events */ fun makeEventThreadAware(realm: Realm, @@ -226,9 +226,9 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * This function is responsible to check if there is any event that relates to our current event + * This function is responsible to check if there is any event that relates to our current event. * This is useful when we receive an event that relates to a missing parent, so when later we receive the parent - * we can update the child as well + * we can update the child as well. * @param event the current event that we examine * @param eventBody the current body of the event * @param isFromCache determines whether or not we already know this is root thread event @@ -263,7 +263,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * Actual update the eventEntity with the new payload + * Actual update the eventEntity with the new payload. * @return the content to inject when this is executed by RoomSyncHandler */ private fun updateEventEntity(event: Event, @@ -291,7 +291,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * Injecting $eventToInject decrypted content as a reply to $event + * Injecting $eventToInject decrypted content as a reply to $event. * @param eventToInject the event that will inject * @param eventBody the actual event body * @return The final content with the injected event @@ -324,7 +324,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * Integrate fallback Quote reply + * Integrate fallback Quote reply. */ private fun injectFallbackIndicator(event: Event, eventBody: String, @@ -364,7 +364,7 @@ internal class ThreadsAwarenessHandler @Inject constructor( /** * Try to get the event form the local DB, if the event does not exist null - * will be returned + * will be returned. */ private fun getEventFromDB(realm: Realm, eventId: String): Event? { val eventEntity = EventEntity.where(realm, eventId = eventId).findFirst() ?: return null @@ -372,14 +372,14 @@ internal class ThreadsAwarenessHandler @Inject constructor( } /** - * Returns True if the event is a thread + * Returns True if the event is a thread. * @param event */ private fun isThreadEvent(event: Event): Boolean = event.content.toModel()?.relatesTo?.type == RelationType.THREAD /** - * Returns the root thread eventId or null otherwise + * Returns the root thread eventId or null otherwise. * @param event */ private fun getRootThreadEventId(event: Event): String? = diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt index f183c4cb28..bbb18b664c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/job/SyncWorker.kt @@ -38,8 +38,8 @@ private const val DEFAULT_LONG_POOL_TIMEOUT_SECONDS = 6L private const val DEFAULT_DELAY_MILLIS = 30_000L /** - * Possible previous worker: None - * Possible next worker : None + * Possible previous worker: None. + * Possible next worker : None. */ internal class SyncWorker(context: Context, workerParameters: WorkerParameters, sessionManager: SessionManager) : SessionSafeCoroutineWorker(context, workerParameters, sessionManager, Params::class.java) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DeviceInfo.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DeviceInfo.kt index fdb9916190..7f6759906f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DeviceInfo.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DeviceInfo.kt @@ -19,24 +19,24 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * This class describes the device information + * This class describes the device information. */ @JsonClass(generateAdapter = true) internal data class DeviceInfo( /** - * The owner user id + * The owner user id. */ @Json(name = "user_id") val userId: String? = null, /** - * The device id + * The device id. */ @Json(name = "device_id") val deviceId: String? = null, /** - * The device display name + * The device display name. */ @Json(name = "display_name") val displayName: String? = null, @@ -48,7 +48,7 @@ internal data class DeviceInfo( val lastSeenTs: Long = 0, /** - * The last ip address + * The last ip address. */ @Json(name = "last_seen_ip") val lastSeenIp: String? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DevicesListResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DevicesListResponse.kt index 3dc71a355d..acef22a542 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DevicesListResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/DevicesListResponse.kt @@ -17,9 +17,6 @@ package org.matrix.android.sdk.internal.session.sync.model import com.squareup.moshi.JsonClass -/** - * This class describes the - */ @JsonClass(generateAdapter = true) internal data class DevicesListResponse( val devices: List? = null diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/accountdata/DirectMessagesContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/accountdata/DirectMessagesContent.kt index 7c73f1fed0..2e45b2ad98 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/accountdata/DirectMessagesContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/sync/model/accountdata/DirectMessagesContent.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.session.sync.model.accountdata /** - * Keys are userIds, values are list of roomIds + * Keys are userIds, values are list of roomIds. */ internal typealias DirectMessagesContent = Map> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/AcceptTermsBody.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/AcceptTermsBody.kt index ee23c9e6bc..bf954b0aee 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/AcceptTermsBody.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/AcceptTermsBody.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * This class represent a list of urls of terms the user wants to accept + * This class represent a list of urls of terms the user wants to accept. */ @JsonClass(generateAdapter = true) internal data class AcceptTermsBody( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt index 5d2fa0fc5c..9876643bed 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/DefaultTermsService.kt @@ -61,7 +61,7 @@ internal class DefaultTermsService @Inject constructor( } /** - * We use a trick here to get the homeserver T&C, we use the register API + * We use a trick here to get the homeserver T&C, we use the register API. */ override suspend fun getHomeserverTerms(baseUrl: String): TermsResponse { return try { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt index 1f117de67e..f6f57bf0ef 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/terms/TermsAPI.kt @@ -28,13 +28,13 @@ import retrofit2.http.Url internal interface TermsAPI { /** - * This request does not require authentication + * This request does not require authentication. */ @GET suspend fun getTerms(@Url url: String): TermsResponse /** - * This request requires authentication + * This request requires authentication. */ @POST suspend fun agreeToTerms(@Url url: String, @@ -43,7 +43,7 @@ internal interface TermsAPI { /** * API to retrieve the terms for a homeserver. The API /terms does not exist yet, so retrieve the terms from the login flow. - * We do not care about the result (Credentials) + * We do not care about the result (Credentials). */ @POST suspend fun register(@Url url: String, diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/typing/DefaultTypingUsersTracker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/typing/DefaultTypingUsersTracker.kt index c5c3fc4b59..ac4a886aa3 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/typing/DefaultTypingUsersTracker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/typing/DefaultTypingUsersTracker.kt @@ -27,7 +27,7 @@ internal class DefaultTypingUsersTracker @Inject constructor() : TypingUsersTrac private val typingUsers = mutableMapOf>() /** - * Set all currently typing users for a room (excluding yourself) + * Set all currently typing users for a room (excluding yourself). */ fun setTypingUsersFromRoom(roomId: String, senderInfoList: List) { val hasNewValue = typingUsers[roomId] != senderInfoList diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataContent.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataContent.kt index 5f9f0777d8..c3daa2a0e9 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataContent.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/AccountDataContent.kt @@ -17,6 +17,6 @@ package org.matrix.android.sdk.internal.session.user.accountdata /** - * Tag class to identify every account data content + * Tag class to identify every account data content. */ internal interface AccountDataContent diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/DefaultSessionAccountDataService.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/DefaultSessionAccountDataService.kt index 59c4dd671e..df9dcfb903 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/DefaultSessionAccountDataService.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/DefaultSessionAccountDataService.kt @@ -68,7 +68,7 @@ internal class DefaultSessionAccountDataService @Inject constructor( val params = UpdateUserAccountDataTask.AnyParams(type = type, any = content) awaitCallback { callback -> updateUserAccountDataTask.configureWith(params) { - this.retryCount = 5 // TODO: Need to refactor retrying out into a helper method. + this.retryCount = 5 // TODO Need to refactor retrying out into a helper method. this.callback = callback } .executeBy(taskExecutor) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/SaveBreadcrumbsTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/SaveBreadcrumbsTask.kt index 22af56a169..148f9d657d 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/SaveBreadcrumbsTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/accountdata/SaveBreadcrumbsTask.kt @@ -29,7 +29,7 @@ import org.matrix.android.sdk.internal.util.awaitTransaction import javax.inject.Inject /** - * Save the Breadcrumbs roomId list in DB, either from the sync, or updated locally + * Save the Breadcrumbs roomId list in DB, either from the sync, or updated locally. */ internal interface SaveBreadcrumbsTask : Task { data class Params( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersParams.kt index 46285965b4..29d957f2bf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersParams.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing an user search parameters + * Class representing an user search parameters. */ @JsonClass(generateAdapter = true) internal data class SearchUsersParams( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersResponse.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersResponse.kt index e2a93abde0..058bf09da6 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersResponse.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/user/model/SearchUsersResponse.kt @@ -20,7 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** - * Class representing an users search response + * Class representing an users search response. */ @JsonClass(generateAdapter = true) internal data class SearchUsersResponse( diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt index 9f42688f7d..1da6827916 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/DefaultWidgetPostAPIMediator.kt @@ -93,7 +93,7 @@ internal class DefaultWidgetPostAPIMediator @Inject constructor(private val mosh */ /** - * Send a boolean response + * Send a boolean response. * * @param response the response * @param eventData the modular data @@ -104,7 +104,7 @@ internal class DefaultWidgetPostAPIMediator @Inject constructor(private val mosh } /** - * Send an integer response + * Send an integer response. * * @param response the response * @param eventData the modular data @@ -114,7 +114,7 @@ internal class DefaultWidgetPostAPIMediator @Inject constructor(private val mosh } /** - * Send an object response + * Send an object response. * * @param response the response * @param eventData the modular data @@ -133,7 +133,7 @@ internal class DefaultWidgetPostAPIMediator @Inject constructor(private val mosh } /** - * Send success + * Send success. * * @param eventData the modular data */ @@ -143,7 +143,7 @@ internal class DefaultWidgetPostAPIMediator @Inject constructor(private val mosh } /** - * Send an error + * Send an error. * * @param message the error message * @param eventData the modular data @@ -151,7 +151,7 @@ internal class DefaultWidgetPostAPIMediator @Inject constructor(private val mosh override fun sendError(message: String, eventData: JsonDict) { Timber.e("## sendError() : eventData $eventData failed $message") - // TODO: JS has an additional optional parameter: nestedError + // TODO JS has an additional optional parameter: nestedError val params = HashMap>() val subMap = HashMap() subMap["message"] = message @@ -160,7 +160,7 @@ internal class DefaultWidgetPostAPIMediator @Inject constructor(private val mosh } /** - * Send the response to the javascript + * Send the response to the javascript. * * @param jsString the response data * @param eventData the modular data diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt index bfc243c213..b871a317c8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/session/widgets/WidgetsAPI.kt @@ -24,7 +24,7 @@ import retrofit2.http.Query internal interface WidgetsAPI { /** - * register to the server + * Register to the server. * * @param body the body content (Ref: https://github.com/matrix-org/matrix-doc/pull/1961) */ diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Base64.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Base64.kt index aae8bf1967..ea7d75a42c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Base64.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/Base64.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.util /** - * Base64 URL conversion methods + * Base64 URL conversion methods. */ internal fun base64UrlToBase64(base64Url: String): String { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/MathUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/BestChunkSize.kt similarity index 100% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/MathUtils.kt rename to matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/BestChunkSize.kt diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableCoroutine.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableCoroutine.kt index f398ee25d8..74b54943cd 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableCoroutine.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/CancelableCoroutine.kt @@ -24,7 +24,7 @@ internal fun Job.toCancelable(): Cancelable { } /** - * Private, use the extension above + * Private, use the extension above. */ private class CancelableCoroutine(private val job: Job) : Cancelable { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FailureExt.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FailureExt.kt index 8c78feeac3..0d65555707 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FailureExt.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FailureExt.kt @@ -22,7 +22,7 @@ import org.matrix.android.sdk.api.failure.MatrixError import org.matrix.android.sdk.internal.di.MoshiProvider /** - * Try to extract and serialize a MatrixError, or default to localizedMessage + * Try to extract and serialize a MatrixError, or default to localizedMessage. */ internal fun Throwable.toMatrixErrorStr(): String { return (this as? Failure.ServerError) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FileSaver.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FileSaver.kt index 3fcf35c127..1bd704a9e8 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FileSaver.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/FileSaver.kt @@ -21,7 +21,7 @@ import java.io.File import java.io.InputStream /** - * Save an input stream to a file with Okio + * Save an input stream to a file with Okio. */ @WorkerThread internal fun writeToFile(inputStream: InputStream, outputFile: File) { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt index 5994cbcf93..94aa238789 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/JsonCanonicalizer.kt @@ -51,7 +51,7 @@ internal object JsonCanonicalizer { } /** - * Canonicalize a JSON element + * Canonicalize a JSON element. * * @param src the src * @return the canonicalize element diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/SecretKeyAndVersion.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/SecretKeyAndVersion.kt index 40aead5d63..79a1554610 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/SecretKeyAndVersion.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/SecretKeyAndVersion.kt @@ -19,14 +19,15 @@ package org.matrix.android.sdk.internal.util import javax.crypto.SecretKey /** - * Tuple which contains the secret key and the version of Android when the key has been generated + * Tuple which contains the secret key and the version of Android when the key has been generated. */ internal data class SecretKeyAndVersion( /** - * the key + * the key. */ val secretKey: SecretKey, /** - * The android version when the key has been generated + * The android version when the key has been generated. */ - val androidVersionWhenTheKeyHasBeenGenerated: Int) + val androidVersionWhenTheKeyHasBeenGenerated: Int +) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/StringUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/StringUtils.kt index 8a6ec18986..d9fd312a6f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/StringUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/StringUtils.kt @@ -20,7 +20,7 @@ import timber.log.Timber import java.util.Locale /** - * Convert a string to an UTF8 String + * Convert a string to an UTF8 String. * * @param s the string to convert * @return the utf-8 string @@ -36,7 +36,7 @@ internal fun convertToUTF8(s: String): String { } /** - * Convert a string from an UTF8 String + * Convert a string from an UTF8 String. * * @param s the string to convert * @return the utf-16 string @@ -76,7 +76,7 @@ internal fun String.caseInsensitiveFind(subString: String): Boolean { internal val spaceChars = "[\u00A0\u2000-\u200B\u2800\u3000]".toRegex() /** - * Strip all the UTF-8 chars which are actually spaces + * Strip all the UTF-8 chars which are actually spaces. */ internal fun String.replaceSpaceChars(replacement: String = "") = replace(spaceChars, replacement) diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt index d13753b5ee..fbbec1a100 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/UrlUtils.kt @@ -39,7 +39,7 @@ internal fun String.ensureProtocol(): String { } /** - * Ensure string has trailing / + * Ensure string ends with "/", if not empty. */ internal fun String.ensureTrailingSlash(): String { return when { diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/system/BuildVersionSdkIntProvider.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/system/BuildVersionSdkIntProvider.kt index b660796ad8..515656049a 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/system/BuildVersionSdkIntProvider.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/util/system/BuildVersionSdkIntProvider.kt @@ -18,7 +18,7 @@ package org.matrix.android.sdk.internal.util.system internal interface BuildVersionSdkIntProvider { /** - * Return the current version of the Android SDK + * Return the current version of the Android SDK. */ fun get(): Int } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt index a6b398f6f5..0d4a5ac28f 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/wellknown/GetWellknownTask.kt @@ -39,7 +39,7 @@ import javax.net.ssl.HttpsURLConnection internal interface GetWellknownTask : Task { data class Params( /** - * domain, for instance "matrix.org" + * domain, for instance "matrix.org". * the URL will be https://{domain}/.well-known/matrix/client */ val domain: String, @@ -48,7 +48,7 @@ internal interface GetWellknownTask : Task AddPusherWorker(appContext, workerParameters, sessionManager) - CancelGossipRequestWorker::class.java.name -> - CancelGossipRequestWorker(appContext, workerParameters, sessionManager) GetGroupDataWorker::class.java.name -> GetGroupDataWorker(appContext, workerParameters, sessionManager) MultipleEventSendingDispatcherWorker::class.java.name -> @@ -66,12 +60,6 @@ internal class MatrixWorkerFactory @Inject constructor(private val sessionManage RedactEventWorker(appContext, workerParameters, sessionManager) SendEventWorker::class.java.name -> SendEventWorker(appContext, workerParameters, sessionManager) - SendGossipRequestWorker::class.java.name -> - SendGossipRequestWorker(appContext, workerParameters, sessionManager) - SendGossipWorker::class.java.name -> - SendGossipWorker(appContext, workerParameters, sessionManager) - SendVerificationMessageWorker::class.java.name -> - SendVerificationMessageWorker(appContext, workerParameters, sessionManager) SyncWorker::class.java.name -> SyncWorker(appContext, workerParameters, sessionManager) UpdateTrustWorker::class.java.name -> diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionSafeCoroutineWorker.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionSafeCoroutineWorker.kt index 334c4580e9..030f51428b 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionSafeCoroutineWorker.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionSafeCoroutineWorker.kt @@ -69,7 +69,7 @@ internal abstract class SessionSafeCoroutineWorker( abstract fun injectWith(injector: SessionComponent) /** - * Should only return Result.Success for workers added to a unique queue + * Should only return Result.Success for workers added to a unique queue. */ abstract suspend fun doSafeWork(params: PARAM): Result diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionWorkerParams.kt b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionWorkerParams.kt index de36b85660..36d03f7fcf 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionWorkerParams.kt +++ b/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/worker/SessionWorkerParams.kt @@ -18,14 +18,14 @@ package org.matrix.android.sdk.internal.worker /** * Note about the Worker usage: - * The workers we chain, or when using the append strategy, should never return Result.Failure(), else the chain will be broken forever + * The workers we chain, or when using the append strategy, should never return Result.Failure(), else the chain will be broken forever. */ internal interface SessionWorkerParams { val sessionId: String /** * Null when no error occurs. When chaining Workers, first step is to check that there is no lastFailureMessage from the previous workers - * If it is the case, the worker should just transmit the error and shouldn't do anything else + * If it is the case, the worker should just transmit the error and shouldn't do anything else. */ val lastFailureMessage: String? } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/auth/data/VersionsKtTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/auth/data/VersionsKtTest.kt index 088e160950..e1438f4741 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/auth/data/VersionsKtTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/api/auth/data/VersionsKtTest.kt @@ -62,12 +62,12 @@ class VersionsKtTest { Versions(supportedVersions = listOf("r0.6.0")).doesServerSupportThreads() shouldBe false Versions(supportedVersions = listOf("r0.9.1")).doesServerSupportThreads() shouldBe false Versions(supportedVersions = listOf("v1.2.0")).doesServerSupportThreads() shouldBe false - Versions(supportedVersions = listOf("v1.3.0")).doesServerSupportThreads() shouldBe true - Versions(supportedVersions = listOf("v1.3.1")).doesServerSupportThreads() shouldBe true - Versions(supportedVersions = listOf("v1.5.1")).doesServerSupportThreads() shouldBe true + Versions(supportedVersions = listOf("v1.3.0")).doesServerSupportThreads() shouldBe false + Versions(supportedVersions = listOf("v1.3.1")).doesServerSupportThreads() shouldBe false + Versions(supportedVersions = listOf("v1.5.1")).doesServerSupportThreads() shouldBe false Versions(supportedVersions = listOf("r0.6.0"), unstableFeatures = mapOf("org.matrix.msc3440.stable" to true)).doesServerSupportThreads() shouldBe true Versions(supportedVersions = listOf("v1.2.1"), unstableFeatures = mapOf("org.matrix.msc3440.stable" to true)).doesServerSupportThreads() shouldBe true Versions(supportedVersions = listOf("r0.6.0"), unstableFeatures = mapOf("org.matrix.msc3440.stable" to false)).doesServerSupportThreads() shouldBe false - Versions(supportedVersions = listOf("v1.4.0"), unstableFeatures = mapOf("org.matrix.msc3440.stable" to false)).doesServerSupportThreads() shouldBe true + Versions(supportedVersions = listOf("v1.4.0"), unstableFeatures = mapOf("org.matrix.msc3440.stable" to false)).doesServerSupportThreads() shouldBe false } } diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/BinaryStringTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/BinaryStringTest.kt index 5a82052d1a..b7951fcc6e 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/BinaryStringTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/BinaryStringTest.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.MatrixTest class BinaryStringTest : MatrixTest { /** - * I want to put bytes to a String, and vice versa + * I want to put bytes to a String, and vice versa. */ @Test fun testNominalCase() { diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/session/pushers/DefaultAddPusherTaskTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/session/pushers/DefaultAddPusherTaskTest.kt index 31fd86fe65..32b1d44fb9 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/session/pushers/DefaultAddPusherTaskTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/session/pushers/DefaultAddPusherTaskTest.kt @@ -81,7 +81,7 @@ class DefaultAddPusherTaskTest { } @Test - fun `given a persisted push entity and SetPush API fails when adding Pusher then mutates persisted result with Failed registration state and rethrows error`() { + fun `given a persisted push entity and SetPush API fails when adding Pusher then mutates persisted result with Failed registration state and rethrows`() { val realmResult = PusherEntity() monarchy.givenWhereReturns(result = realmResult) pushersAPI.givenSetPusherErrors(SocketException()) diff --git a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/task/CoroutineSequencersTest.kt b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/task/CoroutineSequencersTest.kt index 149b964fd2..0cfd9d97a8 100644 --- a/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/task/CoroutineSequencersTest.kt +++ b/matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/task/CoroutineSequencersTest.kt @@ -16,6 +16,8 @@ package org.matrix.android.sdk.internal.task +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.delay @@ -31,8 +33,8 @@ class CoroutineSequencersTest : MatrixTest { private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() + @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class) @Test - @Suppress("EXPERIMENTAL_API_USAGE") fun sequencer_should_run_sequential() { val sequencer = SemaphoreCoroutineSequencer() val results = ArrayList() @@ -60,8 +62,8 @@ class CoroutineSequencersTest : MatrixTest { assertEquals(results[2], "#3") } + @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class) @Test - @Suppress("EXPERIMENTAL_API_USAGE") fun sequencer_should_run_parallel() { val sequencer1 = SemaphoreCoroutineSequencer() val sequencer2 = SemaphoreCoroutineSequencer() @@ -87,8 +89,8 @@ class CoroutineSequencersTest : MatrixTest { assertEquals(3, results.size) } + @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class) @Test - @Suppress("EXPERIMENTAL_API_USAGE") fun sequencer_should_jump_to_next_when_current_job_canceled() { val sequencer = SemaphoreCoroutineSequencer() val results = ArrayList() diff --git a/tools/check/check_code_quality.sh b/tools/check/check_code_quality.sh index e40d3635e8..910616176c 100755 --- a/tools/check/check_code_quality.sh +++ b/tools/check/check_code_quality.sh @@ -67,6 +67,9 @@ echo "Search for forbidden patterns in code..." ${searchForbiddenStringsScript} ./tools/check/forbidden_strings_in_code.txt \ ./matrix-sdk-android/src/main/java \ ./matrix-sdk-android-flow/src/main/java \ + ./library/core-utils/src/main/java \ + ./library/jsonviewer/src/main/java \ + ./library/ui-styles/src/main/java \ ./vector/src/main/java \ ./vector/src/debug/java \ ./vector/src/release/java \ @@ -100,6 +103,7 @@ echo echo "Search for forbidden patterns in resources..." ${searchForbiddenStringsScript} ./tools/check/forbidden_strings_in_resources.txt \ + ./library/ui-styles/src/main/res/values \ ./vector/src/main/res/color \ ./vector/src/main/res/layout \ ./vector/src/main/res/values \ diff --git a/tools/check/forbidden_strings_in_code.txt b/tools/check/forbidden_strings_in_code.txt index 393e942b2a..7362ff2d10 100755 --- a/tools/check/forbidden_strings_in_code.txt +++ b/tools/check/forbidden_strings_in_code.txt @@ -60,7 +60,7 @@ private short final short ### Line length is limited to 160 chars. Please split long lines -[^─]{161} +#[^─]{161} ### "DO NOT COMMIT" has been committed DO NOT COMMIT diff --git a/tools/detekt/detekt.yml b/tools/detekt/detekt.yml new file mode 100644 index 0000000000..322f29e5b7 --- /dev/null +++ b/tools/detekt/detekt.yml @@ -0,0 +1,97 @@ +# Default rules: https://github.com/detekt/detekt/blob/main/detekt-core/src/main/resources/default-detekt-config.yml + +style: + MaxLineLength: + # Default is 120 + maxLineLength: 160 + MagicNumber: + active: false + ReturnCount: + active: false + UnnecessaryAbstractClass: + active: false + FunctionOnlyReturningConstant: + active: false + UnusedPrivateMember: + # TODO Enable it + active: false + ThrowsCount: + active: false + LoopWithTooManyJumpStatements: + active: false + SerialVersionUIDInSerializableClass: + active: false + ProtectedMemberInFinalClass: + active: false + +empty-blocks: + EmptyFunctionBlock: + active: false + EmptySecondaryConstructor: + active: false + +potential-bugs: + ImplicitDefaultLocale: + active: false + +exceptions: + TooGenericExceptionCaught: + active: false + SwallowedException: + active: false + ThrowingExceptionsWithoutMessageOrCause: + active: false + TooGenericExceptionThrown: + active: false + +complexity: + TooManyFunctions: + active: false + LongMethod: + active: false + LongParameterList: + active: false + ComplexMethod: + active: false + NestedBlockDepth: + active: false + ComplexCondition: + active: false + LargeClass: + active: false + +naming: + VariableNaming: + # TODO Enable it + active: false + TopLevelPropertyNaming: + # TODO Enable it + active: false + +performance: + SpreadOperator: + active: false + +# Note: all rules for `comments` are disabled by default, but I put them here to be aware of their existence +comments: + AbsentOrWrongFileLicense: + active: false + licenseTemplateFile: 'license.template' + licenseTemplateIsRegex: false + CommentOverPrivateFunction: + active: false + CommentOverPrivateProperty: + active: false + DeprecatedBlockTag: + active: true + EndOfSentenceFormat: + active: true + OutdatedDocumentation: + # TODO Enable it + active: false + UndocumentedPublicClass: + active: false + UndocumentedPublicFunction: + active: false + UndocumentedPublicProperty: + active: false diff --git a/tools/templates/ElementFeature/root/src/app_package/Activity.kt.ftl b/tools/templates/ElementFeature/root/src/app_package/Activity.kt.ftl index a5c097065e..de63de6c06 100644 --- a/tools/templates/ElementFeature/root/src/app_package/Activity.kt.ftl +++ b/tools/templates/ElementFeature/root/src/app_package/Activity.kt.ftl @@ -8,7 +8,7 @@ import im.vector.app.core.extensions.addFragment import im.vector.app.core.platform.ToolbarConfigurable import im.vector.app.core.platform.VectorBaseActivity -//TODO: add this activity to manifest +//TODO add this activity to manifest class ${activityClass} : VectorBaseActivity(), ToolbarConfigurable { companion object { diff --git a/tools/templates/ElementFeature/root/src/app_package/Fragment.kt.ftl b/tools/templates/ElementFeature/root/src/app_package/Fragment.kt.ftl index 38f8132d24..0f01b347c0 100644 --- a/tools/templates/ElementFeature/root/src/app_package/Fragment.kt.ftl +++ b/tools/templates/ElementFeature/root/src/app_package/Fragment.kt.ftl @@ -18,7 +18,7 @@ import javax.inject.Inject data class ${fragmentArgsClass}() : Parcelable -//TODO: add this fragment into FragmentModule +//TODO add this fragment into FragmentModule class ${fragmentClass} @Inject constructor( private val viewModelFactory: ${viewModelClass}.Factory ) : VectorBaseFragment(), ${viewModelClass}.Factory by viewModelFactory { diff --git a/vector-config/src/main/res/values/config-settings.xml b/vector-config/src/main/res/values/config-settings.xml index 0a4da4c98e..b2cd21c3de 100755 --- a/vector-config/src/main/res/values/config-settings.xml +++ b/vector-config/src/main/res/values/config-settings.xml @@ -38,7 +38,8 @@ false - + true + false diff --git a/vector/build.gradle b/vector/build.gradle index 7112fa98e0..4ae6527e0b 100644 --- a/vector/build.gradle +++ b/vector/build.gradle @@ -7,18 +7,31 @@ apply plugin: 'kotlin-parcelize' apply plugin: 'kotlin-kapt' apply plugin: 'com.likethesalad.stem' apply plugin: 'dagger.hilt.android.plugin' +apply plugin: 'kotlinx-knit' kapt { correctErrorTypes = true } +knit { + files = fileTree(project.rootDir) { + include '**/*.md' + include '**/*.kt' + include '**/*.kts' + exclude '**/build/**' + exclude '**/.gradle/**' + exclude '**/towncrier/template.md' + exclude '**/CHANGES.md' + } +} + // Note: 2 digits max for each value ext.versionMajor = 1 ext.versionMinor = 4 // Note: even values are reserved for regular release, odd values for hotfix release. // When creating a hotfix, you should decrease the value, since the current value // is the value for the next regular release. -ext.versionPatch = 16 +ext.versionPatch = 18 static def getGitTimestamp() { def cmd = 'git show -s --format=%ct' @@ -297,14 +310,14 @@ android { kotlinOptions { jvmTarget = "11" freeCompilerArgs += [ - "-Xopt-in=kotlin.RequiresOptIn", + "-opt-in=kotlin.RequiresOptIn", // Fixes false positive "This is an internal Mavericks API. It is not intended for external use." // of MvRx `by viewModel()` calls. Maybe due to the inlining of code... This is a temporary fix... - "-Xopt-in=com.airbnb.mvrx.InternalMavericksApi", + "-opt-in=com.airbnb.mvrx.InternalMavericksApi", // Opt in for kotlinx.coroutines.FlowPreview too - "-Xopt-in=kotlinx.coroutines.FlowPreview", + "-opt-in=kotlinx.coroutines.FlowPreview", // Opt in for kotlinx.coroutines.ExperimentalCoroutinesApi too - "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", + "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", ] } @@ -439,9 +452,6 @@ dependencies { kapt libs.github.glideCompiler implementation 'com.github.yalantis:ucrop:2.2.8' - // Badge for compatibility - implementation 'me.leolin:ShortcutBadger:1.1.22@aar' - // Chat effects implementation 'nl.dionsegijn:konfetti-xml:2.0.2' diff --git a/vector/lint.xml b/vector/lint.xml index e219ac1eed..d9ca761e7a 100644 --- a/vector/lint.xml +++ b/vector/lint.xml @@ -1,5 +1,9 @@ + + + + diff --git a/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt b/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt index 47e1e43be3..6ac3226674 100644 --- a/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt +++ b/vector/src/androidTest/java/im/vector/app/VerificationTestBase.kt @@ -19,6 +19,7 @@ package im.vector.app import android.net.Uri import androidx.lifecycle.Observer import im.vector.app.ui.robot.OnboardingRobot +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch @@ -107,7 +108,7 @@ abstract class VerificationTestBase { return result!! } - @Suppress("EXPERIMENTAL_API_USAGE") + @OptIn(DelicateCoroutinesApi::class) private fun syncSession(session: Session) { val lock = CountDownLatch(1) diff --git a/vector/src/androidTest/java/im/vector/app/core/utils/TestMatrixHelper.kt b/vector/src/androidTest/java/im/vector/app/core/utils/TestMatrixHelper.kt index 322f5fa23d..48fc1343b1 100644 --- a/vector/src/androidTest/java/im/vector/app/core/utils/TestMatrixHelper.kt +++ b/vector/src/androidTest/java/im/vector/app/core/utils/TestMatrixHelper.kt @@ -26,5 +26,5 @@ fun getMatrixInstance(): Matrix { val configuration = MatrixConfiguration( roomDisplayNameFallbackProvider = VectorRoomDisplayNameFallbackProvider(context) ) - return Matrix.createInstance(context, configuration) + return Matrix(context, configuration) } diff --git a/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt b/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt index 3c5de8b221..b9292bd916 100644 --- a/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt +++ b/vector/src/androidTest/java/im/vector/app/ui/robot/ElementRobot.kt @@ -120,6 +120,26 @@ class ElementRobot { .perform(ViewActions.closeSoftKeyboard(), click()) } } + // at this point we are in a race with the app restarting. The steps that happen are: + // - (initially) app has started, app has initial synched + // - (restart) app has strted, app has not initial synched + // - (racey) app shows some UI but overlays with initial sync ui + // - (initial sync finishes) app has started, has initial synched + + // We need to wait for the initial sync to complete; but we can't + // use waitForHome() like login does. + + // waitForHome() -- does not work because we have already fufilled the initialSync + // so we can racily have an IllegalStateException that we have transitioned from busy -> idle + // but never having sent the signal. + + // So we need to not start waiting for an initial sync until we have restarted + // then we do need to wait for the sync to complete. + + // Which is convoluted especially as it involves the app state refreshing + // so; in order to make this be more stable + // I hereby cheat and write: + Thread.sleep(30_000) } else -> { } diff --git a/vector/src/androidTest/java/im/vector/app/ui/robot/space/SpaceMenuRobot.kt b/vector/src/androidTest/java/im/vector/app/ui/robot/space/SpaceMenuRobot.kt index 4d35e3c550..289c6e21b4 100644 --- a/vector/src/androidTest/java/im/vector/app/ui/robot/space/SpaceMenuRobot.kt +++ b/vector/src/androidTest/java/im/vector/app/ui/robot/space/SpaceMenuRobot.kt @@ -104,11 +104,10 @@ class SpaceMenuRobot { fun leaveSpace() { clickOnSheet(R.id.leaveSpace) - waitUntilDialogVisible(ViewMatchers.withId(R.id.leaveButton)) - clickOn(R.id.leave_selected) waitUntilActivityVisible { waitUntilViewVisible(ViewMatchers.withId(R.id.roomList)) } + clickOn(R.id.spaceLeaveSelectAll) clickOn(R.id.spaceLeaveButton) waitUntilViewVisible(ViewMatchers.withId(R.id.groupListView)) } diff --git a/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt b/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt index b62520278a..a7d814052a 100755 --- a/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt +++ b/vector/src/gplay/java/im/vector/app/gplay/push/fcm/VectorFirebaseMessagingService.kt @@ -1,15 +1,12 @@ /* * Copyright 2019 New Vector Ltd * - * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * * http://www.apache.org/licenses/LICENSE-2.0 * - * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +29,6 @@ import im.vector.app.BuildConfig import im.vector.app.core.di.ActiveSessionHolder import im.vector.app.core.network.WifiDetector import im.vector.app.core.pushers.PushersManager -import im.vector.app.features.badge.BadgeProxy import im.vector.app.features.notifications.NotifiableEventResolver import im.vector.app.features.notifications.NotificationDrawerManager import im.vector.app.features.notifications.NotificationUtils @@ -152,10 +148,6 @@ class VectorFirebaseMessagingService : FirebaseMessagingService() { Timber.tag(loggerTag.value).d("## onMessageReceivedInternal()") } - // update the badge counter - val unreadCount = data["unread"]?.let { Integer.parseInt(it) } ?: 0 - BadgeProxy.updateBadgeCount(applicationContext, unreadCount) - val session = activeSessionHolder.getSafeActiveSession() if (session == null) { diff --git a/vector/src/main/assets/open_source_licenses.html b/vector/src/main/assets/open_source_licenses.html index 0bead1f826..8f27776fbf 100755 --- a/vector/src/main/assets/open_source_licenses.html +++ b/vector/src/main/assets/open_source_licenses.html @@ -369,11 +369,6 @@ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright 2012 Square, Inc. -
  • - ShortcutBadger -
    - Copyright 2014 Leo Lin -
  • diff-match-patch
    diff --git a/vector/src/main/java/im/vector/app/VectorApplication.kt b/vector/src/main/java/im/vector/app/VectorApplication.kt index 0bf4eb13b6..a55351f74b 100644 --- a/vector/src/main/java/im/vector/app/VectorApplication.kt +++ b/vector/src/main/java/im/vector/app/VectorApplication.kt @@ -224,7 +224,7 @@ class VectorApplication : override fun getWorkManagerConfiguration(): WorkConfiguration { return WorkConfiguration.Builder() - .setWorkerFactory(matrix.workerFactory()) + .setWorkerFactory(matrix.getWorkerFactory()) .setExecutor(Executors.newCachedThreadPool()) .build() } diff --git a/vector/src/main/java/im/vector/app/core/datastore/DataStoreProvider.kt b/vector/src/main/java/im/vector/app/core/datastore/DataStoreProvider.kt index 5b7988b76f..3c93b9a7e0 100644 --- a/vector/src/main/java/im/vector/app/core/datastore/DataStoreProvider.kt +++ b/vector/src/main/java/im/vector/app/core/datastore/DataStoreProvider.kt @@ -26,12 +26,12 @@ import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** - * Provides a singleton datastore cache - * allows for lazily fetching a datastore instance by key to avoid creating multiple stores for the same file - * Based on https://androidx.tech/artifacts/datastore/datastore-preferences/1.0.0-source/androidx/datastore/preferences/PreferenceDataStoreDelegate.kt.html + * Provides a singleton datastore cache. + * Allows for lazily fetching a datastore instance by key to avoid creating multiple stores for the same file. + * Based on https://androidx.tech/artifacts/datastore/datastore-preferences/1.0.0-source/androidx/datastore/preferences/PreferenceDataStoreDelegate.kt.html. * - * Makes use of a ReadOnlyProperty in order to provide a simplified api on top of a Context - * ReadOnlyProperty allows us to lazily access the backing property instead of requiring it upfront as a dependency + * Makes use of a ReadOnlyProperty in order to provide a simplified api on top of a Context. + * ReadOnlyProperty allows us to lazily access the backing property instead of requiring it upfront as a dependency. *
      * val Context.dataStoreProvider by dataStoreProvider()
      * 
    diff --git a/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt b/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt index 029fce7423..b3bd671583 100644 --- a/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt +++ b/vector/src/main/java/im/vector/app/core/date/VectorDateFormatter.kt @@ -143,7 +143,7 @@ class VectorDateFormatter @Inject constructor( } /** - * This method will show date and time with a preposition + * This method will show date and time with a preposition. */ private fun formatDateAndTime(ts: Long): String { val date = DateProvider.toLocalDateTime(ts) @@ -157,7 +157,7 @@ class VectorDateFormatter @Inject constructor( } /** - * We are using this method for the keywords Today/Yesterday + * We are using this method for the keywords Today/Yesterday. */ private fun getRelativeDay(ts: Long): String { return DateUtils.getRelativeTimeSpanString( diff --git a/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt b/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt index 4883676f87..983850e3be 100644 --- a/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt +++ b/vector/src/main/java/im/vector/app/core/di/ActiveSessionHolder.kt @@ -87,7 +87,7 @@ class ActiveSessionHolder @Inject constructor(private val activeSessionDataSourc ?: throw IllegalStateException("You should authenticate before using this") } - // TODO: Stop sync ? + // TODO Stop sync ? // fun switchToSession(sessionParams: SessionParams) { // val newActiveSession = authenticationService.getSession(sessionParams) // activeSession.set(newActiveSession) diff --git a/vector/src/main/java/im/vector/app/core/di/FragmentModule.kt b/vector/src/main/java/im/vector/app/core/di/FragmentModule.kt index e3e64063f3..c68a35f4e5 100644 --- a/vector/src/main/java/im/vector/app/core/di/FragmentModule.kt +++ b/vector/src/main/java/im/vector/app/core/di/FragmentModule.kt @@ -189,7 +189,7 @@ import im.vector.app.features.widgets.WidgetFragment @Module interface FragmentModule { /** - * Fragments with @IntoMap will be injected by this factory + * Fragments with @IntoMap will be injected by this factory. */ @Binds fun bindFragmentFactory(factory: VectorFragmentFactory): FragmentFactory diff --git a/vector/src/main/java/im/vector/app/core/di/ImageManager.kt b/vector/src/main/java/im/vector/app/core/di/ImageManager.kt index 60ce70a0b3..1b2ec5b93a 100644 --- a/vector/src/main/java/im/vector/app/core/di/ImageManager.kt +++ b/vector/src/main/java/im/vector/app/core/di/ImageManager.kt @@ -28,7 +28,7 @@ import java.io.InputStream import javax.inject.Inject /** - * This class is used to configure the library we use for images + * This class is used to configure the library we use for images. */ class ImageManager @Inject constructor( private val context: Context, diff --git a/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt b/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt index 0db7e4e8ea..2945ae7d87 100644 --- a/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt +++ b/vector/src/main/java/im/vector/app/core/di/SingletonModule.kt @@ -50,6 +50,7 @@ import im.vector.app.features.settings.VectorPreferences import im.vector.app.features.ui.SharedPreferencesUiStateRepository import im.vector.app.features.ui.UiStateRepository import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.SupervisorJob @@ -128,12 +129,12 @@ object VectorStaticModule { @Provides @Singleton fun providesMatrix(context: Context, configuration: MatrixConfiguration): Matrix { - return Matrix.createInstance(context, configuration) + return Matrix(context, configuration) } @Provides fun providesCurrentSession(activeSessionHolder: ActiveSessionHolder): Session { - // TODO: handle session injection better + // TODO handle session injection better return activeSessionHolder.getActiveSession() } @@ -173,7 +174,7 @@ object VectorStaticModule { return CoroutineDispatchers(io = Dispatchers.IO, computation = Dispatchers.Default) } - @Suppress("EXPERIMENTAL_API_USAGE") + @OptIn(DelicateCoroutinesApi::class) @Provides @NamedGlobalScope fun providesGlobalScope(): CoroutineScope { diff --git a/vector/src/main/java/im/vector/app/core/di/ViewModelModule.kt b/vector/src/main/java/im/vector/app/core/di/ViewModelModule.kt index 4f8329c026..d90e934d0a 100644 --- a/vector/src/main/java/im/vector/app/core/di/ViewModelModule.kt +++ b/vector/src/main/java/im/vector/app/core/di/ViewModelModule.kt @@ -49,7 +49,7 @@ import im.vector.app.features.userdirectory.UserListSharedActionViewModel interface ViewModelModule { /** - * ViewModels with @IntoMap will be injected by this factory + * ViewModels with @IntoMap will be injected by this factory. */ @Binds fun bindViewModelFactory(factory: VectorViewModelFactory): ViewModelProvider.Factory diff --git a/vector/src/main/java/im/vector/app/core/dialogs/DialogLocker.kt b/vector/src/main/java/im/vector/app/core/dialogs/DialogLocker.kt index 51a513e11e..d4efbf1388 100644 --- a/vector/src/main/java/im/vector/app/core/dialogs/DialogLocker.kt +++ b/vector/src/main/java/im/vector/app/core/dialogs/DialogLocker.kt @@ -25,7 +25,7 @@ import timber.log.Timber private const val KEY_DIALOG_IS_DISPLAYED = "DialogLocker.KEY_DIALOG_IS_DISPLAYED" /** - * Class to avoid displaying twice the same dialog + * Class to avoid displaying twice the same dialog. */ class DialogLocker(savedInstanceState: Bundle?) : Restorable { diff --git a/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt b/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt index b594dbcac4..c43b2e4f09 100644 --- a/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt +++ b/vector/src/main/java/im/vector/app/core/dialogs/UnrecognizedCertificateDialog.kt @@ -26,7 +26,7 @@ import timber.log.Timber import javax.inject.Inject /** - * This class displays the unknown certificate dialog + * This class displays the unknown certificate dialog. */ class UnrecognizedCertificateDialog @Inject constructor( private val activeSessionHolder: ActiveSessionHolder, @@ -37,7 +37,7 @@ class UnrecognizedCertificateDialog @Inject constructor( /** * Display a certificate dialog box, asking the user about an unknown certificate - * To use when user is currently logged in + * To use when user is currently logged in. * * @param unrecognizedFingerprint the fingerprint for the unknown certificate * @param callback callback to fire when the user makes a decision @@ -60,7 +60,7 @@ class UnrecognizedCertificateDialog @Inject constructor( } /** - * To use during login flow + * To use during login flow. */ fun show(activity: Activity, unrecognizedFingerprint: Fingerprint, @@ -78,7 +78,7 @@ class UnrecognizedCertificateDialog @Inject constructor( } /** - * Display a certificate dialog box, asking the user about an unknown certificate + * Display a certificate dialog box, asking the user about an unknown certificate. * * @param unrecognizedFingerprint the fingerprint for the unknown certificate * @param existing the current session already exist, so it mean that something has changed server side @@ -167,17 +167,17 @@ class UnrecognizedCertificateDialog @Inject constructor( interface Callback { /** - * The certificate was explicitly accepted + * The certificate was explicitly accepted. */ fun onAccept() /** - * The warning was ignored by the user + * The warning was ignored by the user. */ fun onIgnore() /** - * The unknown certificate was explicitly rejected + * The unknown certificate was explicitly rejected. */ fun onReject() } diff --git a/vector/src/main/java/im/vector/app/core/epoxy/Listener.kt b/vector/src/main/java/im/vector/app/core/epoxy/Listener.kt index 4d8f7b3a1c..178728f144 100644 --- a/vector/src/main/java/im/vector/app/core/epoxy/Listener.kt +++ b/vector/src/main/java/im/vector/app/core/epoxy/Listener.kt @@ -21,7 +21,7 @@ import android.widget.TextView import im.vector.app.core.utils.DebouncedClickListener /** - * View.OnClickListener lambda + * View.OnClickListener lambda. */ typealias ClickListener = (View) -> Unit @@ -46,7 +46,7 @@ fun TextView.onLongClickIgnoringLinks(listener: View.OnLongClickListener?) { } /** - * Infer that a Clickable span has been click by the presence of a selection + * Infer that a Clickable span has been click by the presence of a selection. */ private fun hasLongPressedLink() = selectionStart != -1 || selectionEnd != -1 }) @@ -54,6 +54,6 @@ fun TextView.onLongClickIgnoringLinks(listener: View.OnLongClickListener?) { } /** - * Simple Text listener lambda + * Simple Text listener lambda. */ typealias TextListener = (String) -> Unit diff --git a/vector/src/main/java/im/vector/app/core/epoxy/VectorEpoxyModel.kt b/vector/src/main/java/im/vector/app/core/epoxy/VectorEpoxyModel.kt index 6142748bf4..9bd16b09a3 100644 --- a/vector/src/main/java/im/vector/app/core/epoxy/VectorEpoxyModel.kt +++ b/vector/src/main/java/im/vector/app/core/epoxy/VectorEpoxyModel.kt @@ -25,7 +25,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelChildren /** - * EpoxyModelWithHolder which can listen to visibility state change + * EpoxyModelWithHolder which can listen to visibility state change. */ abstract class VectorEpoxyModel : EpoxyModelWithHolder() { diff --git a/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt b/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt index 129491fe15..da9a63d4c0 100644 --- a/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt +++ b/vector/src/main/java/im/vector/app/core/error/ResourceLimitErrorFormatter.kt @@ -59,7 +59,7 @@ class ResourceLimitErrorFormatter(private val context: Context) { } /** - * Create a HTML link with a uri + * Create a HTML link with a uri. */ private fun uriAsLink(uri: String): String { val contactStr = context.getString(R.string.resource_limit_contact_admin) diff --git a/vector/src/main/java/im/vector/app/core/extensions/BasicExtensions.kt b/vector/src/main/java/im/vector/app/core/extensions/BasicExtensions.kt index f8b8b83178..63d61af0e6 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/BasicExtensions.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/BasicExtensions.kt @@ -26,12 +26,17 @@ fun Boolean.toOnOff() = if (this) "ON" else "OFF" inline fun T.ooi(block: (T) -> Unit): T = also(block) /** - * Check if a CharSequence is an email + * Check if a CharSequence is an email. */ fun CharSequence.isEmail() = Patterns.EMAIL_ADDRESS.matcher(this).matches() /** - * Check if a CharSequence is a phone number + * Return empty CharSequence if the CharSequence is null. + */ +fun CharSequence?.orEmpty() = this ?: "" + +/** + * Check if a CharSequence is a phone number. */ fun CharSequence.isMsisdn(): Boolean { return try { @@ -48,7 +53,7 @@ fun CharSequence.isMsisdn(): Boolean { * - "file.txt".insertBeforeLast("_foo") will return "file_foo.txt" * - "file".insertBeforeLast("_foo") will return "file_foo" * - "fi.le.txt".insertBeforeLast("_foo") will return "fi.le_foo.txt" - * - null.insertBeforeLast("_foo") will return "_foo" + * - null.insertBeforeLast("_foo") will return "_foo". */ fun String?.insertBeforeLast(insert: String, delimiter: String = "."): String { if (this == null) return insert diff --git a/vector/src/main/java/im/vector/app/core/extensions/Fragment.kt b/vector/src/main/java/im/vector/app/core/extensions/Fragment.kt index a26597809b..dfbd2eba97 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/Fragment.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/Fragment.kt @@ -158,7 +158,7 @@ fun Fragment.addChildFragmentToBackstack( } /** - * Return a list of all child Fragments, recursively + * Return a list of all child Fragments, recursively. */ fun Fragment.getAllChildFragments(): List { return listOf(this) + childFragmentManager.fragments.map { it.getAllChildFragments() }.flatten() diff --git a/vector/src/main/java/im/vector/app/core/extensions/Iterable.kt b/vector/src/main/java/im/vector/app/core/extensions/Iterable.kt index 56a9bbe39f..6eba204f8a 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/Iterable.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/Iterable.kt @@ -36,7 +36,7 @@ inline fun > Iterable.lastMinBy(selector: (T) -> R): T? } /** - * Call each for each item, and between between each items + * Call each for each item, and between between each items. */ inline fun Collection.join(each: (Int, T) -> Unit, between: (Int, T) -> Unit) { val lastIndex = size - 1 diff --git a/vector/src/main/java/im/vector/app/core/extensions/MvRxExtension.kt b/vector/src/main/java/im/vector/app/core/extensions/MvRxExtension.kt index 9daf16a589..26b3e552f9 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/MvRxExtension.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/MvRxExtension.kt @@ -21,7 +21,7 @@ import com.airbnb.mvrx.Fail import com.airbnb.mvrx.Success /** - * It maybe already exist somewhere but I cannot find it + * It maybe already exist somewhere but I cannot find it. */ suspend fun tryAsync(block: suspend () -> T): Async { return try { diff --git a/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt b/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt index 84cce10d92..eeb5ddce03 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/RecyclerView.kt @@ -25,7 +25,7 @@ import com.airbnb.epoxy.EpoxyController import com.airbnb.epoxy.EpoxyVisibilityTracker /** - * Apply a Vertical LinearLayout Manager to the recyclerView and set the adapter from the epoxy controller + * Apply a Vertical LinearLayout Manager to the recyclerView and set the adapter from the epoxy controller. */ fun RecyclerView.configureWith(epoxyController: EpoxyController, itemAnimator: RecyclerView.ItemAnimator? = null, @@ -57,7 +57,7 @@ fun RecyclerView.configureWith(epoxyController: EpoxyController, } /** - * To call from Fragment.onDestroyView() + * To call from Fragment.onDestroyView(). */ fun RecyclerView.cleanup() { adapter = null diff --git a/vector/src/main/java/im/vector/app/core/extensions/Session.kt b/vector/src/main/java/im/vector/app/core/extensions/Session.kt index 9bc1aff868..1884909906 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/Session.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/Session.kt @@ -62,7 +62,7 @@ fun Session.startSyncing(context: Context) { } /** - * Tell is the session has unsaved e2e keys in the backup + * Tell is the session has unsaved e2e keys in the backup. */ fun Session.hasUnsavedKeys(): Boolean { return cryptoService().inboundGroupSessionsCount(false) > 0 && diff --git a/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt b/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt index 4347da71f0..d9b92e78b7 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/TextInputLayout.kt @@ -23,7 +23,7 @@ import reactivecircus.flowbinding.android.widget.textChanges fun TextInputLayout.editText() = this.editText!! /** - * Detect if a field starts or ends with spaces + * Detect if a field starts or ends with spaces. */ fun TextInputLayout.hasSurroundingSpaces() = editText().text.toString().let { it.trim() != it } diff --git a/vector/src/main/java/im/vector/app/core/extensions/TextView.kt b/vector/src/main/java/im/vector/app/core/extensions/TextView.kt index 0564f2055b..7d8b60ed58 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/TextView.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/TextView.kt @@ -38,7 +38,7 @@ import im.vector.app.core.utils.copyToClipboard import im.vector.app.features.themes.ThemeUtils /** - * Set a text in the TextView, or set visibility to GONE if the text is null + * Set a text in the TextView, or set visibility to GONE if the text is null. */ fun TextView.setTextOrHide(newText: CharSequence?, hideWhenBlank: Boolean = true, vararg relatedViews: View = emptyArray()) { if (newText == null || @@ -53,7 +53,7 @@ fun TextView.setTextOrHide(newText: CharSequence?, hideWhenBlank: Boolean = true } /** - * Set text with a colored part + * Set text with a colored part. * @param fullTextRes the resource id of the full text. Value MUST contains a parameter for string, which will be replaced by the colored part * @param coloredTextRes the resource id of the colored part of the text * @param colorAttribute attribute of the color. Default to colorPrimary @@ -73,7 +73,7 @@ fun TextView.setTextWithColoredPart(@StringRes fullTextRes: Int, } /** - * Set text with a colored part + * Set text with a colored part. * @param fullText The full text. * @param coloredPart The colored part of the text * @param colorAttribute attribute of the color. Default to colorPrimary @@ -134,7 +134,7 @@ fun TextView.clearDrawables() { } /** - * Set long click listener to copy the current text of the TextView to the clipboard and show a Snackbar + * Set long click listener to copy the current text of the TextView to the clipboard and show a Snackbar. */ fun TextView.copyOnLongClick() { setOnLongClickListener { view -> diff --git a/vector/src/main/java/im/vector/app/core/extensions/UrlExtensions.kt b/vector/src/main/java/im/vector/app/core/extensions/UrlExtensions.kt index 749da0d987..e1e745e399 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/UrlExtensions.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/UrlExtensions.kt @@ -17,7 +17,7 @@ package im.vector.app.core.extensions /** - * Ex: "https://matrix.org/" -> "matrix.org" + * Ex: "https://matrix.org/" -> "matrix.org". */ fun String?.toReducedUrl(keepSchema: Boolean = false): String { return (this ?: "") diff --git a/vector/src/main/java/im/vector/app/core/extensions/ViewExtensions.kt b/vector/src/main/java/im/vector/app/core/extensions/ViewExtensions.kt index f9ca8cb57c..625ff15ef7 100644 --- a/vector/src/main/java/im/vector/app/core/extensions/ViewExtensions.kt +++ b/vector/src/main/java/im/vector/app/core/extensions/ViewExtensions.kt @@ -33,7 +33,7 @@ import im.vector.app.R import im.vector.app.features.themes.ThemeUtils /** - * Remove left margin of a SearchView + * Remove left margin of a SearchView. */ fun SearchView.withoutLeftMargin() { (findViewById(R.id.search_edit_frame))?.let { diff --git a/vector/src/main/java/im/vector/app/core/files/FileSaver.kt b/vector/src/main/java/im/vector/app/core/files/FileSaver.kt index 406fa76520..d0f2247f33 100644 --- a/vector/src/main/java/im/vector/app/core/files/FileSaver.kt +++ b/vector/src/main/java/im/vector/app/core/files/FileSaver.kt @@ -32,7 +32,7 @@ import timber.log.Timber import java.io.File /** - * Save a string to a file with Okio + * Save a string to a file with Okio. */ @WorkerThread fun writeToFile(str: String, file: File): Try { @@ -44,7 +44,7 @@ fun writeToFile(str: String, file: File): Try { } /** - * Save a byte array to a file with Okio + * Save a byte array to a file with Okio. */ @WorkerThread fun writeToFile(data: ByteArray, file: File): Try { diff --git a/vector/src/main/java/im/vector/app/core/hardware/HardwareInfo.kt b/vector/src/main/java/im/vector/app/core/hardware/HardwareInfo.kt index a9aa7be267..8f8e37f9a3 100644 --- a/vector/src/main/java/im/vector/app/core/hardware/HardwareInfo.kt +++ b/vector/src/main/java/im/vector/app/core/hardware/HardwareInfo.kt @@ -29,7 +29,7 @@ class HardwareInfo @Inject constructor( private val context: Context ) { /** - * Tell if the device has a back (or external) camera + * Tell if the device has a back (or external) camera. */ fun hasBackCamera(): Boolean { val manager = context.getSystemService() ?: return Camera.getNumberOfCameras() > 0 diff --git a/vector/src/main/java/im/vector/app/core/intent/ExternalIntentAnalyser.kt b/vector/src/main/java/im/vector/app/core/intent/ExternalIntentData.kt similarity index 97% rename from vector/src/main/java/im/vector/app/core/intent/ExternalIntentAnalyser.kt rename to vector/src/main/java/im/vector/app/core/intent/ExternalIntentData.kt index 0d18f808fb..142a7a6782 100644 --- a/vector/src/main/java/im/vector/app/core/intent/ExternalIntentAnalyser.kt +++ b/vector/src/main/java/im/vector/app/core/intent/ExternalIntentData.kt @@ -23,7 +23,7 @@ import android.net.Uri import androidx.core.util.PatternsCompat.WEB_URL /** - * Inspired from Riot code: RoomMediaMessage.java + * Inspired from Riot code: RoomMediaMessage.java. */ sealed class ExternalIntentData { /** @@ -42,7 +42,7 @@ sealed class ExternalIntentData { ) : ExternalIntentData() /** - * Clip data + * Clip data. */ data class IntentDataClipData( val clipDataItem: ClipData.Item, @@ -50,7 +50,7 @@ sealed class ExternalIntentData { ) : ExternalIntentData() /** - * Constructor from a media Uri/ + * Constructor from a media Uri/. * * @param uri the media uri * @param filename the media file name diff --git a/vector/src/main/java/im/vector/app/core/linkify/VectorAutoLinkPatterns.kt b/vector/src/main/java/im/vector/app/core/linkify/VectorAutoLinkPatterns.kt index b9fab37e43..d98c280f78 100644 --- a/vector/src/main/java/im/vector/app/core/linkify/VectorAutoLinkPatterns.kt +++ b/vector/src/main/java/im/vector/app/core/linkify/VectorAutoLinkPatterns.kt @@ -16,7 +16,7 @@ package im.vector.app.core.linkify /** - * Better support for geo URi + * Better support for geo URI. */ object VectorAutoLinkPatterns { diff --git a/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt b/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt index 0906b398c5..d2184d9bd7 100644 --- a/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt +++ b/vector/src/main/java/im/vector/app/core/linkify/VectorLinkify.kt @@ -22,7 +22,7 @@ import androidx.core.text.util.LinkifyCompat object VectorLinkify { /** - * Better support for auto link than the default implementation + * Better support for auto link than the default implementation. */ fun addLinks(spannable: Spannable, keepExistingUrlSpan: Boolean = false) { // we might want to modify some matches diff --git a/vector/src/main/java/im/vector/app/core/mvrx/ResultExtension.kt b/vector/src/main/java/im/vector/app/core/mvrx/ResultExtension.kt index dfd04ea6f6..4cd68f03ca 100644 --- a/vector/src/main/java/im/vector/app/core/mvrx/ResultExtension.kt +++ b/vector/src/main/java/im/vector/app/core/mvrx/ResultExtension.kt @@ -21,7 +21,7 @@ import com.airbnb.mvrx.Fail import com.airbnb.mvrx.Success /** - * Note: this will be removed when upgrading to mvrx2 + * Note: this will be removed when upgrading to mvrx2. */ suspend fun runCatchingToAsync(block: suspend () -> A): Async { return runCatching { diff --git a/vector/src/main/java/im/vector/app/core/platform/SimpleTextWatcher.kt b/vector/src/main/java/im/vector/app/core/platform/SimpleTextWatcher.kt index 75deebe1ba..0c0f6ef6ec 100644 --- a/vector/src/main/java/im/vector/app/core/platform/SimpleTextWatcher.kt +++ b/vector/src/main/java/im/vector/app/core/platform/SimpleTextWatcher.kt @@ -20,7 +20,7 @@ import android.text.Editable import android.text.TextWatcher /** - * TextWatcher with default no op implementation + * TextWatcher with default no op implementation. */ open class SimpleTextWatcher : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { diff --git a/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt b/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt index fcfd38bccc..8a4aaa4b26 100644 --- a/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt +++ b/vector/src/main/java/im/vector/app/core/platform/VectorBaseActivity.kt @@ -55,6 +55,7 @@ import im.vector.app.core.di.ActiveSessionHolder import im.vector.app.core.di.ActivityEntryPoint import im.vector.app.core.dialogs.DialogLocker import im.vector.app.core.dialogs.UnrecognizedCertificateDialog +import im.vector.app.core.error.fatalError import im.vector.app.core.extensions.observeEvent import im.vector.app.core.extensions.observeNotNull import im.vector.app.core.extensions.registerStartForActivityResult @@ -377,8 +378,8 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver private val postResumeScheduledActions = mutableListOf<() -> Unit>() /** - * Schedule action to be done in the next call of onPostResume() - * It fixes bug observed on Android 6 (API 23) + * Schedule action to be done in the next call of onPostResume(). + * It fixes bug observed on Android 6 (API 23). */ protected fun doOnPostResume(action: () -> Unit) { synchronized(postResumeScheduledActions) { @@ -434,7 +435,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver * ========================================================================================== */ /** - * Force to render the activity in fullscreen + * Force to render the activity in fullscreen. */ @Suppress("DEPRECATION") private fun setFullScreen() { @@ -526,7 +527,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver } /** - * Is first creation + * Is first creation. * * @return true if Activity is created for the first time (and not restored by the system) */ @@ -545,7 +546,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver } /** - * Tells if the waiting view is currently displayed + * Tells if the waiting view is currently displayed. * * @return true if the waiting view is displayed */ @@ -562,7 +563,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver } /** - * Hide the waiting view + * Hide the waiting view. */ open fun hideWaitingView() { waitingView?.isVisible = false @@ -590,7 +591,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver open fun getMenuRes() = -1 /** - * Return a object containing other themes for this activity + * Return a object containing other themes for this activity. */ open fun getOtherThemes(): ActivityOtherThemes = ActivityOtherThemes.Default @@ -611,11 +612,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver } }.show() } else { - if (vectorPreferences.failFast()) { - error("No CoordinatorLayout to display this snackbar!") - } else { - Timber.w("No CoordinatorLayout to display this snackbar!") - } + fatalError("No CoordinatorLayout to display this snackbar!", vectorPreferences.failFast()) } } @@ -643,7 +640,7 @@ abstract class VectorBaseActivity : AppCompatActivity(), Maver } /** - * Sets toolbar as actionBar + * Sets toolbar as actionBar. * * @return Instance of [ToolbarConfig] with set of helper methods to configure toolbar * */ diff --git a/vector/src/main/java/im/vector/app/core/platform/VectorBaseFragment.kt b/vector/src/main/java/im/vector/app/core/platform/VectorBaseFragment.kt index 7db35a8e8f..38667b774f 100644 --- a/vector/src/main/java/im/vector/app/core/platform/VectorBaseFragment.kt +++ b/vector/src/main/java/im/vector/app/core/platform/VectorBaseFragment.kt @@ -80,7 +80,7 @@ abstract class VectorBaseFragment : Fragment(), MavericksView private var progress: AlertDialog? = null /** - * [ToolbarConfig] instance from host activity + * [ToolbarConfig] instance from host activity. * */ protected var toolbar: ToolbarConfig? = null get() = (activity as? VectorBaseActivity<*>)?.toolbar @@ -234,7 +234,7 @@ abstract class VectorBaseFragment : Fragment(), MavericksView * ========================================================================================== */ /** - * Sets toolbar as actionBar for current activity + * Sets toolbar as actionBar for current activity. * * @return Instance of [ToolbarConfig] with set of helper methods to configure toolbar * */ diff --git a/vector/src/main/java/im/vector/app/core/platform/VectorEventViewModel.kt b/vector/src/main/java/im/vector/app/core/platform/VectorEventViewModel.kt index 2b47412901..a28fca60d7 100644 --- a/vector/src/main/java/im/vector/app/core/platform/VectorEventViewModel.kt +++ b/vector/src/main/java/im/vector/app/core/platform/VectorEventViewModel.kt @@ -23,7 +23,7 @@ import im.vector.app.core.utils.PublishDataSource interface VectorSharedAction /** - * Parent class to handle navigation events, action events, or other any events + * Parent class to handle navigation events, action events, or other any events. */ open class VectorSharedActionViewModel(private val store: MutableDataSource = PublishDataSource()) : ViewModel(), MutableDataSource by store diff --git a/vector/src/main/java/im/vector/app/core/platform/VectorViewEvents.kt b/vector/src/main/java/im/vector/app/core/platform/VectorViewEvents.kt index 979394a988..61edb97b96 100644 --- a/vector/src/main/java/im/vector/app/core/platform/VectorViewEvents.kt +++ b/vector/src/main/java/im/vector/app/core/platform/VectorViewEvents.kt @@ -17,11 +17,11 @@ package im.vector.app.core.platform /** - * Interface for View Events + * Interface for View Events. */ interface VectorViewEvents /** - * To use when no view events is associated to the ViewModel + * To use when no view events is associated to the ViewModel. */ object EmptyViewEvents : VectorViewEvents diff --git a/vector/src/main/java/im/vector/app/core/platform/VectorViewModelAction.kt b/vector/src/main/java/im/vector/app/core/platform/VectorViewModelAction.kt index a6ce118eb7..24d8bd7310 100644 --- a/vector/src/main/java/im/vector/app/core/platform/VectorViewModelAction.kt +++ b/vector/src/main/java/im/vector/app/core/platform/VectorViewModelAction.kt @@ -19,6 +19,6 @@ package im.vector.app.core.platform interface VectorViewModelAction /** - * To use when no action is associated to the ViewModel + * To use when no action is associated to the ViewModel. */ object EmptyAction : VectorViewModelAction diff --git a/vector/src/main/java/im/vector/app/core/platform/WaitingViewData.kt b/vector/src/main/java/im/vector/app/core/platform/WaitingViewData.kt index e1e9c7e39f..41b569bd14 100644 --- a/vector/src/main/java/im/vector/app/core/platform/WaitingViewData.kt +++ b/vector/src/main/java/im/vector/app/core/platform/WaitingViewData.kt @@ -17,7 +17,7 @@ package im.vector.app.core.platform /** - * Model to display a Waiting View + * Model to display a Waiting View. */ data class WaitingViewData( val message: String, diff --git a/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt b/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt index 34def7e060..dad7f26560 100644 --- a/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt +++ b/vector/src/main/java/im/vector/app/core/preference/PushRulePreference.kt @@ -53,7 +53,7 @@ class PushRulePreference : VectorPreference { } /** - * Refresh the summary + * Refresh the summary. */ private fun refreshSummary() { summary = context.getString( diff --git a/vector/src/main/java/im/vector/app/core/preference/VectorPreference.kt b/vector/src/main/java/im/vector/app/core/preference/VectorPreference.kt index 22fc1758f1..2dd6f058d7 100755 --- a/vector/src/main/java/im/vector/app/core/preference/VectorPreference.kt +++ b/vector/src/main/java/im/vector/app/core/preference/VectorPreference.kt @@ -33,6 +33,7 @@ import androidx.preference.Preference import androidx.preference.PreferenceViewHolder import im.vector.app.R import im.vector.app.features.themes.ThemeUtils +import org.matrix.android.sdk.api.extensions.orFalse import timber.log.Timber /** @@ -152,16 +153,12 @@ open class VectorPreference : Preference { */ private fun addClickListeners(view: View) { view.setOnLongClickListener { - if (null != onPreferenceLongClickListener) { - onPreferenceLongClickListener!!.onPreferenceLongClick(this@VectorPreference) - } else false + onPreferenceLongClickListener?.onPreferenceLongClick(this@VectorPreference).orFalse() } view.setOnClickListener { // call only the click listener - if (onPreferenceClickListener != null) { - onPreferenceClickListener.onPreferenceClick(this@VectorPreference) - } + onPreferenceClickListener?.onPreferenceClick(this@VectorPreference) } } } diff --git a/vector/src/main/java/im/vector/app/core/preference/VectorSwitchPreference.kt b/vector/src/main/java/im/vector/app/core/preference/VectorSwitchPreference.kt index 346e8488b9..635cbff568 100644 --- a/vector/src/main/java/im/vector/app/core/preference/VectorSwitchPreference.kt +++ b/vector/src/main/java/im/vector/app/core/preference/VectorSwitchPreference.kt @@ -30,7 +30,7 @@ import im.vector.app.R import im.vector.app.features.themes.ThemeUtils /** - * Switch preference with title on multiline (only used in XML) + * Switch preference with title on multiline (only used in XML). */ class VectorSwitchPreference : SwitchPreference { diff --git a/vector/src/main/java/im/vector/app/core/resources/ColorProvider.kt b/vector/src/main/java/im/vector/app/core/resources/ColorProvider.kt index 395b75d336..12c8a47056 100644 --- a/vector/src/main/java/im/vector/app/core/resources/ColorProvider.kt +++ b/vector/src/main/java/im/vector/app/core/resources/ColorProvider.kt @@ -32,7 +32,7 @@ class ColorProvider @Inject constructor(private val context: Context) { } /** - * Translates color attributes to colors + * Translates color attributes to colors. * * @param colorAttribute Color Attribute * @return Requested Color diff --git a/vector/src/main/java/im/vector/app/core/resources/DateProvider.kt b/vector/src/main/java/im/vector/app/core/resources/DateProvider.kt index 30cb1dcae4..6762bd68da 100644 --- a/vector/src/main/java/im/vector/app/core/resources/DateProvider.kt +++ b/vector/src/main/java/im/vector/app/core/resources/DateProvider.kt @@ -19,27 +19,30 @@ package im.vector.app.core.resources import org.threeten.bp.Instant import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneId +import org.threeten.bp.ZoneOffset object DateProvider { - private val zoneId = ZoneId.systemDefault() - private val zoneOffset by lazy { - val now = currentLocalDateTime() - zoneId.rules.getOffset(now) - } + // recompute the zoneId each time we access it to handle change of timezones + private val defaultZoneId: ZoneId + get() = ZoneId.systemDefault() + + // recompute the zoneOffset each time we access it to handle change of timezones + private val defaultZoneOffset: ZoneOffset + get() = defaultZoneId.rules.getOffset(currentLocalDateTime()) fun toLocalDateTime(timestamp: Long?): LocalDateTime { val instant = Instant.ofEpochMilli(timestamp ?: 0) - return LocalDateTime.ofInstant(instant, zoneId) + return LocalDateTime.ofInstant(instant, defaultZoneId) } fun currentLocalDateTime(): LocalDateTime { val instant = Instant.now() - return LocalDateTime.ofInstant(instant, zoneId) + return LocalDateTime.ofInstant(instant, defaultZoneId) } fun toTimestamp(localDateTime: LocalDateTime): Long { - return localDateTime.toInstant(zoneOffset).toEpochMilli() + return localDateTime.toInstant(defaultZoneOffset).toEpochMilli() } } diff --git a/vector/src/main/java/im/vector/app/core/resources/ResourceUtils.kt b/vector/src/main/java/im/vector/app/core/resources/Resource.kt similarity index 100% rename from vector/src/main/java/im/vector/app/core/resources/ResourceUtils.kt rename to vector/src/main/java/im/vector/app/core/resources/Resource.kt diff --git a/vector/src/main/java/im/vector/app/core/resources/UserPreferencesProvider.kt b/vector/src/main/java/im/vector/app/core/resources/UserPreferencesProvider.kt index 3aa1964d8d..d39dcbe318 100644 --- a/vector/src/main/java/im/vector/app/core/resources/UserPreferencesProvider.kt +++ b/vector/src/main/java/im/vector/app/core/resources/UserPreferencesProvider.kt @@ -52,4 +52,8 @@ class UserPreferencesProvider @Inject constructor(private val vectorPreferences: fun areThreadMessagesEnabled(): Boolean { return vectorPreferences.areThreadMessagesEnabled() } + + fun showLiveSenderInfo(): Boolean { + return vectorPreferences.showLiveSenderInfo() + } } diff --git a/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt b/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt index 3f2cd2566e..d050890509 100644 --- a/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt +++ b/vector/src/main/java/im/vector/app/core/services/BluetoothHeadsetReceiver.kt @@ -37,9 +37,10 @@ class BluetoothHeadsetReceiver : BroadcastReceiver() { val plugged: Boolean, val headsetName: String?, /** - * BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE - * BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO - * AUDIO_VIDEO_WEARABLE_HEADSET + * Can be: + * - BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE + * - BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO + * - AUDIO_VIDEO_WEARABLE_HEADSET. */ val deviceClass: Int ) diff --git a/vector/src/main/java/im/vector/app/core/services/CallService.kt b/vector/src/main/java/im/vector/app/core/services/CallService.kt index 4dd95fd49a..df9e670423 100644 --- a/vector/src/main/java/im/vector/app/core/services/CallService.kt +++ b/vector/src/main/java/im/vector/app/core/services/CallService.kt @@ -48,7 +48,7 @@ import javax.inject.Inject private val loggerTag = LoggerTag("CallService", LoggerTag.VOIP) /** - * Foreground service to manage calls + * Foreground service to manage calls. */ @AndroidEntryPoint class CallService : VectorService() { diff --git a/vector/src/main/java/im/vector/app/core/services/VectorService.kt b/vector/src/main/java/im/vector/app/core/services/VectorService.kt index 888f7a8cac..cc816c21a1 100644 --- a/vector/src/main/java/im/vector/app/core/services/VectorService.kt +++ b/vector/src/main/java/im/vector/app/core/services/VectorService.kt @@ -22,7 +22,7 @@ import android.os.IBinder import timber.log.Timber /** - * Parent class for all services + * Parent class for all services. */ abstract class VectorService : Service() { diff --git a/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt b/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt index ac6ced002e..0d3ebafb04 100644 --- a/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt +++ b/vector/src/main/java/im/vector/app/core/services/WiredHeadsetStateReceiver.kt @@ -25,7 +25,7 @@ import timber.log.Timber import java.lang.ref.WeakReference /** - * Dynamic broadcast receiver to detect headset plug/unplug + * Dynamic broadcast receiver to detect headset plug/unplug. */ class WiredHeadsetStateReceiver : BroadcastReceiver() { diff --git a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGeneric.kt b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGeneric.kt index bd7a07c640..9f864aaa68 100644 --- a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGeneric.kt +++ b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGeneric.kt @@ -29,7 +29,7 @@ import im.vector.app.databinding.BottomSheetGenericListBinding import javax.inject.Inject /** - * Generic Bottom sheet with actions + * Generic Bottom sheet with actions. */ abstract class BottomSheetGeneric : VectorBaseBottomSheetDialogFragment(), diff --git a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericController.kt b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericController.kt index 70faa87645..31d13c760e 100644 --- a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericController.kt +++ b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericController.kt @@ -18,7 +18,7 @@ package im.vector.app.core.ui.bottomsheet import com.airbnb.epoxy.TypedEpoxyController /** - * Epoxy controller for generic bottom sheet actions + * Epoxy controller for generic bottom sheet actions. */ abstract class BottomSheetGenericController : TypedEpoxyController() { diff --git a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericRadioAction.kt b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericRadioAction.kt index 88eaf587a8..dc298c434f 100644 --- a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericRadioAction.kt +++ b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericRadioAction.kt @@ -20,7 +20,7 @@ import im.vector.app.core.epoxy.bottomsheet.BottomSheetRadioActionItem_ import im.vector.app.core.platform.VectorSharedAction /** - * Parent class for a bottom sheet action + * Parent class for a bottom sheet action. */ open class BottomSheetGenericRadioAction( open val title: String?, diff --git a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericSharedActionViewModel.kt b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericSharedActionViewModel.kt index 49147b954a..2443784df9 100644 --- a/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericSharedActionViewModel.kt +++ b/vector/src/main/java/im/vector/app/core/ui/bottomsheet/BottomSheetGenericSharedActionViewModel.kt @@ -20,6 +20,6 @@ import im.vector.app.core.platform.VectorSharedAction import im.vector.app.core.platform.VectorSharedActionViewModel /** - * Activity shared view model to handle bottom sheet quick actions + * Activity shared view model to handle bottom sheet quick actions. */ abstract class BottomSheetGenericSharedActionViewModel : VectorSharedActionViewModel() diff --git a/vector/src/main/java/im/vector/app/core/ui/list/GenericEmptyWithActionItem.kt b/vector/src/main/java/im/vector/app/core/ui/list/GenericEmptyWithActionItem.kt index 5801ca6b7c..4cc39af0a5 100644 --- a/vector/src/main/java/im/vector/app/core/ui/list/GenericEmptyWithActionItem.kt +++ b/vector/src/main/java/im/vector/app/core/ui/list/GenericEmptyWithActionItem.kt @@ -33,7 +33,7 @@ import im.vector.app.core.epoxy.onClick import im.vector.app.core.extensions.setTextOrHide /** - * A generic list item to display when there is no results, with an optional CTA + * A generic list item to display when there is no results, with an optional CTA. */ @EpoxyModelClass(layout = R.layout.item_generic_empty_state) abstract class GenericEmptyWithActionItem : VectorEpoxyModel() { diff --git a/vector/src/main/java/im/vector/app/core/ui/list/GenericPillItem.kt b/vector/src/main/java/im/vector/app/core/ui/list/GenericPillItem.kt index 09fdcded6e..a51c1b70ed 100644 --- a/vector/src/main/java/im/vector/app/core/ui/list/GenericPillItem.kt +++ b/vector/src/main/java/im/vector/app/core/ui/list/GenericPillItem.kt @@ -34,7 +34,7 @@ import im.vector.app.features.themes.ThemeUtils import im.vector.lib.core.utils.epoxy.charsequence.EpoxyCharSequence /** - * A generic list item with a rounded corner background and an optional icon + * A generic list item with a rounded corner background and an optional icon. */ @EpoxyModelClass(layout = R.layout.item_generic_pill_footer) abstract class GenericPillItem : VectorEpoxyModel() { diff --git a/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt b/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt index 58a5666e94..f2ea79984e 100755 --- a/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/KeysBackupBanner.kt @@ -28,8 +28,8 @@ import im.vector.app.databinding.ViewKeysBackupBannerBinding import timber.log.Timber /** - * The view used in VectorHomeActivity to show some information about the keys backup state - * It does have a unique render method + * The view used in VectorHomeActivity to show some information about the keys backup state. + * It does have a unique render method. */ class KeysBackupBanner @JvmOverloads constructor( context: Context, @@ -51,7 +51,7 @@ class KeysBackupBanner @JvmOverloads constructor( } /** - * This methods is responsible for rendering the view according to the newState + * This methods is responsible for rendering the view according to the newState. * * @param newState the newState representing the view */ @@ -182,7 +182,7 @@ class KeysBackupBanner @JvmOverloads constructor( } /** - * Hide all views that are not visible in all state + * Hide all views that are not visible in all state. */ private fun hideAll() { views.viewKeysBackupBannerText2.isVisible = false @@ -191,8 +191,8 @@ class KeysBackupBanner @JvmOverloads constructor( } /** - * The state representing the view - * It can take one state at a time + * The state representing the view. + * It can take one state at a time. */ sealed class State { // Not yet rendered @@ -215,7 +215,7 @@ class KeysBackupBanner @JvmOverloads constructor( } /** - * An interface to delegate some actions to another object + * An interface to delegate some actions to another object. */ interface Delegate { fun setupKeysBackup() @@ -239,7 +239,7 @@ class KeysBackupBanner @JvmOverloads constructor( private const val BANNER_UPDATE_DO_NOT_SHOW_FOR_VERSION = "BANNER_UPDATE_DO_NOT_SHOW_FOR_VERSION" /** - * Inform the banner that a Recover has been done for this version, so do not show the Recover banner for this version + * Inform the banner that a Recover has been done for this version, so do not show the Recover banner for this version. */ fun onRecoverDoneForVersion(context: Context, version: String) { DefaultSharedPreferences.getInstance(context).edit { diff --git a/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt b/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt index 5190bb21a8..d9624f65e9 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/NotificationAreaView.kt @@ -37,8 +37,8 @@ import org.matrix.android.sdk.api.session.events.model.Event import timber.log.Timber /** - * The view used to show some information about the room - * It does have a unique render method + * The view used to show some information about the room. + * It does have a unique render method. */ class NotificationAreaView @JvmOverloads constructor( context: Context, @@ -56,7 +56,7 @@ class NotificationAreaView @JvmOverloads constructor( } /** - * This methods is responsible for rendering the view according to the newState + * This methods is responsible for rendering the view according to the newState. * * @param newState the newState representing the view */ @@ -169,8 +169,8 @@ class NotificationAreaView @JvmOverloads constructor( } /** - * The state representing the view - * It can take one state at a time + * The state representing the view. + * It can take one state at a time. */ sealed class State { @@ -195,7 +195,7 @@ class NotificationAreaView @JvmOverloads constructor( } /** - * An interface to delegate some actions to another object + * An interface to delegate some actions to another object. */ interface Delegate { fun onTombstoneEventClicked() diff --git a/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt b/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt index 39bfce6975..04bc821387 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/PasswordStrengthBar.kt @@ -24,8 +24,8 @@ import im.vector.app.R import im.vector.app.databinding.ViewPasswordStrengthBarBinding /** - * A password strength bar custom widget - * Strength is an Integer + * A password strength bar custom widget. + * Strength is an Integer * -> 0 No strength * -> 1 Weak * -> 2 Fair diff --git a/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt b/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt index 82675e8c11..a1d3e49f3b 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/PresenceStateImageView.kt @@ -25,7 +25,7 @@ import org.matrix.android.sdk.api.session.presence.model.PresenceEnum import org.matrix.android.sdk.api.session.presence.model.UserPresence /** - * Custom ImageView to dynamically render Presence state in multiple screens + * Custom ImageView to dynamically render Presence state in multiple screens. */ class PresenceStateImageView @JvmOverloads constructor( context: Context, @@ -42,13 +42,17 @@ class PresenceStateImageView @JvmOverloads constructor( contentDescription = context.getString(R.string.a11y_presence_online) } PresenceEnum.UNAVAILABLE -> { - setImageResource(R.drawable.ic_presence_offline) + setImageResource(R.drawable.ic_presence_away) contentDescription = context.getString(R.string.a11y_presence_unavailable) } PresenceEnum.OFFLINE -> { setImageResource(R.drawable.ic_presence_offline) contentDescription = context.getString(R.string.a11y_presence_offline) } + PresenceEnum.BUSY -> { + setImageResource(R.drawable.ic_presence_busy) + contentDescription = context.getString(R.string.a11y_presence_busy) + } null -> Unit } } diff --git a/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageAvatar.kt b/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageAvatar.kt index 22312f36fa..1f78584a6b 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageAvatar.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageAvatar.kt @@ -22,7 +22,7 @@ import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout -import im.vector.app.core.utils.DimensionConverter +import im.vector.app.R import im.vector.app.features.home.AvatarRenderer import org.matrix.android.sdk.api.session.room.sender.SenderInfo import org.matrix.android.sdk.api.util.toMatrixItem @@ -34,19 +34,22 @@ class TypingMessageAvatar @JvmOverloads constructor( ) : LinearLayout(context, attrs, defStyleAttr) { companion object { - const val AVATAR_SIZE_DP = 20 const val OVERLAP_FACT0R = -3 // =~ 30% to left } + private val typingAvatarSize by lazy(LazyThreadSafetyMode.NONE) { + context.resources.getDimension(R.dimen.typing_avatar_size).toInt() + } + fun render(typingUsers: List, avatarRenderer: AvatarRenderer) { removeAllViews() for ((index, value) in typingUsers.withIndex()) { val avatar = ImageView(context) avatar.id = View.generateViewId() val layoutParams = MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) - if (index != 0) layoutParams.marginStart = DimensionConverter(resources).dpToPx(AVATAR_SIZE_DP / OVERLAP_FACT0R) - layoutParams.width = DimensionConverter(resources).dpToPx(AVATAR_SIZE_DP) - layoutParams.height = DimensionConverter(resources).dpToPx(AVATAR_SIZE_DP) + if (index != 0) layoutParams.marginStart = typingAvatarSize / OVERLAP_FACT0R + layoutParams.width = typingAvatarSize + layoutParams.height = typingAvatarSize avatar.layoutParams = layoutParams avatarRenderer.render(value.toMatrixItem(), avatar) addView(avatar) diff --git a/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageView.kt b/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageView.kt index 2dc9eedd99..263f043fad 100644 --- a/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageView.kt +++ b/vector/src/main/java/im/vector/app/core/ui/views/TypingMessageView.kt @@ -31,7 +31,8 @@ import javax.inject.Inject class TypingMessageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, - defStyleAttr: Int = 0) : ConstraintLayout(context, attrs, defStyleAttr) { + defStyleAttr: Int = 0 +) : ConstraintLayout(context, attrs, defStyleAttr) { val views: TypingMessageLayoutBinding @@ -44,8 +45,8 @@ class TypingMessageView @JvmOverloads constructor( } fun render(typingUsers: List, avatarRenderer: AvatarRenderer) { - views.usersName.text = typingHelper.getNotificationTypingMessage(typingUsers) - views.avatars.render(typingUsers, avatarRenderer) + views.typingUserText.text = typingHelper.getNotificationTypingMessage(typingUsers) + views.typingUserAvatars.render(typingUsers, avatarRenderer) } override fun onDetachedFromWindow() { diff --git a/vector/src/main/java/im/vector/app/core/utils/AssetReader.kt b/vector/src/main/java/im/vector/app/core/utils/AssetReader.kt index 41fca42cb3..9de98e611e 100644 --- a/vector/src/main/java/im/vector/app/core/utils/AssetReader.kt +++ b/vector/src/main/java/im/vector/app/core/utils/AssetReader.kt @@ -21,7 +21,7 @@ import timber.log.Timber import javax.inject.Inject /** - * Read asset files + * Read asset files. */ class AssetReader @Inject constructor(private val context: Context) { diff --git a/vector/src/main/java/im/vector/app/core/utils/DebouncedClickListener.kt b/vector/src/main/java/im/vector/app/core/utils/DebouncedClickListener.kt index f7c3eec112..319c7e65f5 100644 --- a/vector/src/main/java/im/vector/app/core/utils/DebouncedClickListener.kt +++ b/vector/src/main/java/im/vector/app/core/utils/DebouncedClickListener.kt @@ -21,8 +21,8 @@ import timber.log.Timber import java.util.WeakHashMap /** - * Simple Debounced OnClickListener - * Safe to use in different views + * Simple Debounced OnClickListener. + * Safe to use in different views. */ class DebouncedClickListener( val original: View.OnClickListener, diff --git a/vector/src/main/java/im/vector/app/core/utils/Emoji.kt b/vector/src/main/java/im/vector/app/core/utils/Emoji.kt index d73af1e917..d6a63dca10 100644 --- a/vector/src/main/java/im/vector/app/core/utils/Emoji.kt +++ b/vector/src/main/java/im/vector/app/core/utils/Emoji.kt @@ -32,7 +32,7 @@ fun containsOnlyEmojis(str: String?): Boolean { } /** - * Same as split, but considering emojis + * Same as split, but considering emojis. */ fun CharSequence.splitEmoji(): List { val result = mutableListOf() diff --git a/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt b/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt index d961dcaa46..8bfbcaeb92 100644 --- a/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt +++ b/vector/src/main/java/im/vector/app/core/utils/ExternalApplicationsUtil.kt @@ -62,7 +62,7 @@ import java.util.Date import java.util.Locale /** - * Open a url in the internet browser of the system + * Open a url in the internet browser of the system. */ fun openUrlInExternalBrowser(context: Context, url: String?) { url?.let { @@ -71,7 +71,7 @@ fun openUrlInExternalBrowser(context: Context, url: String?) { } /** - * Open a uri in the internet browser of the system + * Open a uri in the internet browser of the system. */ fun openUrlInExternalBrowser(context: Context, uri: Uri?) { uri?.let { @@ -85,9 +85,9 @@ fun openUrlInExternalBrowser(context: Context, uri: Uri?) { } /** - * Open url in custom tab or, if not available, in the default browser + * Open url in custom tab or, if not available, in the default browser. * If several compatible browsers are installed, the user will be proposed to choose one. - * Ref: https://developer.chrome.com/multidevice/android/customtabs + * Ref: https://developer.chrome.com/multidevice/android/customtabs. */ fun openUrlInChromeCustomTab(context: Context, session: CustomTabsSession?, @@ -120,7 +120,7 @@ fun openUrlInChromeCustomTab(context: Context, } /** - * Open file selection activity + * Open file selection activity. */ fun openFileSelection(activity: Activity, activityResultLauncher: ActivityResultLauncher?, @@ -144,7 +144,7 @@ fun openFileSelection(activity: Activity, } /** - * Send an email to address with optional subject and message + * Send an email to address with optional subject and message. */ fun sendMailTo(address: String, subject: String? = null, message: String? = null, activity: Activity) { val intent = Intent( @@ -159,7 +159,7 @@ fun sendMailTo(address: String, subject: String? = null, message: String? = null } /** - * Open an arbitrary uri + * Open an arbitrary uri. */ fun openUri(activity: Activity, uri: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) @@ -187,7 +187,7 @@ fun openMedia(activity: Activity, savedMediaPath: String, mimeType: String) { } /** - * Open external location + * Open external location. * @param activity the activity * @param latitude latitude of the location * @param longitude longitude of the location @@ -364,7 +364,7 @@ private fun addToGallery(savedFile: File, mediaMimeType: String?, context: Conte } /** - * Open the play store to the provided application Id, default to this app + * Open the play store to the provided application Id, default to this app. */ fun openPlayStore(activity: Activity, appId: String = BuildConfig.APPLICATION_ID) { try { @@ -385,7 +385,7 @@ fun openAppSettingsPage(activity: Activity) { } /** - * Ask the user to select a location and a file name to write in + * Ask the user to select a location and a file name to write in. */ fun selectTxtFileToWrite( activity: Activity, diff --git a/vector/src/main/java/im/vector/app/core/utils/FileUtils.kt b/vector/src/main/java/im/vector/app/core/utils/FileUtils.kt index 8d0c308202..c735b8b33d 100644 --- a/vector/src/main/java/im/vector/app/core/utils/FileUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/FileUtils.kt @@ -68,7 +68,7 @@ private fun logAction(file: File): Boolean { * ========================================================================================== */ /** - * Return true in case of success + * Return true in case of success. */ private fun recursiveActionOnFile(file: File, action: ActionOnFile): Boolean { if (file.isDirectory) { @@ -86,7 +86,7 @@ private fun recursiveActionOnFile(file: File, action: ActionOnFile): Boolean { } /** - * Get the file extension of a fileUri or a filename + * Get the file extension of a fileUri or a filename. * * @param fileUri the fileUri (can be a simple filename) * @return the file extension, in lower case, or null is extension is not available or empty diff --git a/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt b/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt index eada3a4f25..b4f8de2485 100644 --- a/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt +++ b/vector/src/main/java/im/vector/app/core/utils/PermissionsTools.kt @@ -142,7 +142,7 @@ fun checkPermissions(permissionsToBeGranted: List, } /** - * To be call after the permission request + * To be call after the permission request. * * @param permissionsToBeGranted the permissions to be granted * @param activity the calling Activity that is requesting the permissions (or fragment parent) diff --git a/vector/src/main/java/im/vector/app/core/utils/ReadOnce.kt b/vector/src/main/java/im/vector/app/core/utils/ReadOnce.kt index 4283ecefab..8c627cf55c 100644 --- a/vector/src/main/java/im/vector/app/core/utils/ReadOnce.kt +++ b/vector/src/main/java/im/vector/app/core/utils/ReadOnce.kt @@ -19,7 +19,7 @@ package im.vector.app.core.utils import java.util.concurrent.atomic.AtomicBoolean /** - * Use this container to read a value only once + * Use this container to read a value only once. */ class ReadOnce( private val value: T @@ -36,7 +36,7 @@ class ReadOnce( } /** - * Only the first call to isTrue() will return true + * Only the first call to isTrue() will return true. */ class ReadOnceTrue { private val readOnce = ReadOnce(true) diff --git a/vector/src/main/java/im/vector/app/core/utils/RingtoneUtils.kt b/vector/src/main/java/im/vector/app/core/utils/RingtoneUtils.kt index 9b84ea7b2f..a0fd3addac 100644 --- a/vector/src/main/java/im/vector/app/core/utils/RingtoneUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/RingtoneUtils.kt @@ -101,14 +101,14 @@ fun setCallRingtoneUri(context: Context, ringtoneUri: Uri) { } /** - * Set using Riot default ringtone + * Set using Riot default ringtone. */ fun useRiotDefaultRingtone(context: Context): Boolean { return DefaultSharedPreferences.getInstance(context).getBoolean(VectorPreferences.SETTINGS_CALL_RINGTONE_USE_RIOT_PREFERENCE_KEY, true) } /** - * Ask if default Riot ringtone has to be used + * Ask if default Riot ringtone has to be used. */ fun setUseRiotDefaultRingtone(context: Context, useRiotDefault: Boolean) { DefaultSharedPreferences.getInstance(context) diff --git a/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt b/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt index f8ff12ddb2..18a467d8d0 100644 --- a/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/SystemUtils.kt @@ -79,7 +79,7 @@ fun requestDisablingBatteryOptimization(activity: Activity, activityResultLaunch // ============================================================================================================== /** - * Copy a text to the clipboard, and display a Toast when done + * Copy a text to the clipboard, and display a Toast when done. * * @param context the context * @param text the text to copy diff --git a/vector/src/main/java/im/vector/app/core/utils/TemporaryStore.kt b/vector/src/main/java/im/vector/app/core/utils/TemporaryStore.kt index 63f80341eb..fb386e0876 100644 --- a/vector/src/main/java/im/vector/app/core/utils/TemporaryStore.kt +++ b/vector/src/main/java/im/vector/app/core/utils/TemporaryStore.kt @@ -22,7 +22,7 @@ import java.util.TimerTask const val THREE_MINUTES = 3 * 60_000L /** - * Store an object T for a specific period of time + * Store an object T for a specific period of time. * @param delay delay to keep the data, in millis */ open class TemporaryStore(private val delay: Long = THREE_MINUTES) { diff --git a/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt b/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt index 992a85679c..d2f8c4022b 100644 --- a/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/TextUtils.kt @@ -19,11 +19,15 @@ package im.vector.app.core.utils import android.content.Context import android.os.Build import android.text.format.Formatter +import im.vector.app.R import org.threeten.bp.Duration import java.util.TreeMap object TextUtils { + private const val MINUTES_PER_HOUR = 60 + private const val SECONDS_PER_MINUTE = 60 + private val suffixes = TreeMap().also { it[1000] = "k" it[1000000] = "M" @@ -71,13 +75,63 @@ object TextUtils { } fun formatDuration(duration: Duration): String { - val hours = duration.seconds / 3600 - val minutes = (duration.seconds % 3600) / 60 - val seconds = duration.seconds % 60 + val hours = getHours(duration) + val minutes = getMinutes(duration) + val seconds = getSeconds(duration) return if (hours > 0) { String.format("%d:%02d:%02d", hours, minutes, seconds) } else { String.format("%02d:%02d", minutes, seconds) } } + + fun formatDurationWithUnits(context: Context, duration: Duration): String { + val hours = getHours(duration) + val minutes = getMinutes(duration) + val seconds = getSeconds(duration) + val builder = StringBuilder() + when { + hours > 0 -> { + appendHours(context, builder, hours) + if (minutes > 0) { + builder.append(" ") + appendMinutes(context, builder, minutes) + } + if (seconds > 0) { + builder.append(" ") + appendSeconds(context, builder, seconds) + } + } + minutes > 0 -> { + appendMinutes(context, builder, minutes) + if (seconds > 0) { + builder.append(" ") + appendSeconds(context, builder, seconds) + } + } + else -> { + appendSeconds(context, builder, seconds) + } + } + return builder.toString() + } + + private fun appendHours(context: Context, builder: StringBuilder, hours: Int) { + builder.append(hours) + builder.append(context.resources.getString(R.string.time_unit_hour_short)) + } + + private fun appendMinutes(context: Context, builder: StringBuilder, minutes: Int) { + builder.append(minutes) + builder.append(context.getString(R.string.time_unit_minute_short)) + } + + private fun appendSeconds(context: Context, builder: StringBuilder, seconds: Int) { + builder.append(seconds) + builder.append(context.getString(R.string.time_unit_second_short)) + } + + private fun getHours(duration: Duration): Int = duration.toHours().toInt() + private fun getMinutes(duration: Duration): Int = duration.toMinutes().toInt() % MINUTES_PER_HOUR + private fun getSeconds(duration: Duration): Int = (duration.seconds % SECONDS_PER_MINUTE).toInt() } diff --git a/vector/src/main/java/im/vector/app/core/utils/ToggleableAppBarLayoutBehavior.kt b/vector/src/main/java/im/vector/app/core/utils/ToggleableAppBarLayoutBehavior.kt new file mode 100644 index 0000000000..c829313256 --- /dev/null +++ b/vector/src/main/java/im/vector/app/core/utils/ToggleableAppBarLayoutBehavior.kt @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.core.utils + +import android.content.Context +import android.util.AttributeSet +import android.view.View +import androidx.coordinatorlayout.widget.CoordinatorLayout +import com.google.android.material.appbar.AppBarLayout + +/** + * [AppBarLayout.Behavior] subclass with a possibility to disable behavior. + * Useful for cases when in some view state we want prevent toolbar from collapsing/expanding by scroll events + */ +class ToggleableAppBarLayoutBehavior : AppBarLayout.Behavior { + constructor() : super() + constructor(context: Context, attrs: AttributeSet) : super(context, attrs) + + var isEnabled = true + + override fun onStartNestedScroll(parent: CoordinatorLayout, + child: AppBarLayout, + directTargetChild: View, + target: View, + nestedScrollAxes: Int, + type: Int): Boolean { + return isEnabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes, type) + } + + override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, + child: AppBarLayout, + target: View, + dxConsumed: Int, + dyConsumed: Int, + dxUnconsumed: Int, + dyUnconsumed: Int, + type: Int, + consumed: IntArray) { + if (!isEnabled) return + super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed) + } + + override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, + child: AppBarLayout, + target: View, + dx: Int, + dy: Int, + consumed: IntArray, + type: Int) { + if (!isEnabled) return + super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type) + } +} diff --git a/vector/src/main/java/im/vector/app/core/utils/ToolbarConfig.kt b/vector/src/main/java/im/vector/app/core/utils/ToolbarConfig.kt index 53bc60a4a6..620cad063c 100644 --- a/vector/src/main/java/im/vector/app/core/utils/ToolbarConfig.kt +++ b/vector/src/main/java/im/vector/app/core/utils/ToolbarConfig.kt @@ -34,7 +34,7 @@ class ToolbarConfig(val activity: AppCompatActivity, val toolbar: MaterialToolba } /** - * Delegating property for [activity.supportActionBar?.title] + * Delegating property for [activity.supportActionBar?.title]. */ var title: CharSequence? set(value) { @@ -43,7 +43,7 @@ class ToolbarConfig(val activity: AppCompatActivity, val toolbar: MaterialToolba get() = activity.supportActionBar?.title /** - * Delegating property for [activity.supportActionBar?.subtitle] + * Delegating property for [activity.supportActionBar?.subtitle]. */ var subtitle: CharSequence? set(value) { @@ -52,27 +52,27 @@ class ToolbarConfig(val activity: AppCompatActivity, val toolbar: MaterialToolba get() = activity.supportActionBar?.subtitle /** - * Sets toolbar's title text + * Sets toolbar's title text. */ fun setTitle(title: CharSequence?) = apply { activity.supportActionBar?.title = title } /** - * Sets toolbar's title text using provided string resource + * Sets toolbar's title text using provided string resource. */ fun setTitle(@StringRes titleRes: Int) = apply { activity.supportActionBar?.setTitle(titleRes) } /** - * Sets toolbar's subtitle text + * Sets toolbar's subtitle text. */ fun setSubtitle(subtitle: CharSequence?) = apply { activity.supportActionBar?.subtitle = subtitle } /** - * Sets toolbar's title text using provided string resource + * Sets toolbar's title text using provided string resource. */ fun setSubtitle(@StringRes subtitleRes: Int) = apply { activity.supportActionBar?.setSubtitle(subtitleRes) } /** - * Enables/disables navigate back button + * Enables/disables navigate back button. * * @param isAllowed defines if back button is enabled. Default [true] * @param useCross defines if cross icon should be used instead of arrow. Default [false] diff --git a/vector/src/main/java/im/vector/app/core/utils/ViewUtils.kt b/vector/src/main/java/im/vector/app/core/utils/ViewUtils.kt index 0e10a35981..aa15697aa1 100644 --- a/vector/src/main/java/im/vector/app/core/utils/ViewUtils.kt +++ b/vector/src/main/java/im/vector/app/core/utils/ViewUtils.kt @@ -23,7 +23,7 @@ import com.google.android.material.textfield.TextInputLayout import im.vector.app.core.platform.SimpleTextWatcher /** - * Find all TextInputLayout in a ViewGroup and in all its descendants + * Find all TextInputLayout in a ViewGroup and in all its descendants. */ fun ViewGroup.findAllTextInputLayout(): List { val res = ArrayList() @@ -41,7 +41,7 @@ fun ViewGroup.findAllTextInputLayout(): List { } /** - * Add a text change listener to all TextInputEditText to reset error on its TextInputLayout when the text is changed + * Add a text change listener to all TextInputEditText to reset error on its TextInputLayout when the text is changed. */ fun autoResetTextInputLayoutErrors(textInputLayouts: List) { textInputLayouts.forEach { diff --git a/vector/src/main/java/im/vector/app/features/MainActivity.kt b/vector/src/main/java/im/vector/app/features/MainActivity.kt index 121edd4216..17bf02dc4f 100644 --- a/vector/src/main/java/im/vector/app/features/MainActivity.kt +++ b/vector/src/main/java/im/vector/app/features/MainActivity.kt @@ -64,9 +64,9 @@ data class MainActivityArgs( ) : Parcelable /** - * This is the entry point of Element Android + * This is the entry point of Element Android. * This Activity, when started with argument, is also doing some cleanup when user signs out, - * clears cache, is logged out, or is soft logged out + * clears cache, is logged out, or is soft logged out. */ @AndroidEntryPoint class MainActivity : VectorBaseActivity(), UnlockedActivity { diff --git a/vector/src/main/java/im/vector/app/features/analytics/AnalyticsTracker.kt b/vector/src/main/java/im/vector/app/features/analytics/AnalyticsTracker.kt index 2389fbd724..871782e473 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/AnalyticsTracker.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/AnalyticsTracker.kt @@ -22,17 +22,17 @@ import im.vector.app.features.analytics.plan.UserProperties interface AnalyticsTracker { /** - * Capture an Event + * Capture an Event. */ fun capture(event: VectorAnalyticsEvent) /** - * Track a displayed screen + * Track a displayed screen. */ fun screen(screen: VectorAnalyticsScreen) /** - * Update user specific properties + * Update user specific properties. */ fun updateUserProperties(userProperties: UserProperties) } diff --git a/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt b/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt index ec34ff7421..e020ec1cf7 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/DecryptionFailureTracker.kt @@ -86,7 +86,7 @@ class DecryptionFailureTracker @Inject constructor( /** * Can be called when the timeline is disposed in order - * to grace those events as they are not anymore displayed on screen + * to grace those events as they are not anymore displayed on screen. * */ fun onTimeLineDisposed(roomId: String) { scope.launch(Dispatchers.Default) { diff --git a/vector/src/main/java/im/vector/app/features/analytics/VectorAnalytics.kt b/vector/src/main/java/im/vector/app/features/analytics/VectorAnalytics.kt index 95322412bd..7d11f93883 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/VectorAnalytics.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/VectorAnalytics.kt @@ -20,42 +20,42 @@ import kotlinx.coroutines.flow.Flow interface VectorAnalytics : AnalyticsTracker { /** - * Return a Flow of Boolean, true if the user has given their consent + * Return a Flow of Boolean, true if the user has given their consent. */ fun getUserConsent(): Flow /** - * Update the user consent value + * Update the user consent value. */ suspend fun setUserConsent(userConsent: Boolean) /** - * Return a Flow of Boolean, true if the user has been asked for their consent + * Return a Flow of Boolean, true if the user has been asked for their consent. */ fun didAskUserConsent(): Flow /** - * Store the fact that the user has been asked for their consent + * Store the fact that the user has been asked for their consent. */ suspend fun setDidAskUserConsent() /** - * Return a Flow of String, used for analytics Id + * Return a Flow of String, used for analytics Id. */ fun getAnalyticsId(): Flow /** - * Update analyticsId from the AccountData + * Update analyticsId from the AccountData. */ suspend fun setAnalyticsId(analyticsId: String) /** - * To be called when a session is destroyed + * To be called when a session is destroyed. */ suspend fun onSignOut() /** - * To be called when application is started + * To be called when application is started. */ fun init() } diff --git a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt index 7b653ef44b..87f0e8c13b 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/impl/DefaultVectorAnalytics.kt @@ -158,8 +158,8 @@ class DefaultVectorAnalytics @Inject constructor( } /** - * We avoid sending nulls as part of the UserProperties as this will reset the values across all devices - * The UserProperties event has nullable properties to allow for clients to opt in + * We avoid sending nulls as part of the UserProperties as this will reset the values across all devices. + * The UserProperties event has nullable properties to allow for clients to opt in. */ private fun Map.toPostHogUserProperties(): Properties { return Properties().apply { diff --git a/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt b/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt index a926776680..da80787a65 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/plan/Error.kt @@ -22,11 +22,11 @@ import im.vector.app.features.analytics.itf.VectorAnalyticsEvent // https://github.com/matrix-org/matrix-analytics-events/ /** - * Triggered when an error occurred + * Triggered when an error occurred. */ data class Error( /** - * Context - client defined, can be used for debugging + * Context - client defined, can be used for debugging. */ val context: String? = null, val domain: Domain, diff --git a/vector/src/main/java/im/vector/app/features/analytics/plan/JoinedRoom.kt b/vector/src/main/java/im/vector/app/features/analytics/plan/JoinedRoom.kt index 06cefa702e..b076a07ae0 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/plan/JoinedRoom.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/plan/JoinedRoom.kt @@ -50,7 +50,7 @@ data class JoinedRoom( Invite, /** - * Room joined via link + * Room joined via link. */ MobilePermalink, diff --git a/vector/src/main/java/im/vector/app/features/analytics/plan/MobileScreen.kt b/vector/src/main/java/im/vector/app/features/analytics/plan/MobileScreen.kt index 79bae544ec..3ce3dfb578 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/plan/MobileScreen.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/plan/MobileScreen.kt @@ -22,7 +22,7 @@ import im.vector.app.features.analytics.itf.VectorAnalyticsScreen // https://github.com/matrix-org/matrix-analytics-events/ /** - * Triggered when the user changed screen on Element Android/iOS + * Triggered when the user changed screen on Element Android/iOS. */ data class MobileScreen( /** @@ -59,7 +59,7 @@ data class MobileScreen( Favourites, /** - * The form for the forgot password use case + * The form for the forgot password use case. */ ForgotPassword, @@ -96,7 +96,7 @@ data class MobileScreen( /** * The screen that displays the registration flow (when the user wants - * to create an account) + * to create an account). */ Register, @@ -143,7 +143,7 @@ data class MobileScreen( RoomPermissions, /** - * Screen that displays room preview if user hasn't joined yet + * Screen that displays room preview if user hasn't joined yet. */ RoomPreview, @@ -197,7 +197,7 @@ data class MobileScreen( /** * The advanced settings screen (developer mode, rageshake, push - * notification rules) + * notification rules). */ SettingsAdvanced, @@ -212,7 +212,7 @@ data class MobileScreen( SettingsGeneral, /** - * The Help and About screen + * The Help and About screen. */ SettingsHelp, @@ -222,12 +222,12 @@ data class MobileScreen( SettingsIgnoredUsers, /** - * The experimental features settings screen, + * The experimental features settings screen. */ SettingsLabs, /** - * The settings screen with legals information + * The settings screen with legals information. */ SettingsLegals, @@ -262,17 +262,17 @@ data class MobileScreen( Sidebar, /** - * Screen that displays the list of rooms and spaces of a space + * Screen that displays the list of rooms and spaces of a space. */ SpaceExploreRooms, /** - * Screen that displays the list of members of a space + * Screen that displays the list of members of a space. */ SpaceMembers, /** - * The bottom sheet that list all space options + * The bottom sheet that list all space options. */ SpaceMenu, @@ -287,7 +287,7 @@ data class MobileScreen( SwitchDirectory, /** - * Screen that displays list of threads for a room + * Screen that displays list of threads for a room. */ ThreadList, diff --git a/vector/src/main/java/im/vector/app/features/analytics/plan/UserProperties.kt b/vector/src/main/java/im/vector/app/features/analytics/plan/UserProperties.kt index dea499edde..77be2456cd 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/plan/UserProperties.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/plan/UserProperties.kt @@ -25,35 +25,35 @@ package im.vector.app.features.analytics.plan */ data class UserProperties( /** - * Whether the user has the favourites space enabled + * Whether the user has the favourites space enabled. */ - val WebMetaSpaceFavouritesEnabled: Boolean? = null, + val webMetaSpaceFavouritesEnabled: Boolean? = null, /** - * Whether the user has the home space set to all rooms + * Whether the user has the home space set to all rooms. */ - val WebMetaSpaceHomeAllRooms: Boolean? = null, + val webMetaSpaceHomeAllRooms: Boolean? = null, /** - * Whether the user has the home space enabled + * Whether the user has the home space enabled. */ - val WebMetaSpaceHomeEnabled: Boolean? = null, + val webMetaSpaceHomeEnabled: Boolean? = null, /** - * Whether the user has the other rooms space enabled + * Whether the user has the other rooms space enabled. */ - val WebMetaSpaceOrphansEnabled: Boolean? = null, + val webMetaSpaceOrphansEnabled: Boolean? = null, /** - * Whether the user has the people space enabled + * Whether the user has the people space enabled. */ - val WebMetaSpacePeopleEnabled: Boolean? = null, + val webMetaSpacePeopleEnabled: Boolean? = null, /** * The selected messaging use case during the onboarding flow. */ val ftueUseCaseSelection: FtueUseCaseSelection? = null, /** - * Number of joined rooms the user has favourited + * Number of joined rooms the user has favourited. */ val numFavouriteRooms: Int? = null, /** - * Number of spaces (and sub-spaces) the user is joined to + * Number of spaces (and sub-spaces) the user is joined to. */ val numSpaces: Int? = null, ) { @@ -82,11 +82,11 @@ data class UserProperties( fun getProperties(): Map? { return mutableMapOf().apply { - WebMetaSpaceFavouritesEnabled?.let { put("WebMetaSpaceFavouritesEnabled", it) } - WebMetaSpaceHomeAllRooms?.let { put("WebMetaSpaceHomeAllRooms", it) } - WebMetaSpaceHomeEnabled?.let { put("WebMetaSpaceHomeEnabled", it) } - WebMetaSpaceOrphansEnabled?.let { put("WebMetaSpaceOrphansEnabled", it) } - WebMetaSpacePeopleEnabled?.let { put("WebMetaSpacePeopleEnabled", it) } + webMetaSpaceFavouritesEnabled?.let { put("WebMetaSpaceFavouritesEnabled", it) } + webMetaSpaceHomeAllRooms?.let { put("WebMetaSpaceHomeAllRooms", it) } + webMetaSpaceHomeEnabled?.let { put("WebMetaSpaceHomeEnabled", it) } + webMetaSpaceOrphansEnabled?.let { put("WebMetaSpaceOrphansEnabled", it) } + webMetaSpacePeopleEnabled?.let { put("WebMetaSpacePeopleEnabled", it) } ftueUseCaseSelection?.let { put("ftueUseCaseSelection", it.name) } numFavouriteRooms?.let { put("numFavouriteRooms", it) } numSpaces?.let { put("numSpaces", it) } diff --git a/vector/src/main/java/im/vector/app/features/analytics/plan/ViewRoom.kt b/vector/src/main/java/im/vector/app/features/analytics/plan/ViewRoom.kt index e9bef6f1d3..d2f30eec9b 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/plan/ViewRoom.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/plan/ViewRoom.kt @@ -64,7 +64,7 @@ data class ViewRoom( MessageUser, /** - * Room accessed via space explore + * Room accessed via space explore. */ MobileExploreRooms, @@ -79,12 +79,12 @@ data class ViewRoom( MobileInCall, /** - * Room accessed during external sharing + * Room accessed during external sharing. */ MobileLinkShare, /** - * Room accessed via link + * Room accessed via link. */ MobilePermalink, @@ -95,7 +95,7 @@ data class ViewRoom( MobileRoomMemberDetail, /** - * Room accessed via preview + * Room accessed via preview. */ MobileRoomPreview, @@ -117,7 +117,7 @@ data class ViewRoom( MobileSpaceMemberDetail, /** - * Room accessed via space members list + * Room accessed via space members list. */ MobileSpaceMembers, diff --git a/vector/src/main/java/im/vector/app/features/analytics/store/AnalyticsStore.kt b/vector/src/main/java/im/vector/app/features/analytics/store/AnalyticsStore.kt index d732e27a82..823d6285ed 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/store/AnalyticsStore.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/store/AnalyticsStore.kt @@ -33,9 +33,9 @@ private val Context.dataStore: DataStore by preferencesDataStore(na /** * Local storage for: - * - user consent (Boolean) - * - did ask user consent (Boolean) - * - analytics Id (String) + * - user consent (Boolean); + * - did ask user consent (Boolean); + * - analytics Id (String). */ class AnalyticsStore @Inject constructor( private val context: Context diff --git a/vector/src/main/java/im/vector/app/features/analytics/ui/consent/AnalyticsOptInActivity.kt b/vector/src/main/java/im/vector/app/features/analytics/ui/consent/AnalyticsOptInActivity.kt index c11cf582d3..39458f84a3 100644 --- a/vector/src/main/java/im/vector/app/features/analytics/ui/consent/AnalyticsOptInActivity.kt +++ b/vector/src/main/java/im/vector/app/features/analytics/ui/consent/AnalyticsOptInActivity.kt @@ -25,7 +25,7 @@ import im.vector.app.databinding.ActivitySimpleBinding import javax.inject.Inject /** - * Simple container for AnalyticsOptInFragment + * Simple container for AnalyticsOptInFragment. */ @AndroidEntryPoint class AnalyticsOptInActivity : VectorBaseActivity() { diff --git a/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt b/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt index 6734744c29..d1f0efae6c 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/AttachmentTypeSelectorView.kt @@ -211,7 +211,7 @@ class AttachmentTypeSelectorView(context: Context, } /** - * The all possible types to pick with their required permissions and tooltip resource + * The all possible types to pick with their required permissions and tooltip resource. */ enum class Type(val permissions: List, @StringRes val tooltipRes: Int) { CAMERA(PERMISSIONS_FOR_TAKING_PHOTO, R.string.tooltip_attachment_photo), diff --git a/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt b/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt index 28760bf52f..14324896bc 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/AttachmentsHelper.kt @@ -73,21 +73,21 @@ class AttachmentsHelper(val context: Context, val callback: Callback) : Restorab // Public Methods /** - * Starts the process for handling file picking + * Starts the process for handling file picking. */ fun selectFile(activityResultLauncher: ActivityResultLauncher) { MultiPicker.get(MultiPicker.FILE).startWith(activityResultLauncher) } /** - * Starts the process for handling image/video picking + * Starts the process for handling image/video picking. */ fun selectGallery(activityResultLauncher: ActivityResultLauncher) { MultiPicker.get(MultiPicker.MEDIA).startWith(activityResultLauncher) } /** - * Starts the process for handling audio picking + * Starts the process for handling audio picking. */ fun selectAudio(activityResultLauncher: ActivityResultLauncher) { MultiPicker.get(MultiPicker.AUDIO).startWith(activityResultLauncher) @@ -112,7 +112,7 @@ class AttachmentsHelper(val context: Context, val callback: Callback) : Restorab } /** - * Starts the process for handling contact picking + * Starts the process for handling contact picking. */ fun selectContact(activityResultLauncher: ActivityResultLauncher) { MultiPicker.get(MultiPicker.CONTACT).startWith(activityResultLauncher) diff --git a/vector/src/main/java/im/vector/app/features/attachments/preview/Extensions.kt b/vector/src/main/java/im/vector/app/features/attachments/preview/Extensions.kt index 672cde977d..3d48be5f67 100644 --- a/vector/src/main/java/im/vector/app/features/attachments/preview/Extensions.kt +++ b/vector/src/main/java/im/vector/app/features/attachments/preview/Extensions.kt @@ -21,7 +21,7 @@ import org.matrix.android.sdk.api.util.MimeTypes import org.matrix.android.sdk.api.util.MimeTypes.isMimeTypeImage /** - * All images are editable, expect Gif + * All images are editable, expect Gif. */ fun ContentAttachmentData.isEditable(): Boolean { return type == ContentAttachmentData.Type.IMAGE && diff --git a/vector/src/main/java/im/vector/app/features/autocomplete/AutocompleteClickListener.kt b/vector/src/main/java/im/vector/app/features/autocomplete/AutocompleteClickListener.kt index 50896c5f34..867269ae4a 100644 --- a/vector/src/main/java/im/vector/app/features/autocomplete/AutocompleteClickListener.kt +++ b/vector/src/main/java/im/vector/app/features/autocomplete/AutocompleteClickListener.kt @@ -17,7 +17,7 @@ package im.vector.app.features.autocomplete /** - * Simple generic listener interface + * Simple generic listener interface. */ interface AutocompleteClickListener { diff --git a/vector/src/main/java/im/vector/app/features/badge/BadgeProxy.kt b/vector/src/main/java/im/vector/app/features/badge/BadgeProxy.kt deleted file mode 100644 index fb597d1ef9..0000000000 --- a/vector/src/main/java/im/vector/app/features/badge/BadgeProxy.kt +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2019 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@file:Suppress("UNUSED_PARAMETER") - -package im.vector.app.features.badge - -import android.content.Context -import android.os.Build -import me.leolin.shortcutbadger.ShortcutBadger -import org.matrix.android.sdk.api.session.Session - -/** - * Manage application badge (displayed in the launcher) - */ -object BadgeProxy { - - /** - * Badge is now managed by notification channel, so no need to use compatibility library in recent versions - * - * @return true if library ShortcutBadger can be used - */ - private fun useShortcutBadger() = Build.VERSION.SDK_INT < Build.VERSION_CODES.O - - /** - * Update the application badge value. - * - * @param context the context - * @param badgeValue the new badge value - */ - fun updateBadgeCount(context: Context, badgeValue: Int) { - if (!useShortcutBadger()) { - return - } - - ShortcutBadger.applyCount(context, badgeValue) - } - - /** - * Refresh the badge count for specific configurations.

    - * The refresh is only effective if the device is: - * * offline * does not support FCM - * * FCM registration failed - *

    Notifications rooms are parsed to track the notification count value. - * - * @param aSession session value - * @param aContext App context - */ - fun specificUpdateBadgeUnreadCount(aSession: Session?, aContext: Context?) { - if (!useShortcutBadger()) { - return - } - - /* TODO - val dataHandler: MXDataHandler - - // sanity check - if (null == aContext || null == aSession) { - Timber.w("## specificUpdateBadgeUnreadCount(): invalid input null values") - } else { - dataHandler = aSession.dataHandler - - if (dataHandler == null) { - Timber.w("## specificUpdateBadgeUnreadCount(): invalid DataHandler instance") - } else { - if (aSession.isAlive) { - var isRefreshRequired: Boolean - val pushManager = Matrix.getInstance(aContext)!!.pushManager - - // update the badge count if the device is offline, FCM is not supported or FCM registration failed - isRefreshRequired = !Matrix.getInstance(aContext)!!.isConnected - isRefreshRequired = isRefreshRequired or (null != pushManager && (!pushManager.useFcm() || !pushManager.hasRegistrationToken())) - - if (isRefreshRequired) { - updateBadgeCount(aContext, dataHandler) - } - } - } - } - */ - } - - /** - * Update the badge count value according to the rooms content. - * - * @param aContext App context - * @param aDataHandler data handler instance - */ - private fun updateBadgeCount(aSession: Session?, aContext: Context?) { - if (!useShortcutBadger()) { - return - } - - /* TODO - //sanity check - if (null == aContext || null == aDataHandler) { - Timber.w("## updateBadgeCount(): invalid input null values") - } else if (null == aDataHandler.store) { - Timber.w("## updateBadgeCount(): invalid store instance") - } else { - val roomCompleteList = ArrayList(aDataHandler.store.rooms) - var unreadRoomsCount = 0 - - for (room in roomCompleteList) { - if (room.notificationCount > 0) { - unreadRoomsCount++ - } - } - - // update the badge counter - Timber.v("## updateBadgeCount(): badge update count=$unreadRoomsCount") - updateBadgeCount(aContext, unreadRoomsCount) - } - */ - } -} diff --git a/vector/src/main/java/im/vector/app/features/call/CallProximityManager.kt b/vector/src/main/java/im/vector/app/features/call/CallProximityManager.kt index 3aeeac15af..78a5ff969a 100644 --- a/vector/src/main/java/im/vector/app/features/call/CallProximityManager.kt +++ b/vector/src/main/java/im/vector/app/features/call/CallProximityManager.kt @@ -85,7 +85,7 @@ class CallProximityManager @Inject constructor( } /** - * Recommending naming convention for WakeLock tags is "app:tag" + * Recommending naming convention for WakeLock tags is "app:tag". */ private fun generateWakeLockTag() = "${stringProvider.getString(R.string.app_name)}:$PROXIMITY_WAKE_LOCK_TAG" diff --git a/vector/src/main/java/im/vector/app/features/call/CallSessionDependencies.kt b/vector/src/main/java/im/vector/app/features/call/VectorCallService.kt similarity index 100% rename from vector/src/main/java/im/vector/app/features/call/CallSessionDependencies.kt rename to vector/src/main/java/im/vector/app/features/call/VectorCallService.kt diff --git a/vector/src/main/java/im/vector/app/features/call/telecom/VectorConnectionService.kt b/vector/src/main/java/im/vector/app/features/call/telecom/VectorConnectionService.kt index e289537177..4a630dc451 100644 --- a/vector/src/main/java/im/vector/app/features/call/telecom/VectorConnectionService.kt +++ b/vector/src/main/java/im/vector/app/features/call/telecom/VectorConnectionService.kt @@ -50,7 +50,7 @@ import im.vector.app.core.services.CallService @RequiresApi(Build.VERSION_CODES.M) class VectorConnectionService : ConnectionService() { /** - * The telecom subsystem calls this method in response to your app calling placeCall(Uri, Bundle) to create a new outgoing call + * The telecom subsystem calls this method in response to your app calling placeCall(Uri, Bundle) to create a new outgoing call. */ override fun onCreateOutgoingConnection(connectionManagerPhoneAccount: PhoneAccountHandle?, request: ConnectionRequest?): Connection? { val callId = request?.address?.encodedQuery ?: return null diff --git a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt index 5a100edcf2..b92316c292 100644 --- a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt +++ b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCall.kt @@ -310,7 +310,7 @@ class WebRtcCall( } /** - * Without consultation + * Without consultation. */ fun transferToUser(targetUserId: String, targetRoomId: String?) { sessionScope?.launch(dispatcher) { @@ -325,7 +325,7 @@ class WebRtcCall( } /** - * With consultation + * With consultation. */ fun transferToCall(transferTargetCall: WebRtcCall) { sessionScope?.launch(dispatcher) { @@ -357,7 +357,7 @@ class WebRtcCall( } /** - * Sends a DTMF digit to the other party + * Sends a DTMF digit to the other party. * @param digit The digit (nb. string - '#' and '*' are dtmf too) */ fun sendDtmfDigit(digit: String) { @@ -683,6 +683,8 @@ class WebRtcCall( direction = RtpTransceiver.RtpTransceiverDirection.SEND_RECV } for (transceiver in peerConnection?.transceivers ?: emptyList()) { + transceiver.sender.track()?.setEnabled(!onHold) + transceiver.receiver.track()?.setEnabled(!onHold) transceiver.direction = direction } updateMuteStatus() diff --git a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt index 10e822c947..5f50747d77 100644 --- a/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt +++ b/vector/src/main/java/im/vector/app/features/call/webrtc/WebRtcCallManager.kt @@ -63,7 +63,7 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Manage peerConnectionFactory & Peer connections outside of activity lifecycle to resist configuration changes + * Manage peerConnectionFactory & Peer connections outside of activity lifecycle to resist configuration changes. * Use app context */ private val loggerTag = LoggerTag("WebRtcCallManager", LoggerTag.VOIP) @@ -454,7 +454,7 @@ class WebRtcCallManager @Inject constructor( } /** - * Analytics + * Analytics. */ private fun WebRtcCall.trackCallStarted() { analyticsTracker.capture( diff --git a/vector/src/main/java/im/vector/app/features/command/Command.kt b/vector/src/main/java/im/vector/app/features/command/Command.kt index 421c83c9fe..24b4ed5300 100644 --- a/vector/src/main/java/im/vector/app/features/command/Command.kt +++ b/vector/src/main/java/im/vector/app/features/command/Command.kt @@ -20,9 +20,9 @@ import androidx.annotation.StringRes import im.vector.app.R /** - * Defines the command line operations - * the user can write theses messages to perform some actions - * the list will be displayed in this order + * Defines the command line operations. + * The user can write theses messages to perform some actions. + * The list will be displayed in this order. */ enum class Command(val command: String, val aliases: Array?, diff --git a/vector/src/main/java/im/vector/app/features/command/CommandParser.kt b/vector/src/main/java/im/vector/app/features/command/CommandParser.kt index b8bef506b1..49e35687f4 100644 --- a/vector/src/main/java/im/vector/app/features/command/CommandParser.kt +++ b/vector/src/main/java/im/vector/app/features/command/CommandParser.kt @@ -411,7 +411,7 @@ class CommandParser @Inject constructor() { } /** - * Checks whether or not the current command is not supported by threads + * Checks whether or not the current command is not supported by threads. * @param slashCommand the slash command that will be checked * @param isInThreadTimeline if its true we are in a thread timeline * @return The command that is not supported diff --git a/vector/src/main/java/im/vector/app/features/command/ParsedCommand.kt b/vector/src/main/java/im/vector/app/features/command/ParsedCommand.kt index 771f721d3c..4571deb54f 100644 --- a/vector/src/main/java/im/vector/app/features/command/ParsedCommand.kt +++ b/vector/src/main/java/im/vector/app/features/command/ParsedCommand.kt @@ -20,7 +20,7 @@ import im.vector.app.features.home.room.detail.ChatEffect import org.matrix.android.sdk.api.session.identity.ThreePid /** - * Represent a parsed command + * Represent a parsed command. */ sealed interface ParsedCommand { // This is not a Slash command diff --git a/vector/src/main/java/im/vector/app/features/configuration/VectorConfiguration.kt b/vector/src/main/java/im/vector/app/features/configuration/VectorConfiguration.kt index 2c19e80772..d209adecc8 100644 --- a/vector/src/main/java/im/vector/app/features/configuration/VectorConfiguration.kt +++ b/vector/src/main/java/im/vector/app/features/configuration/VectorConfiguration.kt @@ -29,7 +29,7 @@ import java.util.Locale import javax.inject.Inject /** - * Handle locale configuration change, such as theme, font size and locale chosen by the user + * Handle locale configuration change, such as theme, font size and locale chosen by the user. */ class VectorConfiguration @Inject constructor(private val context: Context) { @@ -57,7 +57,7 @@ class VectorConfiguration @Inject constructor(private val context: Context) { } /** - * Compute a localised context + * Compute a localised context. * * @param context the context * @return the localised context @@ -100,7 +100,7 @@ class VectorConfiguration @Inject constructor(private val context: Context) { } /** - * Compute the locale status value + * Compute the locale status value. * @return the local status value */ fun getHash(): String { diff --git a/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt b/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt index 9f6aa8cdd8..463954dff7 100644 --- a/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt +++ b/vector/src/main/java/im/vector/app/features/consent/ConsentNotGivenHelper.kt @@ -33,7 +33,7 @@ class ConsentNotGivenHelper(private val activity: Activity, * ========================================================================================== */ /** - * Display the consent dialog, if not already displayed + * Display the consent dialog, if not already displayed. */ fun displayDialog(consentUri: String, homeServerHost: String) { dialogLocker.displayDialog { diff --git a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt index f40f126d2c..f5346980cb 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysExporter.kt @@ -30,7 +30,7 @@ class KeysExporter @Inject constructor( private val dispatchers: CoroutineDispatchers ) { /** - * Export keys and write them to the provided uri + * Export keys and write them to the provided uri. */ suspend fun export(password: String, uri: Uri) { withContext(dispatchers.io) { diff --git a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt index 9b1d29fa25..4b27111851 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keys/KeysImporter.kt @@ -31,7 +31,7 @@ class KeysImporter @Inject constructor( private val session: Session ) { /** - * Import keys from provided Uri + * Import keys from provided Uri. */ suspend fun import(uri: Uri, mimetype: String?, diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt index a4f6587be4..a32cd7caa7 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt @@ -128,7 +128,7 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() { } private fun launch4SActivity() { - SharedSecureStorageActivity.newIntent( + SharedSecureStorageActivity.newReadIntent( context = this, keyId = null, // default key requestedSecrets = listOf(KEYBACKUP_SECRET_SSSS_NAME), diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeyBackupSettingsAction.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeyBackupSettingsAction.kt index 776c7bb521..0d19ae630b 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeyBackupSettingsAction.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeyBackupSettingsAction.kt @@ -22,4 +22,8 @@ sealed class KeyBackupSettingsAction : VectorViewModelAction { object Init : KeyBackupSettingsAction() object GetKeyBackupTrust : KeyBackupSettingsAction() object DeleteKeyBackup : KeyBackupSettingsAction() + object SetUpKeyBackup : KeyBackupSettingsAction() + data class StoreIn4SSuccess(val recoveryKey: String, val alias: String) : KeyBackupSettingsAction() + object StoreIn4SReset : KeyBackupSettingsAction() + object StoreIn4SFailure : KeyBackupSettingsAction() } diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt index 13df109dd5..e58746193b 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupManageActivity.kt @@ -15,6 +15,7 @@ */ package im.vector.app.features.crypto.keysbackup.settings +import android.app.Activity import android.content.Context import android.content.Intent import com.airbnb.mvrx.Fail @@ -23,9 +24,13 @@ import com.airbnb.mvrx.viewModel import com.google.android.material.dialog.MaterialAlertDialogBuilder import dagger.hilt.android.AndroidEntryPoint import im.vector.app.R +import im.vector.app.core.extensions.registerStartForActivityResult import im.vector.app.core.extensions.replaceFragment import im.vector.app.core.platform.SimpleFragmentActivity import im.vector.app.core.platform.WaitingViewData +import im.vector.app.features.crypto.keysbackup.setup.KeysBackupSetupActivity +import im.vector.app.features.crypto.quads.SharedSecureStorageActivity +import org.matrix.android.sdk.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME @AndroidEntryPoint class KeysBackupManageActivity : SimpleFragmentActivity() { @@ -41,6 +46,21 @@ class KeysBackupManageActivity : SimpleFragmentActivity() { private val viewModel: KeysBackupSettingsViewModel by viewModel() + private val secretStartForActivityResult = registerStartForActivityResult { activityResult -> + if (activityResult.resultCode == Activity.RESULT_OK) { + val result = activityResult.data?.getStringExtra(SharedSecureStorageActivity.EXTRA_DATA_RESULT) + val reset = activityResult.data?.getBooleanExtra(SharedSecureStorageActivity.EXTRA_DATA_RESET, false) ?: false + if (result != null) { + viewModel.handle(KeyBackupSettingsAction.StoreIn4SSuccess(result, SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS)) + } else if (reset) { + // all have been reset so a new backup would have been created + viewModel.handle(KeyBackupSettingsAction.StoreIn4SReset) + } + } else { + viewModel.handle(KeyBackupSettingsAction.StoreIn4SFailure) + } + } + override fun initUiAndData() { super.initUiAndData() if (supportFragmentManager.fragments.isEmpty()) { @@ -69,6 +89,22 @@ class KeysBackupManageActivity : SimpleFragmentActivity() { } } } + + viewModel.observeViewEvents { + when (it) { + KeysBackupViewEvents.OpenLegacyCreateBackup -> { + startActivity(KeysBackupSetupActivity.intent(this, false)) + } + is KeysBackupViewEvents.RequestStore4SSecret -> { + secretStartForActivityResult.launch( + SharedSecureStorageActivity.newWriteIntent( + context = this, + writeSecrets = listOf(KEYBACKUP_SECRET_SSSS_NAME to it.recoveryKey) + ) + ) + } + } + } } override fun onBackPressed() { diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsFragment.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsFragment.kt index 4d3ec9a820..edc44fa796 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsFragment.kt @@ -28,7 +28,6 @@ import im.vector.app.core.extensions.configureWith import im.vector.app.core.platform.VectorBaseFragment import im.vector.app.databinding.FragmentKeysBackupSettingsBinding import im.vector.app.features.crypto.keysbackup.restore.KeysBackupRestoreActivity -import im.vector.app.features.crypto.keysbackup.setup.KeysBackupSetupActivity import javax.inject.Inject class KeysBackupSettingsFragment @Inject constructor(private val keysBackupSettingsRecyclerViewController: KeysBackupSettingsRecyclerViewController) : @@ -58,9 +57,7 @@ class KeysBackupSettingsFragment @Inject constructor(private val keysBackupSetti } override fun didSelectSetupMessageRecovery() { - context?.let { - startActivity(KeysBackupSetupActivity.intent(it, false)) - } + viewModel.handle(KeyBackupSettingsAction.SetUpKeyBackup) } override fun didSelectRestoreMessageRecovery() { diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt index d281360678..d13b97a9ba 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsRecyclerViewController.kt @@ -29,9 +29,11 @@ import im.vector.app.core.ui.list.ItemStyle import im.vector.app.core.ui.list.genericItem import im.vector.app.features.settings.VectorPreferences import im.vector.lib.core.utils.epoxy.charsequence.toEpoxyCharSequence +import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupState import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupVersionTrust +import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupVersionTrustSignature import java.util.UUID import javax.inject.Inject @@ -191,69 +193,105 @@ class KeysBackupSettingsRecyclerViewController @Inject constructor( } } is Success -> { - keysVersionTrust().signatures.forEach { - genericItem { - id(UUID.randomUUID().toString()) - title(host.stringProvider.getString(R.string.keys_backup_info_title_signature).toEpoxyCharSequence()) - - val isDeviceKnown = it.device != null - val isDeviceVerified = it.device?.isVerified ?: false - val isSignatureValid = it.valid - val deviceId: String = it.deviceId ?: "" - - if (!isDeviceKnown) { - description( - host.stringProvider - .getString(R.string.keys_backup_settings_signature_from_unknown_device, deviceId) - .toEpoxyCharSequence() - ) - endIconResourceId(R.drawable.e2e_warning) - } else { - if (isSignatureValid) { - if (host.session.sessionParams.deviceId == it.deviceId) { + keysVersionTrust() + .signatures + .filterIsInstance() + .forEach { + val isUserVerified = it.cryptoCrossSigningKey?.trustLevel?.isVerified().orFalse() + val isSignatureValid = it.valid + val userId: String = it.cryptoCrossSigningKey?.userId ?: "" + if (userId == session.sessionParams.userId && isSignatureValid && isUserVerified) { + genericItem { + id(UUID.randomUUID().toString()) + title(host.stringProvider.getString(R.string.keys_backup_info_title_signature).toEpoxyCharSequence()) description( host.stringProvider - .getString(R.string.keys_backup_settings_valid_signature_from_this_device) + .getString(R.string.keys_backup_settings_signature_from_this_user) .toEpoxyCharSequence() ) endIconResourceId(R.drawable.e2e_verified) - } else { - if (isDeviceVerified) { - description( - host.stringProvider - .getString(R.string.keys_backup_settings_valid_signature_from_verified_device, deviceId) - .toEpoxyCharSequence() - ) - endIconResourceId(R.drawable.e2e_verified) - } else { - description( - host.stringProvider - .getString(R.string.keys_backup_settings_valid_signature_from_unverified_device, deviceId) - .toEpoxyCharSequence() - ) - endIconResourceId(R.drawable.e2e_warning) - } - } - } else { - // Invalid signature - endIconResourceId(R.drawable.e2e_warning) - if (isDeviceVerified) { - description( - host.stringProvider - .getString(R.string.keys_backup_settings_invalid_signature_from_verified_device, deviceId) - .toEpoxyCharSequence() - ) - } else { - description( - host.stringProvider - .getString(R.string.keys_backup_settings_invalid_signature_from_unverified_device, deviceId) - .toEpoxyCharSequence() - ) } } } - } - } // end for each + + keysVersionTrust() + .signatures + .filterIsInstance() + .forEach { + genericItem { + id(UUID.randomUUID().toString()) + title(host.stringProvider.getString(R.string.keys_backup_info_title_signature).toEpoxyCharSequence()) + + val isDeviceKnown = it.device != null + val isDeviceVerified = it.device?.isVerified ?: false + val isSignatureValid = it.valid + val deviceId: String = it.deviceId ?: "" + + if (!isDeviceKnown) { + description( + host.stringProvider + .getString(R.string.keys_backup_settings_signature_from_unknown_device, deviceId) + .toEpoxyCharSequence() + ) + endIconResourceId(R.drawable.e2e_warning) + } else { + if (isSignatureValid) { + if (host.session.sessionParams.deviceId == it.deviceId) { + description( + host.stringProvider + .getString(R.string.keys_backup_settings_valid_signature_from_this_device) + .toEpoxyCharSequence() + ) + endIconResourceId(R.drawable.e2e_verified) + } else { + if (isDeviceVerified) { + description( + host.stringProvider + .getString( + R.string.keys_backup_settings_valid_signature_from_verified_device, + deviceId + ) + .toEpoxyCharSequence() + ) + endIconResourceId(R.drawable.e2e_verified) + } else { + description( + host.stringProvider + .getString( + R.string.keys_backup_settings_valid_signature_from_unverified_device, + deviceId + ) + .toEpoxyCharSequence() + ) + endIconResourceId(R.drawable.e2e_warning) + } + } + } else { + // Invalid signature + endIconResourceId(R.drawable.e2e_warning) + if (isDeviceVerified) { + description( + host.stringProvider + .getString( + R.string.keys_backup_settings_invalid_signature_from_verified_device, + deviceId + ) + .toEpoxyCharSequence() + ) + } else { + description( + host.stringProvider + .getString( + R.string.keys_backup_settings_invalid_signature_from_unverified_device, + deviceId + ) + .toEpoxyCharSequence() + ) + } + } + } + } + } // end for each } is Fail -> { errorWithRetryItem { diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt index ca6edf0941..b47b84af71 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupSettingsViewModel.kt @@ -25,8 +25,8 @@ import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import im.vector.app.core.di.MavericksAssistedViewModelFactory import im.vector.app.core.di.hiltMavericksViewModelFactory -import im.vector.app.core.platform.EmptyViewEvents import im.vector.app.core.platform.VectorViewModel +import kotlinx.coroutines.launch import org.matrix.android.sdk.api.MatrixCallback import org.matrix.android.sdk.api.NoOpMatrixCallback import org.matrix.android.sdk.api.session.Session @@ -34,10 +34,16 @@ import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupService 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.KeysBackupVersionTrust +import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysVersion +import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreationInfo +import org.matrix.android.sdk.api.session.crypto.keysbackup.extractCurveKeyFromRecoveryKey +import org.matrix.android.sdk.api.util.awaitCallback +import org.matrix.android.sdk.api.util.toBase64NoPadding +import timber.log.Timber class KeysBackupSettingsViewModel @AssistedInject constructor(@Assisted initialState: KeysBackupSettingViewState, - session: Session -) : VectorViewModel(initialState), + private val session: Session +) : VectorViewModel(initialState), KeysBackupStateListener { @AssistedFactory @@ -49,6 +55,8 @@ class KeysBackupSettingsViewModel @AssistedInject constructor(@Assisted initialS private val keysBackupService: KeysBackupService = session.cryptoService().keysBackupService() + var pendingBackupCreationInfo: MegolmBackupCreationInfo? = null + init { setState { this.copy( @@ -62,9 +70,18 @@ class KeysBackupSettingsViewModel @AssistedInject constructor(@Assisted initialS override fun handle(action: KeyBackupSettingsAction) { when (action) { - KeyBackupSettingsAction.Init -> init() - KeyBackupSettingsAction.GetKeyBackupTrust -> getKeysBackupTrust() - KeyBackupSettingsAction.DeleteKeyBackup -> deleteCurrentBackup() + KeyBackupSettingsAction.Init -> init() + KeyBackupSettingsAction.GetKeyBackupTrust -> getKeysBackupTrust() + KeyBackupSettingsAction.DeleteKeyBackup -> deleteCurrentBackup() + KeyBackupSettingsAction.SetUpKeyBackup -> viewModelScope.launch { + setUpKeyBackup() + } + KeyBackupSettingsAction.StoreIn4SReset, + KeyBackupSettingsAction.StoreIn4SFailure -> { + pendingBackupCreationInfo = null + // nothing to do just stay on fragment + } + is KeyBackupSettingsAction.StoreIn4SSuccess -> viewModelScope.launch { completeBackupCreation() } } } @@ -120,6 +137,41 @@ class KeysBackupSettingsViewModel @AssistedInject constructor(@Assisted initialS getKeysBackupTrust() } + suspend fun setUpKeyBackup() { + // We need to check if 4S is enabled first. + // If it is we need to use it, generate a random key + // for the backup and store it in the 4S + if (session.sharedSecretStorageService().isRecoverySetup()) { + val creationInfo = awaitCallback { + session.cryptoService().keysBackupService().prepareKeysBackupVersion(null, null, it) + } + pendingBackupCreationInfo = creationInfo + val recoveryKey = extractCurveKeyFromRecoveryKey(creationInfo.recoveryKey)?.toBase64NoPadding() + _viewEvents.post(KeysBackupViewEvents.RequestStore4SSecret(recoveryKey!!)) + } else { + // No 4S so we can open legacy flow + _viewEvents.post(KeysBackupViewEvents.OpenLegacyCreateBackup) + } + } + + suspend fun completeBackupCreation() { + val info = pendingBackupCreationInfo ?: return + try { + val version = awaitCallback { + session.cryptoService().keysBackupService().createKeysBackupVersion(info, it) + } + // Save it for gossiping + Timber.d("## BootstrapCrossSigningTask: Creating 4S - Save megolm backup key for gossiping") + session.cryptoService().keysBackupService().saveBackupRecoveryKey(info.recoveryKey, version = version.version) + } catch (failure: Throwable) { + // XXX mm... failed we should remove what we put in 4S, as it was not created? + + // for now just stay on the screen, user can retry, there is no api to delete account data + } finally { + pendingBackupCreationInfo = null + } + } + private fun deleteCurrentBackup() { val keysBackupService = keysBackupService diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/GossipingRequestState.kt b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupViewEvents.kt similarity index 62% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/GossipingRequestState.kt rename to vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupViewEvents.kt index d9a6f4fcba..b39a516772 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/crypto/model/GossipingRequestState.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysbackup/settings/KeysBackupViewEvents.kt @@ -1,5 +1,5 @@ /* - * Copyright 2020 The Matrix.org Foundation C.I.C. + * Copyright (c) 2022 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,18 +14,11 @@ * limitations under the License. */ -package org.matrix.android.sdk.api.session.crypto.model +package im.vector.app.features.crypto.keysbackup.settings -enum class GossipingRequestState { - NONE, - PENDING, - REJECTED, - ACCEPTING, - ACCEPTED, - FAILED_TO_ACCEPTED, +import im.vector.app.core.platform.VectorViewEvents - // USER_REJECTED, - UNABLE_TO_PROCESS, - CANCELLED_BY_REQUESTER, - RE_REQUESTED +sealed class KeysBackupViewEvents : VectorViewEvents { + object OpenLegacyCreateBackup : KeysBackupViewEvents() + data class RequestStore4SSecret(val recoveryKey: String) : KeysBackupViewEvents() } diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt index 0fbb18e63c..034c667aac 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/KeyRequestHandler.kt @@ -22,16 +22,17 @@ import im.vector.app.core.date.DateFormatKind import im.vector.app.core.date.VectorDateFormatter import im.vector.app.features.popup.DefaultVectorAlert import im.vector.app.features.popup.PopupAlertManager +import im.vector.app.features.session.coroutineScope +import kotlinx.coroutines.launch import org.matrix.android.sdk.api.MatrixCallback import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.crosssigning.DeviceTrustLevel import org.matrix.android.sdk.api.session.crypto.keyshare.GossipingRequestListener import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo -import org.matrix.android.sdk.api.session.crypto.model.IncomingRequestCancellation import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest -import org.matrix.android.sdk.api.session.crypto.model.IncomingSecretShareRequest import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap +import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest import org.matrix.android.sdk.api.session.crypto.verification.SasVerificationTransaction import org.matrix.android.sdk.api.session.crypto.verification.VerificationService import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransaction @@ -60,6 +61,9 @@ class KeyRequestHandler @Inject constructor( var session: Session? = null + // This functionality is disabled in element for now. As it could be prone to social attacks + var enablePromptingForRequest = false + fun start(session: Session) { this.session = session session.cryptoService().verificationService().addListener(this) @@ -72,10 +76,9 @@ class KeyRequestHandler @Inject constructor( session = null } - override fun onSecretShareRequest(request: IncomingSecretShareRequest): Boolean { + override fun onSecretShareRequest(request: SecretShareRequest): Boolean { // By default Element will not prompt if the SDK has decided that the request should not be fulfilled Timber.v("## onSecretShareRequest() : Ignoring $request") - request.ignore?.run() return true } @@ -85,6 +88,8 @@ class KeyRequestHandler @Inject constructor( * @param request the key request. */ override fun onRoomKeyRequest(request: IncomingRoomKeyRequest) { + if (!enablePromptingForRequest) return + val userId = request.userId val deviceId = request.deviceId val requestId = request.requestId @@ -195,15 +200,14 @@ class KeyRequestHandler @Inject constructor( } private fun denyAllRequests(mappingKey: String) { - alertsToRequests[mappingKey]?.forEach { - it.ignore?.run() - } alertsToRequests.remove(mappingKey) } private fun shareAllSessions(mappingKey: String) { alertsToRequests[mappingKey]?.forEach { - it.share?.run() + session?.coroutineScope?.launch { + session?.cryptoService()?.manuallyAcceptRoomKeyRequest(it) + } } alertsToRequests.remove(mappingKey) } @@ -213,7 +217,7 @@ class KeyRequestHandler @Inject constructor( * * @param request the cancellation request. */ - override fun onRoomKeyRequestCancellation(request: IncomingRequestCancellation) { + override fun onRequestCancelled(request: IncomingRoomKeyRequest) { // see if we can find the request in the queue val userId = request.userId val deviceId = request.deviceId diff --git a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt index 19c62ed572..2018a5b053 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/keysrequest/OutboundSessionKeySharingStrategy.kt @@ -18,17 +18,17 @@ package im.vector.app.features.crypto.keysrequest enum class OutboundSessionKeySharingStrategy { /** - * Keys will be sent for the first time when the first message is sent + * Keys will be sent for the first time when the first message is sent. */ WhenSendingEvent, /** - * Keys will be sent for the first time when the timeline displayed + * Keys will be sent for the first time when the timeline displayed. */ WhenEnteringRoom, /** - * Keys will be sent for the first time when a typing started + * Keys will be sent for the first time when a typing started. */ WhenTyping } diff --git a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt index 8ca1dec6d7..40ad2859fe 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageActivity.kt @@ -48,8 +48,9 @@ class SharedSecureStorageActivity : @Parcelize data class Args( val keyId: String?, - val requestedSecrets: List, - val resultKeyStoreAlias: String + val requestedSecrets: List = emptyList(), + val resultKeyStoreAlias: String, + val writeSecrets: List> = emptyList(), ) : Parcelable private val viewModel: SharedSecureStorageViewModel by viewModel() @@ -148,18 +149,36 @@ class SharedSecureStorageActivity : const val EXTRA_DATA_RESET = "EXTRA_DATA_RESET" const val DEFAULT_RESULT_KEYSTORE_ALIAS = "SharedSecureStorageActivity" - fun newIntent(context: Context, - keyId: String? = null, - requestedSecrets: List, - resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS): Intent { + fun newReadIntent(context: Context, + keyId: String? = null, + requestedSecrets: List, + resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS): Intent { require(requestedSecrets.isNotEmpty()) return Intent(context, SharedSecureStorageActivity::class.java).also { it.putExtra( - Mavericks.KEY_ARG, Args( - keyId, - requestedSecrets, - resultKeyStoreAlias + Mavericks.KEY_ARG, + Args( + keyId = keyId, + requestedSecrets = requestedSecrets, + resultKeyStoreAlias = resultKeyStoreAlias + ) ) + } + } + + fun newWriteIntent(context: Context, + keyId: String? = null, + writeSecrets: List>, + resultKeyStoreAlias: String = DEFAULT_RESULT_KEYSTORE_ALIAS): Intent { + require(writeSecrets.isNotEmpty()) + return Intent(context, SharedSecureStorageActivity::class.java).also { + it.putExtra( + Mavericks.KEY_ARG, + Args( + keyId = keyId, + writeSecrets = writeSecrets, + resultKeyStoreAlias = resultKeyStoreAlias + ) ) } } diff --git a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt index 3fafda54a3..e045ac020d 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/quads/SharedSecureStorageViewModel.kt @@ -39,13 +39,20 @@ import kotlinx.coroutines.withContext import org.matrix.android.sdk.api.listeners.ProgressListener import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.securestorage.IntegrityResult +import org.matrix.android.sdk.api.session.securestorage.KeyInfo import org.matrix.android.sdk.api.session.securestorage.KeyInfoResult import org.matrix.android.sdk.api.session.securestorage.RawBytesKeySpec +import org.matrix.android.sdk.api.session.securestorage.SharedSecretStorageService import org.matrix.android.sdk.api.util.toBase64NoPadding import org.matrix.android.sdk.flow.flow import timber.log.Timber import java.io.ByteArrayOutputStream +sealed class RequestType { + data class ReadSecrets(val secretsName: List) : RequestType() + data class WriteSecrets(val secretsNameValue: List>) : RequestType() +} + data class SharedSecureStorageViewState( val ready: Boolean = false, val hasPassphrase: Boolean = true, @@ -55,13 +62,17 @@ data class SharedSecureStorageViewState( val showResetAllAction: Boolean = false, val userId: String = "", val keyId: String?, - val requestedSecrets: List, + val requestType: RequestType, val resultKeyStoreAlias: String ) : MavericksState { constructor(args: SharedSecureStorageActivity.Args) : this( keyId = args.keyId, - requestedSecrets = args.requestedSecrets, + requestType = if (args.writeSecrets.isNotEmpty()) { + RequestType.WriteSecrets(args.writeSecrets) + } else { + RequestType.ReadSecrets(args.requestedSecrets) + }, resultKeyStoreAlias = args.resultKeyStoreAlias ) @@ -87,14 +98,17 @@ class SharedSecureStorageViewModel @AssistedInject constructor( setState { copy(userId = session.myUserId) } - val integrityResult = session.sharedSecretStorageService().checkShouldBeAbleToAccessSecrets(initialState.requestedSecrets, initialState.keyId) - if (integrityResult !is IntegrityResult.Success) { - _viewEvents.post( - SharedSecureStorageViewEvent.Error( - stringProvider.getString(R.string.enter_secret_storage_invalid), - true - ) - ) + if (initialState.requestType is RequestType.ReadSecrets) { + val integrityResult = + session.sharedSecretStorageService().checkShouldBeAbleToAccessSecrets(initialState.requestType.secretsName, initialState.keyId) + if (integrityResult !is IntegrityResult.Success) { + _viewEvents.post( + SharedSecureStorageViewEvent.Error( + stringProvider.getString(R.string.enter_secret_storage_invalid), + true + ) + ) + } } val keyResult = initialState.keyId?.let { session.sharedSecretStorageService().getKey(it) } ?: session.sharedSecretStorageService().getDefaultKey() @@ -226,20 +240,8 @@ class SharedSecureStorageViewModel @AssistedInject constructor( _viewEvents.post(SharedSecureStorageViewEvent.HideModalLoading) setState { copy(checkingSSSSAction = Fail(IllegalArgumentException(stringProvider.getString(R.string.bootstrap_invalid_recovery_key)))) } } - withContext(Dispatchers.IO) { - initialState.requestedSecrets.forEach { - if (session.accountDataService().getUserAccountDataEvent(it) != null) { - val res = session.sharedSecretStorageService().getSecret( - name = it, - keyId = keyInfo.id, - secretKey = keySpec - ) - decryptedSecretMap[it] = res - } else { - Timber.w("## Cannot find secret $it in SSSS, skip") - } - } + performRequest(keyInfo, keySpec, decryptedSecretMap) } }.fold({ setState { copy(checkingSSSSAction = Success(Unit)) } @@ -258,6 +260,37 @@ class SharedSecureStorageViewModel @AssistedInject constructor( } } + private suspend fun performRequest(keyInfo: KeyInfo, keySpec: RawBytesKeySpec, decryptedSecretMap: HashMap) { + when (val requestType = initialState.requestType) { + is RequestType.ReadSecrets -> { + requestType.secretsName.forEach { + if (session.accountDataService().getUserAccountDataEvent(it) != null) { + val res = session.sharedSecretStorageService().getSecret( + name = it, + keyId = keyInfo.id, + secretKey = keySpec + ) + decryptedSecretMap[it] = res + } else { + Timber.w("## Cannot find secret $it in SSSS, skip") + } + } + } + is RequestType.WriteSecrets -> { + requestType.secretsNameValue.forEach { + val (name, value) = it + + session.sharedSecretStorageService().storeSecret( + name = name, + secretBase64 = value, + keys = listOf(SharedSecretStorageService.KeyRef(keyInfo.id, keySpec)) + ) + decryptedSecretMap[name] = value + } + } + } + } + private fun handleSubmitPassphrase(action: SharedSecureStorageAction.SubmitPassphrase) { _viewEvents.post(SharedSecureStorageViewEvent.ShowModalLoading) val decryptedSecretMap = HashMap() @@ -302,17 +335,8 @@ class SharedSecureStorageViewModel @AssistedInject constructor( ) withContext(Dispatchers.IO) { - initialState.requestedSecrets.forEach { - if (session.accountDataService().getUserAccountDataEvent(it) != null) { - val res = session.sharedSecretStorageService().getSecret( - name = it, - keyId = keyInfo.id, - secretKey = keySpec - ) - decryptedSecretMap[it] = res - } else { - Timber.w("## Cannot find secret $it in SSSS, skip") - } + withContext(Dispatchers.IO) { + performRequest(keyInfo, keySpec, decryptedSecretMap) } } }.fold({ diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt index bc756974ad..e620500d70 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/BackupToQuadSMigrationTask.kt @@ -20,7 +20,6 @@ import im.vector.app.R import im.vector.app.core.platform.ViewModelTask import im.vector.app.core.platform.WaitingViewData import im.vector.app.core.resources.StringProvider -import org.matrix.android.sdk.api.NoOpMatrixCallback import org.matrix.android.sdk.api.listeners.ProgressListener import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME @@ -149,15 +148,8 @@ class BackupToQuadSMigrationTask @Inject constructor( // save for gossiping keysBackupService.saveBackupRecoveryKey(recoveryKey, version.version) - // while we are there let's restore, but do not block - session.cryptoService().keysBackupService().restoreKeysWithRecoveryKey( - version, - recoveryKey, - null, - null, - null, - NoOpMatrixCallback() - ) + // It's not a good idea to download the full backup, it might take very long + // and use a lot of resources return Result.Success } catch (failure: Throwable) { diff --git a/vector/src/main/java/im/vector/app/features/crypto/recover/SetupMode.kt b/vector/src/main/java/im/vector/app/features/crypto/recover/SetupMode.kt index 0879490e79..c8bd2e69e5 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/recover/SetupMode.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/recover/SetupMode.kt @@ -19,7 +19,7 @@ package im.vector.app.features.crypto.recover enum class SetupMode { /** - * Only setup cross signing, no 4S or megolm backup + * Only setup cross signing, no 4S or megolm backup. */ CROSS_SIGNING_ONLY, @@ -30,21 +30,21 @@ enum class SetupMode { /** * Only reset the 4S passphrase/key, but do not touch - * to existing cross-signing or megolm backup - * It take the local known secrets and put them in 4S + * to existing cross-signing or megolm backup. + * It takes the local known secrets and put them in 4S. */ PASSPHRASE_RESET, /** * Resets the passphrase/key, and all missing secrets * are re-created. Meaning that if cross signing is setup and the secrets - * keys are not known, cross signing will be reset (if secret is known we just keep same cross signing) - * Same apply to megolm + * keys are not known, cross signing will be reset (if secret is known we just keep same cross signing). + * Same apply to megolm. */ PASSPHRASE_AND_NEEDED_SECRETS_RESET, /** - * Resets the passphrase/key, cross signing and megolm backup + * Resets the passphrase/key, cross signing and megolm backup. */ HARD_RESET } diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/SupportedVerificationMethodsProvider.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/SupportedVerificationMethodsProvider.kt index 6bbd37a3a8..f8e63f0ea5 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/SupportedVerificationMethodsProvider.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/SupportedVerificationMethodsProvider.kt @@ -26,7 +26,7 @@ class SupportedVerificationMethodsProvider @Inject constructor( ) { /** * Provide the list of supported method by Element, with or without the QR_CODE_SCAN, depending if a back camera - * is available + * is available. */ fun provide(): List { return mutableListOf( diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt index 9c6c22b6ca..dc79136cad 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheet.kt @@ -95,14 +95,12 @@ class VerificationBottomSheet : VectorBaseBottomSheetDialogFragment dismiss() is VerificationBottomSheetViewEvents.AccessSecretStore -> { - secretStartForActivityResult.launch( - SharedSecureStorageActivity.newIntent( - requireContext(), - null, // use default key - listOf(MASTER_KEY_SSSS_NAME, USER_SIGNING_KEY_SSSS_NAME, SELF_SIGNING_KEY_SSSS_NAME, KEYBACKUP_SECRET_SSSS_NAME), - SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS - ) - ) + secretStartForActivityResult.launch(SharedSecureStorageActivity.newReadIntent( + requireContext(), + null, // use default key + listOf(MASTER_KEY_SSSS_NAME, USER_SIGNING_KEY_SSSS_NAME, SELF_SIGNING_KEY_SSSS_NAME, KEYBACKUP_SECRET_SSSS_NAME), + SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS + )) } is VerificationBottomSheetViewEvents.ModalError -> { MaterialAlertDialogBuilder(requireContext()) diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewEvents.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewEvents.kt index ba47de18fc..13d211bf9d 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewEvents.kt @@ -19,7 +19,7 @@ package im.vector.app.features.crypto.verification import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for the verification bottom sheet + * Transient events for the verification bottom sheet. */ sealed class VerificationBottomSheetViewEvents : VectorViewEvents { object Dismiss : VerificationBottomSheetViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt index 44694404bc..b65ce4b30b 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/VerificationBottomSheetViewModel.kt @@ -42,7 +42,6 @@ import org.matrix.android.sdk.api.session.crypto.crosssigning.isVerified import org.matrix.android.sdk.api.session.crypto.keysbackup.KeysBackupLastVersionResult import org.matrix.android.sdk.api.session.crypto.keysbackup.computeRecoveryKey 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.verification.CancelCode import org.matrix.android.sdk.api.session.crypto.verification.IncomingSasVerificationTransaction import org.matrix.android.sdk.api.session.crypto.verification.PendingVerificationRequest @@ -424,6 +423,11 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( } private fun tentativeRestoreBackup(res: Map?) { + // It's not a good idea to download the full backup, it might take very long + // and use a lot of resources + // Just check that the key is valid and store it, the backup will be used megolm session per + // megolm session when an UISI is encountered + viewModelScope.launch(Dispatchers.IO) { try { val secret = res?.get(KEYBACKUP_SECRET_SSSS_NAME) ?: return@launch Unit.also { @@ -434,17 +438,13 @@ class VerificationBottomSheetViewModel @AssistedInject constructor( session.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() ?: return@launch - awaitCallback { - session.cryptoService().keysBackupService().restoreKeysWithRecoveryKey( - version, - computeRecoveryKey(secret.fromBase64()), - null, - null, - null, - it - ) + val recoveryKey = computeRecoveryKey(secret.fromBase64()) + val isValid = awaitCallback { + session.cryptoService().keysBackupService().isValidRecoveryKeyForCurrentVersion(recoveryKey, it) + } + if (isValid) { + session.cryptoService().keysBackupService().saveBackupRecoveryKey(recoveryKey, version.version) } - awaitCallback { session.cryptoService().keysBackupService().trustKeysBackupVersion(version, true, it) } diff --git a/vector/src/main/java/im/vector/app/features/crypto/verification/epoxy/BottomSheetVerificationQrCodeItem.kt b/vector/src/main/java/im/vector/app/features/crypto/verification/epoxy/BottomSheetVerificationQrCodeItem.kt index 41c92fa76f..0041631986 100644 --- a/vector/src/main/java/im/vector/app/features/crypto/verification/epoxy/BottomSheetVerificationQrCodeItem.kt +++ b/vector/src/main/java/im/vector/app/features/crypto/verification/epoxy/BottomSheetVerificationQrCodeItem.kt @@ -24,7 +24,7 @@ import im.vector.app.core.epoxy.VectorEpoxyModel import im.vector.app.core.ui.views.QrCodeImageView /** - * An Epoxy item displaying a QR code + * An Epoxy item displaying a QR code. */ @EpoxyModelClass(layout = R.layout.item_verification_qr_code) abstract class BottomSheetVerificationQrCodeItem : VectorEpoxyModel() { diff --git a/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt b/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt index 7b7896316b..5023c6bd83 100644 --- a/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt +++ b/vector/src/main/java/im/vector/app/features/form/FormEditTextItem.kt @@ -128,7 +128,7 @@ abstract class FormEditTextItem : VectorEpoxyModel() { /** * Configure the inputType of the EditText, input type should be always defined * especially when we want to use a single line, we set the InputType to InputType.TYPE_CLASS_TEXT - * while the default for the EditText is InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE + * while the default for the EditText is InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE. */ private fun configureInputType(holder: Holder) { val newInputType = @@ -146,7 +146,7 @@ abstract class FormEditTextItem : VectorEpoxyModel() { /** * Configure the imeOptions of the EditText, when imeOptions are not defined by the developer * EditorInfo.IME_ACTION_NEXT will be used for singleLine EditTexts to disable "new line" - * while EditorInfo.IME_ACTION_NONE will be used for all the other cases + * while EditorInfo.IME_ACTION_NONE will be used for all the other cases. */ private fun configureImeOptions(holder: Holder) { holder.textInputEditText.imeOptions = diff --git a/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt b/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt index fd2862f5f0..cb24382e6a 100644 --- a/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt +++ b/vector/src/main/java/im/vector/app/features/home/AvatarRenderer.kt @@ -53,9 +53,8 @@ import java.io.File import javax.inject.Inject /** - * This helper centralise ways to retrieve avatar into ImageView or even generic Target + * This helper centralise ways to retrieve avatar into ImageView or even generic Target. */ - class AvatarRenderer @Inject constructor(private val activeSessionHolder: ActiveSessionHolder, private val matrixItemColorProvider: MatrixItemColorProvider, private val dimensionConverter: DimensionConverter) { diff --git a/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt b/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt index cc202868cc..ee9340f37d 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeActivity.kt @@ -278,7 +278,7 @@ class HomeActivity : /** * Migrating from old threads io.element.thread to new m.thread needs an initial sync to - * sync and display existing messages appropriately + * sync and display existing messages appropriately. */ private fun migrateThreadsIfNeeded(checkSession: Boolean) { if (checkSession) { @@ -301,7 +301,7 @@ class HomeActivity : } /** - * Clear cache and restart to invoke an initial sync for threads migration + * Clear cache and restart to invoke an initial sync for threads migration. */ private fun handleThreadsMigration() { Timber.i("----> Threads Migration detected, clearing cache and sync...") diff --git a/vector/src/main/java/im/vector/app/features/home/HomeActivitySharedAction.kt b/vector/src/main/java/im/vector/app/features/home/HomeActivitySharedAction.kt index 6047a1e55e..d460efb564 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeActivitySharedAction.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeActivitySharedAction.kt @@ -19,7 +19,7 @@ package im.vector.app.features.home import im.vector.app.core.platform.VectorSharedAction /** - * Supported navigation actions for [HomeActivity] + * Supported navigation actions for [HomeActivity]. */ sealed class HomeActivitySharedAction : VectorSharedAction { object OpenDrawer : HomeActivitySharedAction() diff --git a/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt b/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt index 05973de49d..c47ca0880e 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeActivityViewModel.kt @@ -204,9 +204,9 @@ class HomeActivityViewModel @AssistedInject constructor( /** * After migration from riot to element some users reported that their - * push setting for the session was set to off + * push setting for the session was set to off. * In order to mitigate this, we want to display a popup once to the user - * giving him the option to review this setting + * giving him the option to review this setting. */ private fun checkSessionPushIsOn() { viewModelScope.launch(Dispatchers.IO) { diff --git a/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt b/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt index fc39165a7e..a4f1566eff 100644 --- a/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/HomeDetailViewModel.kt @@ -59,7 +59,7 @@ import timber.log.Timber /** * View model used to update the home bottom bar notification counts, observe the sync state and - * change the selected room list view + * change the selected room list view. */ class HomeDetailViewModel @AssistedInject constructor( @Assisted initialState: HomeDetailViewState, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt index be5f9c0bb4..65d18105fe 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/AutoCompleter.kt @@ -53,7 +53,7 @@ class AutoCompleter @AssistedInject constructor( @Assisted val isInThreadTimeline: Boolean, private val avatarRenderer: AvatarRenderer, private val commandAutocompletePolicy: CommandAutocompletePolicy, - AutocompleteCommandPresenterFactory: AutocompleteCommandPresenter.Factory, + autocompleteCommandPresenterFactory: AutocompleteCommandPresenter.Factory, private val autocompleteMemberPresenterFactory: AutocompleteMemberPresenter.Factory, private val autocompleteRoomPresenter: AutocompleteRoomPresenter, private val autocompleteGroupPresenter: AutocompleteGroupPresenter, @@ -68,7 +68,7 @@ class AutoCompleter @AssistedInject constructor( } private val autocompleteCommandPresenter: AutocompleteCommandPresenter by lazy { - AutocompleteCommandPresenterFactory.create(isInThreadTimeline) + autocompleteCommandPresenterFactory.create(isInThreadTimeline) } private var editText: EditText? = null diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedAction.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedAction.kt index 1b4435bf57..a72aca31a0 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedAction.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedAction.kt @@ -19,7 +19,7 @@ package im.vector.app.features.home.room.detail import im.vector.app.core.platform.VectorSharedAction /** - * Supported navigation actions for [RoomDetailActivity] + * Supported navigation actions for [RoomDetailActivity]. */ sealed class RoomDetailSharedAction : VectorSharedAction { data class SwitchToRoom(val roomId: String) : RoomDetailSharedAction() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedActionViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedActionViewModel.kt index 065be461f3..830134309a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedActionViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailSharedActionViewModel.kt @@ -19,6 +19,6 @@ import im.vector.app.core.platform.VectorSharedActionViewModel import javax.inject.Inject /** - * Activity shared view model + * Activity shared view model. */ class RoomDetailSharedActionViewModel @Inject constructor() : VectorSharedActionViewModel() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt index f36a1141b8..b168bfea97 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/RoomDetailViewEvents.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.util.MatrixItem import java.io.File /** - * Transient events for RoomDetail + * Transient events for RoomDetail. */ sealed class RoomDetailViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable, val showInDialog: Boolean = false) : RoomDetailViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt index de1d512c75..635b00c05d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineFragment.kt @@ -726,8 +726,8 @@ class TimelineFragment @Inject constructor( } /** - * Ensure dismiss actions only trigger when the fragment is in the started state - * EmojiPopup by default dismisses onViewDetachedFromWindow, this can cause race conditions with onDestroyView + * Ensure dismiss actions only trigger when the fragment is in the started state. + * EmojiPopup by default dismisses onViewDetachedFromWindow, this can cause race conditions with onDestroyView. */ private fun EmojiPopup.Builder.setOnEmojiPopupDismissListenerLifecycleAware(action: () -> Unit): EmojiPopup.Builder { return setOnEmojiPopupDismissListener { @@ -1167,7 +1167,7 @@ class TimelineFragment @Inject constructor( } /** - * Update menu thread notification badge appropriately + * Update menu thread notification badge appropriately. */ private fun updateMenuThreadNotificationBadge(menu: Menu, state: RoomDetailViewState) { val menuThreadList = menu.findItem(R.id.menu_timeline_thread_list).actionView @@ -1190,7 +1190,7 @@ class TimelineFragment @Inject constructor( } /** - * View and highlight the original root thread message in the main timeline + * View and highlight the original root thread message in the main timeline. */ private fun handleViewInRoomAction() { getRootThreadEventId()?.let { @@ -1529,7 +1529,7 @@ class TimelineFragment @Inject constructor( views.composerLayout.views.composerEmojiButton.isVisible = vectorPreferences.showEmojiKeyboard() - if (isThreadTimeLine() && timelineArgs.threadTimelineArgs?.startsThread == true) { + if (isThreadTimeLine() && timelineArgs.threadTimelineArgs?.showKeyboard == true) { // Show keyboard when the user started a thread views.composerLayout.views.composerEditText.showKeyboard(andRequestFocus = true) } @@ -2443,7 +2443,11 @@ class TimelineFragment @Inject constructor( private fun onReplyInThreadClicked(action: EventSharedAction.ReplyInThread) { if (vectorPreferences.areThreadMessagesEnabled()) { - navigateToThreadTimeline(action.eventId, action.startsThread) + navigateToThreadTimeline( + rootThreadEventId = action.eventId, + startsThread = action.startsThread, + showKeyboard = true + ) } else { displayThreadsBetaOptInDialog() } @@ -2451,10 +2455,9 @@ class TimelineFragment @Inject constructor( /** * Navigate to Threads timeline for the specified rootThreadEventId - * using the ThreadsActivity + * using the ThreadsActivity. */ - - private fun navigateToThreadTimeline(rootThreadEventId: String, startsThread: Boolean = false) { + private fun navigateToThreadTimeline(rootThreadEventId: String, startsThread: Boolean = false, showKeyboard: Boolean = false) { analyticsTracker.capture(Interaction.Name.MobileRoomThreadSummaryItem.toAnalyticsInteraction()) context?.let { val roomThreadDetailArgs = ThreadTimelineArgs( @@ -2463,7 +2466,8 @@ class TimelineFragment @Inject constructor( displayName = timelineViewModel.getRoomSummary()?.displayName, avatarUrl = timelineViewModel.getRoomSummary()?.avatarUrl, roomEncryptionTrustLevel = timelineViewModel.getRoomSummary()?.roomEncryptionTrustLevel, - rootThreadEventId = rootThreadEventId + rootThreadEventId = rootThreadEventId, + showKeyboard = showKeyboard ) navigator.openThread(it, roomThreadDetailArgs) } @@ -2490,9 +2494,8 @@ class TimelineFragment @Inject constructor( /** * Navigate to Threads list for the current room - * using the ThreadsActivity + * using the ThreadsActivity. */ - private fun navigateToThreadList() { analyticsTracker.capture(Interaction.Name.MobileRoomThreadListButton.toAnalyticsInteraction()) context?.let { @@ -2619,12 +2622,12 @@ class TimelineFragment @Inject constructor( } /** - * Returns true if the current room is a Thread room, false otherwise + * Returns true if the current room is a Thread room, false otherwise. */ private fun isThreadTimeLine(): Boolean = timelineArgs.threadTimelineArgs?.rootThreadEventId != null /** - * Returns the root thread event if we are in a thread room, otherwise returns null + * Returns the root thread event if we are in a thread room, otherwise returns null. */ fun getRootThreadEventId(): String? = timelineArgs.threadTimelineArgs?.rootThreadEventId } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt index fc31c72df3..e81bab3e3e 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/TimelineViewModel.kt @@ -232,7 +232,7 @@ class TimelineViewModel @AssistedInject constructor( } /** - * Threads specific initialization + * Threads specific initialization. */ private fun initThreads() { markThreadTimelineAsReadLocal() @@ -351,8 +351,8 @@ class TimelineViewModel @AssistedInject constructor( } /** - * Mark the thread as read, while the user navigated within the thread - * This is a local implementation has nothing to do with APIs + * Mark the thread as read, while the user navigated within the thread. + * This is a local implementation has nothing to do with APIs. */ private fun markThreadTimelineAsReadLocal() { initialState.rootThreadEventId?.let { @@ -363,7 +363,7 @@ class TimelineViewModel @AssistedInject constructor( } /** - * Observe local unread threads + * Observe local unread threads. */ private fun observeLocalThreadNotifications() { room.flow() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/AudioMessageHelper.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/AudioMessageHelper.kt index f4cab3305d..98694d9c9e 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/AudioMessageHelper.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/AudioMessageHelper.kt @@ -110,7 +110,7 @@ class AudioMessageHelper @Inject constructor( } /** - * When entering in playback mode actually + * When entering in playback mode actually. */ fun pauseRecording() { voiceRecorder.stopRecord() diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt index 58ec9c76bc..eca5c846ca 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewModel.kt @@ -818,7 +818,7 @@ class MessageComposerViewModel @AssistedInject constructor( } /** - * Convert a send mode to a draft and save the draft + * Convert a send mode to a draft and save the draft. */ private fun handleSaveTextDraft(draft: String) = withState { session.coroutineScope.launch { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt index 016a39d919..75a6c1e912 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/MessageComposerViewState.kt @@ -25,11 +25,11 @@ import kotlin.random.Random /** * Describes the current send mode: - * REGULAR: sends the text as a regular message - * QUOTE: User is currently quoting a message - * EDIT: User is currently editing an existing message + * REGULAR: sends the text as a regular message; + * QUOTE: User is currently quoting a message; + * EDIT: User is currently editing an existing message. * - * Depending on the state the bottom toolbar will change (icons/preview/actions...) + * Depending on the state the bottom toolbar will change (icons/preview/actions...). */ sealed interface SendMode { data class Regular( diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt index b898aaf114..4350ad6a7d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageRecorderView.kt @@ -225,7 +225,7 @@ class VoiceMessageRecorderView @JvmOverloads constructor( override fun onUpdate(state: AudioMessagePlaybackTracker.Listener.State) { when (state) { is AudioMessagePlaybackTracker.Listener.State.Recording -> { - voiceMessageViews.renderRecordingWaveform(state.amplitudeList.toTypedArray()) + voiceMessageViews.renderRecordingWaveform(state.amplitudeList.toList()) } is AudioMessagePlaybackTracker.Listener.State.Playing -> { voiceMessageViews.renderPlaying(state) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt index 0256064af2..0a093221a6 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/composer/voice/VoiceMessageViews.kt @@ -345,10 +345,10 @@ class VoiceMessageViews( } } - fun renderRecordingWaveform(amplitudeList: Array) { + fun renderRecordingWaveform(amplitudeList: List) { views.voicePlaybackWaveform.doOnLayout { waveFormView -> val waveformColor = ThemeUtils.getColor(waveFormView.context, R.attr.vctr_content_quaternary) - amplitudeList.iterator().forEach { + amplitudeList.forEach { (waveFormView as AudioWaveformView).add(AudioWaveformView.FFT(it.toFloat(), waveformColor)) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsBottomSheet.kt index db80b02a6b..dfb23d25c8 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsBottomSheet.kt @@ -40,7 +40,7 @@ data class DisplayReadReceiptArgs( ) : Parcelable /** - * Bottom sheet displaying list of read receipts for a given event ordered by descending timestamp + * Bottom sheet displaying list of read receipts for a given event ordered by descending timestamp. */ @AndroidEntryPoint class DisplayReadReceiptsBottomSheet : diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt index c316c556b0..5246906223 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/readreceipts/DisplayReadReceiptsController.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.session.Session import javax.inject.Inject /** - * Epoxy controller for read receipt event list + * Epoxy controller for read receipt event list. */ class DisplayReadReceiptsController @Inject constructor(private val dateFormatter: VectorDateFormatter, private val session: Session, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt index 1952e598a6..011258f126 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchFragment.kt @@ -121,14 +121,25 @@ class SearchFragment @Inject constructor( override fun onItemClicked(event: Event) = navigateToEvent(event) + override fun onThreadSummaryClicked(event: Event) { + navigateToEvent(event, true) + } + /** * Navigate and highlight the event. If this is a thread event, * user will be redirected to the appropriate thread room * @param event the event to navigate and highlight + * @param forceNavigateToThread force navigate within the thread (ex. when user clicks on thread summary) */ - private fun navigateToEvent(event: Event) { + private fun navigateToEvent(event: Event, forceNavigateToThread: Boolean = false) { val roomId = event.roomId ?: return - event.getRootThreadEventId()?.let { + val rootThreadEventId = if (forceNavigateToThread) { + event.eventId + } else { + event.getRootThreadEventId() + } + + rootThreadEventId?.let { val threadTimelineArgs = ThreadTimelineArgs( roomId = roomId, displayName = fragmentArgs.roomDisplayName, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultController.kt index 913e440a20..81e4d8fd5f 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultController.kt @@ -58,6 +58,7 @@ class SearchResultController @Inject constructor( interface Listener { fun onItemClicked(event: Event) + fun onThreadSummaryClicked(event: Event) fun loadMore() } @@ -134,6 +135,7 @@ class SearchResultController @Inject constructor( .threadSummaryFormatted(displayableEventFormatter.formatThreadSummary(event.threadDetails?.threadSummaryLatestEvent).toString()) .areThreadMessagesEnabled(userPreferencesProvider.areThreadMessagesEnabled()) .listener { listener?.onItemClicked(eventAndSender.event) } + .threadSummaryListener { listener?.onThreadSummaryClicked(eventAndSender.event) } .let { result.add(it) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultItem.kt index 3e141ab0e9..d92dcdd3ef 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/search/SearchResultItem.kt @@ -46,6 +46,7 @@ abstract class SearchResultItem : VectorEpoxyModel() { @EpoxyAttribute var areThreadMessagesEnabled: Boolean = false @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var listener: ClickListener? = null + @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var threadSummaryListener: ClickListener? = null override fun bind(holder: Holder) { super.bind(holder) @@ -66,23 +67,24 @@ abstract class SearchResultItem : VectorEpoxyModel() { val displayName = it.threadSummarySenderInfo?.displayName val avatarUrl = it.threadSummarySenderInfo?.avatarUrl avatarRenderer.render(MatrixItem.UserItem(userId, displayName, avatarUrl), holder.threadSummaryAvatarImageView) + holder.threadSummaryContainer.onClick(threadSummaryListener) } else { showFromThread(holder) } } ?: run { - holder.threadSummaryConstraintLayout.isVisible = false + holder.threadSummaryContainer.isVisible = false holder.fromThreadConstraintLayout.isVisible = false } } } private fun showThreadSummary(holder: Holder, show: Boolean = true) { - holder.threadSummaryConstraintLayout.isVisible = show + holder.threadSummaryContainer.isVisible = show holder.fromThreadConstraintLayout.isVisible = !show } private fun showFromThread(holder: Holder, show: Boolean = true) { - holder.threadSummaryConstraintLayout.isVisible = !show + holder.threadSummaryContainer.isVisible = !show holder.fromThreadConstraintLayout.isVisible = show } @@ -91,7 +93,7 @@ abstract class SearchResultItem : VectorEpoxyModel() { val memberNameView by bind(R.id.messageMemberNameView) val timeView by bind(R.id.messageTimeView) val contentView by bind(R.id.messageContentView) - val threadSummaryConstraintLayout by bind(R.id.searchThreadSummaryConstraintLayout) + val threadSummaryContainer by bind(R.id.searchThreadSummaryContainer) val threadSummaryCounterTextView by bind(R.id.messageThreadSummaryCounterTextView) val threadSummaryAvatarImageView by bind(R.id.messageThreadSummaryAvatarImageView) val threadSummaryInfoTextView by bind(R.id.messageThreadSummaryInfoTextView) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt index 6c9f7ac4ff..a601870ae8 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/TimelineEventController.kt @@ -97,7 +97,7 @@ class TimelineEventController @Inject constructor( ) : EpoxyController(backgroundHandler, backgroundHandler), Timeline.Listener, EpoxyController.Interceptor { /** - * This is a partial state of the RoomDetailViewState + * This is a partial state of the RoomDetailViewState. */ data class PartialState( val unreadState: UnreadState = UnreadState.Unknown, @@ -609,7 +609,7 @@ class TimelineEventController @Inject constructor( } /** - * Return true if added + * Return true if added. */ private fun LoadingItem_.addWhenLoading(direction: Timeline.Direction): Boolean { val host = this@TimelineEventController diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/LocationUiData.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/LocationUiData.kt index c50c649221..073dda626f 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/LocationUiData.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/LocationUiData.kt @@ -19,7 +19,7 @@ package im.vector.app.features.home.room.detail.timeline.action import im.vector.app.features.home.room.detail.timeline.helper.LocationPinProvider /** - * Data used to display Location data in the message bottom sheet + * Data used to display Location data in the message bottom sheet. */ data class LocationUiData( val locationUrl: String, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionState.kt index 57b2912aff..f547734651 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionState.kt @@ -25,7 +25,7 @@ import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent /** - * Quick reactions state + * Quick reactions state. */ data class ToggleState( val reaction: String, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsAnimator.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsAnimator.kt index 5530abf839..a94cca168d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsAnimator.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsAnimator.kt @@ -21,7 +21,7 @@ import androidx.recyclerview.widget.DefaultItemAnimator private const val ANIM_DURATION_IN_MILLIS = 300L /** - * We only want to animate the expand of the "Report content" submenu + * We only want to animate the expand of the "Report content" submenu. */ class MessageActionsAnimator : DefaultItemAnimator() { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsBottomSheet.kt index 24c5679438..53d9e2aa99 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsBottomSheet.kt @@ -30,7 +30,7 @@ import im.vector.app.features.home.room.detail.timeline.item.MessageInformationD import javax.inject.Inject /** - * Bottom sheet fragment that shows a message preview with list of contextual actions + * Bottom sheet fragment that shows a message preview with list of contextual actions. */ @AndroidEntryPoint class MessageActionsBottomSheet : diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt index 41916c609d..ade08fdfed 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsEpoxyController.kt @@ -54,7 +54,7 @@ import org.matrix.android.sdk.api.session.room.send.SendState import javax.inject.Inject /** - * Epoxy controller for message action list + * Epoxy controller for message action list. */ class MessageActionsEpoxyController @Inject constructor( private val stringProvider: StringProvider, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt index 2f9f2331e0..4bc513284b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageActionsViewModel.kt @@ -450,7 +450,7 @@ class MessageActionsViewModel @AssistedInject constructor( /** * Determine whether or not the Reply In Thread bottom sheet action will be visible - * to the user + * to the user. */ private fun canReplyInThread(event: TimelineEvent, messageContent: MessageContent?, @@ -481,7 +481,7 @@ class MessageActionsViewModel @AssistedInject constructor( } /** - * Determine whether or not the view in room action will be available for the current event + * Determine whether or not the view in room action will be available for the current event. */ private fun canViewInRoom(event: TimelineEvent, messageContent: MessageContent?, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageSharedActionViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageSharedActionViewModel.kt index b6023333b1..a06f85ad3f 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageSharedActionViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/action/MessageSharedActionViewModel.kt @@ -19,7 +19,7 @@ import im.vector.app.core.platform.VectorSharedActionViewModel import javax.inject.Inject /** - * Activity shared view model to handle message actions + * Activity shared view model to handle message actions. */ class MessageSharedActionViewModel @Inject constructor() : VectorSharedActionViewModel() { var pendingAction: EventSharedAction? = null diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryBottomSheet.kt index 0548a6ad18..d01a607d17 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryBottomSheet.kt @@ -32,7 +32,7 @@ import im.vector.app.features.home.room.detail.timeline.item.MessageInformationD import javax.inject.Inject /** - * Bottom sheet displaying list of edits for a given event ordered by timestamp + * Bottom sheet displaying list of edits for a given event ordered by timestamp. */ @AndroidEntryPoint class ViewEditHistoryBottomSheet : diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt index f96ee7eee2..b92548dd5e 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/edithistory/ViewEditHistoryEpoxyController.kt @@ -44,7 +44,7 @@ import java.util.Calendar import javax.inject.Inject /** - * Epoxy controller for edit history list + * Epoxy controller for edit history list. */ class ViewEditHistoryEpoxyController @Inject constructor( private val stringProvider: StringProvider, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationMessageItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationMessageItemFactory.kt deleted file mode 100644 index d233deffb8..0000000000 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationMessageItemFactory.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2022 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package im.vector.app.features.home.room.detail.timeline.factory - -import im.vector.app.core.epoxy.VectorEpoxyModel -import im.vector.app.core.utils.DimensionConverter -import im.vector.app.features.home.room.detail.timeline.helper.AvatarSizeProvider -import im.vector.app.features.home.room.detail.timeline.helper.TimelineMediaSizeProvider -import im.vector.app.features.home.room.detail.timeline.item.AbsMessageItem -import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationStartItem -import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationStartItem_ -import org.matrix.android.sdk.api.extensions.orFalse -import org.matrix.android.sdk.api.session.room.model.message.MessageBeaconInfoContent -import javax.inject.Inject - -class LiveLocationMessageItemFactory @Inject constructor( - private val dimensionConverter: DimensionConverter, - private val timelineMediaSizeProvider: TimelineMediaSizeProvider, - private val avatarSizeProvider: AvatarSizeProvider, -) { - - fun create( - beaconInfoContent: MessageBeaconInfoContent, - highlight: Boolean, - attributes: AbsMessageItem.Attributes, - ): VectorEpoxyModel<*>? { - // TODO handle location received and stopped states - return when { - isLiveRunning(beaconInfoContent) -> buildStartLiveItem(highlight, attributes) - else -> null - } - } - - private fun isLiveRunning(beaconInfoContent: MessageBeaconInfoContent): Boolean { - // TODO when we will use aggregatedSummary, check if the live has timed out as well - return beaconInfoContent.isLive.orFalse() - } - - private fun buildStartLiveItem( - highlight: Boolean, - attributes: AbsMessageItem.Attributes, - ): MessageLiveLocationStartItem { - val width = timelineMediaSizeProvider.getMaxSize().first - val height = dimensionConverter.dpToPx(MessageItemFactory.MESSAGE_LOCATION_ITEM_HEIGHT_IN_DP) - - return MessageLiveLocationStartItem_() - .attributes(attributes) - .mapWidth(width) - .mapHeight(height) - .highlighted(highlight) - .leftGuideline(avatarSizeProvider.leftGuideline) - } -} diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationShareMessageItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationShareMessageItemFactory.kt new file mode 100644 index 0000000000..479a742369 --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/LiveLocationShareMessageItemFactory.kt @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.home.room.detail.timeline.factory + +import im.vector.app.core.date.VectorDateFormatter +import im.vector.app.core.epoxy.VectorEpoxyModel +import im.vector.app.core.resources.DateProvider +import im.vector.app.core.utils.DimensionConverter +import im.vector.app.features.home.room.detail.timeline.helper.AvatarSizeProvider +import im.vector.app.features.home.room.detail.timeline.helper.LocationPinProvider +import im.vector.app.features.home.room.detail.timeline.helper.TimelineMediaSizeProvider +import im.vector.app.features.home.room.detail.timeline.item.AbsMessageItem +import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationInactiveItem +import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationInactiveItem_ +import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationItem +import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationItem_ +import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationStartItem +import im.vector.app.features.home.room.detail.timeline.item.MessageLiveLocationStartItem_ +import im.vector.app.features.location.INITIAL_MAP_ZOOM_IN_TIMELINE +import im.vector.app.features.location.UrlMapProvider +import im.vector.app.features.location.toLocationData +import org.matrix.android.sdk.api.extensions.orFalse +import org.matrix.android.sdk.api.session.Session +import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent +import org.threeten.bp.LocalDateTime +import timber.log.Timber +import javax.inject.Inject + +class LiveLocationShareMessageItemFactory @Inject constructor( + private val session: Session, + private val dimensionConverter: DimensionConverter, + private val timelineMediaSizeProvider: TimelineMediaSizeProvider, + private val avatarSizeProvider: AvatarSizeProvider, + private val urlMapProvider: UrlMapProvider, + private val locationPinProvider: LocationPinProvider, + private val vectorDateFormatter: VectorDateFormatter, +) { + + fun create( + event: TimelineEvent, + highlight: Boolean, + attributes: AbsMessageItem.Attributes, + ): VectorEpoxyModel<*>? { + val liveLocationShareSummaryData = getLiveLocationShareSummaryData(event) + val item = when (val currentState = getViewState(liveLocationShareSummaryData)) { + LiveLocationShareViewState.Inactive -> buildInactiveItem(highlight, attributes) + LiveLocationShareViewState.Loading -> buildLoadingItem(highlight, attributes) + is LiveLocationShareViewState.Running -> buildRunningItem(highlight, attributes, currentState) + LiveLocationShareViewState.Unkwown -> null + } + item?.layout(attributes.informationData.messageLayout.layoutRes) + + return item + } + + private fun buildInactiveItem( + highlight: Boolean, + attributes: AbsMessageItem.Attributes, + ): MessageLiveLocationInactiveItem { + val width = timelineMediaSizeProvider.getMaxSize().first + val height = dimensionConverter.dpToPx(MessageItemFactory.MESSAGE_LOCATION_ITEM_HEIGHT_IN_DP) + + return MessageLiveLocationInactiveItem_() + .attributes(attributes) + .mapWidth(width) + .mapHeight(height) + .highlighted(highlight) + .leftGuideline(avatarSizeProvider.leftGuideline) + } + + private fun buildLoadingItem( + highlight: Boolean, + attributes: AbsMessageItem.Attributes, + ): MessageLiveLocationStartItem { + val width = timelineMediaSizeProvider.getMaxSize().first + val height = dimensionConverter.dpToPx(MessageItemFactory.MESSAGE_LOCATION_ITEM_HEIGHT_IN_DP) + + return MessageLiveLocationStartItem_() + .attributes(attributes) + .mapWidth(width) + .mapHeight(height) + .highlighted(highlight) + .leftGuideline(avatarSizeProvider.leftGuideline) + } + + private fun buildRunningItem( + highlight: Boolean, + attributes: AbsMessageItem.Attributes, + runningState: LiveLocationShareViewState.Running, + ): MessageLiveLocationItem { + // TODO only render location if enabled in preferences: to be handled in a next PR + val width = timelineMediaSizeProvider.getMaxSize().first + val height = dimensionConverter.dpToPx(MessageItemFactory.MESSAGE_LOCATION_ITEM_HEIGHT_IN_DP) + + val locationUrl = runningState.lastGeoUri.toLocationData()?.let { + urlMapProvider.buildStaticMapUrl(it, INITIAL_MAP_ZOOM_IN_TIMELINE, width, height) + } + + return MessageLiveLocationItem_() + .attributes(attributes) + .locationUrl(locationUrl) + .mapWidth(width) + .mapHeight(height) + .locationUserId(attributes.informationData.senderId) + .locationPinProvider(locationPinProvider) + .highlighted(highlight) + .leftGuideline(avatarSizeProvider.leftGuideline) + .currentUserId(session.myUserId) + .endOfLiveDateTime(runningState.endOfLiveDateTime) + .vectorDateFormatter(vectorDateFormatter) + } + + private fun getViewState(liveLocationShareSummaryData: LiveLocationShareSummaryData?): LiveLocationShareViewState { + return when { + liveLocationShareSummaryData?.isActive == null -> LiveLocationShareViewState.Unkwown + liveLocationShareSummaryData.isActive.not() || isLiveTimedOut(liveLocationShareSummaryData) -> LiveLocationShareViewState.Inactive + liveLocationShareSummaryData.isActive && liveLocationShareSummaryData.lastGeoUri.isNullOrEmpty() -> LiveLocationShareViewState.Loading + else -> + LiveLocationShareViewState.Running( + liveLocationShareSummaryData.lastGeoUri.orEmpty(), + getEndOfLiveDateTime(liveLocationShareSummaryData) + ) + }.also { viewState -> Timber.d("computed viewState: $viewState") } + } + + private fun isLiveTimedOut(liveLocationShareSummaryData: LiveLocationShareSummaryData): Boolean { + return getEndOfLiveDateTime(liveLocationShareSummaryData) + ?.let { endOfLive -> + // this will only cover users with different timezones but not users with manually time set + val now = LocalDateTime.now() + now.isAfter(endOfLive) + } + .orFalse() + } + + private fun getEndOfLiveDateTime(liveLocationShareSummaryData: LiveLocationShareSummaryData): LocalDateTime? { + return liveLocationShareSummaryData.endOfLiveTimestampMillis?.let { DateProvider.toLocalDateTime(timestamp = it) } + } + + private fun getLiveLocationShareSummaryData(event: TimelineEvent): LiveLocationShareSummaryData? { + return event.annotations?.liveLocationShareAggregatedSummary?.let { summary -> + LiveLocationShareSummaryData( + isActive = summary.isActive, + endOfLiveTimestampMillis = summary.endOfLiveTimestampMillis, + lastGeoUri = summary.lastLocationDataContent?.getBestLocationInfo()?.geoUri + ) + } + } + + private data class LiveLocationShareSummaryData( + val isActive: Boolean?, + val endOfLiveTimestampMillis: Long?, + val lastGeoUri: String?, + ) + + private sealed class LiveLocationShareViewState { + object Loading : LiveLocationShareViewState() + data class Running(val lastGeoUri: String, val endOfLiveDateTime: LocalDateTime?) : LiveLocationShareViewState() + object Inactive : LiveLocationShareViewState() + object Unkwown : LiveLocationShareViewState() + } +} diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt index b960e2c6a9..13f783cded 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/MessageItemFactory.kt @@ -148,7 +148,7 @@ class MessageItemFactory @Inject constructor( private val locationPinProvider: LocationPinProvider, private val vectorPreferences: VectorPreferences, private val urlMapProvider: UrlMapProvider, - private val liveLocationMessageItemFactory: LiveLocationMessageItemFactory, + private val liveLocationShareMessageItemFactory: LiveLocationShareMessageItemFactory, ) { // TODO inject this properly? @@ -216,7 +216,7 @@ class MessageItemFactory @Inject constructor( buildMessageTextItem(messageContent.body, false, informationData, highlight, callback, attributes) } } - is MessageBeaconInfoContent -> liveLocationMessageItemFactory.create(messageContent, highlight, attributes) + is MessageBeaconInfoContent -> liveLocationShareMessageItemFactory.create(params.event, highlight, attributes) else -> buildNotHandledMessageItem(messageContent, informationData, highlight, callback, attributes) } return messageItem?.apply { @@ -237,14 +237,14 @@ class MessageItemFactory @Inject constructor( urlMapProvider.buildStaticMapUrl(it, INITIAL_MAP_ZOOM_IN_TIMELINE, width, height) } - val userId = if (locationContent.isSelfLocation()) informationData.senderId else null + val locationUserId = if (locationContent.isSelfLocation()) informationData.senderId else null return MessageLocationItem_() .attributes(attributes) .locationUrl(locationUrl) .mapWidth(width) .mapHeight(height) - .userId(userId) + .locationUserId(locationUserId) .locationPinProvider(locationPinProvider) .highlighted(highlight) .leftGuideline(avatarSizeProvider.leftGuideline) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt index f4bcc1ba65..07ae9d66c3 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/TimelineItemFactory.kt @@ -100,7 +100,7 @@ class TimelineItemFactory @Inject constructor( // Message itemsX EventType.STICKER, in EventType.POLL_START, - EventType.MESSAGE -> messageItemFactory.create(params) + EventType.MESSAGE -> messageItemFactory.create(params) EventType.REDACTION, EventType.KEY_VERIFICATION_ACCEPT, EventType.KEY_VERIFICATION_START, @@ -113,14 +113,15 @@ class TimelineItemFactory @Inject constructor( EventType.CALL_NEGOTIATE, EventType.REACTION, in EventType.POLL_RESPONSE, - in EventType.POLL_END -> noticeItemFactory.create(params) + in EventType.POLL_END, + in EventType.BEACON_LOCATION_DATA -> noticeItemFactory.create(params) // Calls EventType.CALL_INVITE, EventType.CALL_HANGUP, EventType.CALL_REJECT, - EventType.CALL_ANSWER -> callItemFactory.create(params) + EventType.CALL_ANSWER -> callItemFactory.create(params) // Crypto - EventType.ENCRYPTED -> { + EventType.ENCRYPTED -> { if (event.root.isRedacted()) { // Redacted event, let the MessageItemFactory handle it messageItemFactory.create(params) @@ -129,11 +130,11 @@ class TimelineItemFactory @Inject constructor( } } EventType.KEY_VERIFICATION_CANCEL, - EventType.KEY_VERIFICATION_DONE -> { + EventType.KEY_VERIFICATION_DONE -> { verificationConclusionItemFactory.create(params) } // Unhandled event types - else -> { + else -> { // Should only happen when shouldShowHiddenEvents() settings is ON Timber.v("Type ${event.root.getClearType()} not handled") defaultItemFactory.create(params) diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt index ecd80297fc..e679b8d059 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/factory/VerificationItemFactory.kt @@ -39,9 +39,9 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageVerification import javax.inject.Inject /** - * Can creates verification conclusion items + * Can creates verification conclusion items. * Notice that not all KEY_VERIFICATION_DONE will be displayed in timeline, - * several checks are made to see if this conclusion is attached to a known request + * several checks are made to see if this conclusion is attached to a known request. */ class VerificationItemFactory @Inject constructor( private val messageColorProvider: MessageColorProvider, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt index 6296d31e48..4c92ab0e34 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/EventDetailsFormatter.kt @@ -56,7 +56,7 @@ class EventDetailsFormatter @Inject constructor( } /** - * Example: "1024 x 720 - 670 kB" + * Example: "1024 x 720 - 670 kB". */ private fun formatForImageMessage(event: Event): CharSequence? { return event.getClearContent().toModel()?.info @@ -64,7 +64,7 @@ class EventDetailsFormatter @Inject constructor( } /** - * Example: "02:45 - 1024 x 720 - 670 kB" + * Example: "02:45 - 1024 x 720 - 670 kB". */ private fun formatForVideoMessage(event: Event): CharSequence? { return event.getClearContent().toModel()?.videoInfo @@ -72,7 +72,7 @@ class EventDetailsFormatter @Inject constructor( } /** - * Example: "02:45 - 670 kB" + * Example: "02:45 - 670 kB". */ private fun formatForAudioMessage(event: Event): CharSequence? { return event.getClearContent().toModel()?.audioInfo @@ -84,7 +84,7 @@ class EventDetailsFormatter @Inject constructor( } /** - * Example: "670 kB - application/pdf" + * Example: "670 kB - application/pdf". */ private fun formatForFileMessage(event: Event): CharSequence? { return event.getClearContent().toModel()?.info diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt index 7ad0cb27c6..8e06b3ee5d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/format/NoticeEventFormatter.kt @@ -107,7 +107,8 @@ class NoticeEventFormatter @Inject constructor( EventType.REDACTION, EventType.STICKER, in EventType.POLL_RESPONSE, - in EventType.POLL_END -> formatDebug(timelineEvent.root) + in EventType.POLL_END, + in EventType.BEACON_LOCATION_DATA -> formatDebug(timelineEvent.root) else -> { Timber.v("Type $type not handled by this formatter") null diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt index 0312ac9e6f..44387759c8 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/AudioMessagePlaybackTracker.kt @@ -63,7 +63,7 @@ class AudioMessagePlaybackTracker @Inject constructor() { } /** - * Set state and notify the listeners + * Set state and notify the listeners. */ private fun setState(key: String, state: Listener.State) { states[key] = state diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt index f882840eee..7874f843e1 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageInformationDataFactory.kt @@ -44,8 +44,7 @@ import org.matrix.android.sdk.api.session.room.timeline.hasBeenEdited import javax.inject.Inject /** - * TODO Update this comment - * This class compute if data of an event (such has avatar, display name, ...) should be displayed, depending on the previous event in the timeline + * This class is responsible of building extra information data associated to a given event. */ class MessageInformationDataFactory @Inject constructor(private val session: Session, private val dateFormatter: VectorDateFormatter, @@ -119,7 +118,7 @@ class MessageInformationDataFactory @Inject constructor(private val session: Ses isFirstFromThisSender = isFirstFromThisSender, isLastFromThisSender = isLastFromThisSender, e2eDecoration = e2eDecoration, - sendStateDecoration = sendStateDecoration + sendStateDecoration = sendStateDecoration, ) } @@ -190,7 +189,7 @@ class MessageInformationDataFactory @Inject constructor(private val session: Ses /** * Tiles type message never show the sender information (like verification request), so we should repeat it for next message - * even if same sender + * even if same sender. */ private fun isTileTypeMessage(event: TimelineEvent?): Boolean { return when (event?.root?.getClearType()) { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt index 45c711ff93..737b0dc85d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/MessageItemAttributesFactory.kt @@ -57,6 +57,7 @@ class MessageItemAttributesFactory @Inject constructor( memberClickListener = { callback?.onMemberNameClicked(informationData) }, + callback = callback, reactionPillCallback = callback, avatarCallback = callback, threadCallback = callback, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineSettingsFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineSettingsFactory.kt index 8b7dcc9c72..18bdc2fdaa 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineSettingsFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/helper/TimelineSettingsFactory.kt @@ -26,7 +26,8 @@ class TimelineSettingsFactory @Inject constructor(private val userPreferencesPro return TimelineSettings( initialSize = 30, buildReadReceipts = userPreferencesProvider.shouldShowReadReceipts(), - rootThreadEventId = rootThreadEventId + rootThreadEventId = rootThreadEventId, + useLiveSenderInfo = userPreferencesProvider.showLiveSenderInfo() ) } } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageItem.kt index 30c366738d..b9d79d5818 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageItem.kt @@ -39,8 +39,8 @@ import org.matrix.android.sdk.api.session.threads.ThreadDetails import org.matrix.android.sdk.api.util.MatrixItem /** - * Base timeline item that adds an optional information bar with the sender avatar, name, time, send state - * Adds associated click listeners (on avatar, displayname) + * Base timeline item that adds an optional information bar with the sender avatar, name, time, send state. + * Adds associated click listeners (on avatar, displayname). */ abstract class AbsMessageItem : AbsBaseMessageItem() { @@ -178,6 +178,7 @@ abstract class AbsMessageItem : AbsBaseMessageItem override val itemLongClickListener: View.OnLongClickListener? = null, override val itemClickListener: ClickListener? = null, val memberClickListener: ClickListener? = null, + val callback: TimelineEventController.Callback? = null, override val reactionPillCallback: TimelineEventController.ReactionPillCallback? = null, val avatarCallback: TimelineEventController.AvatarCallback? = null, val threadCallback: TimelineEventController.ThreadCallback? = null, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt new file mode 100644 index 0000000000..f7146c24e9 --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/AbsMessageLocationItem.kt @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.home.room.detail.timeline.item + +import android.graphics.drawable.Drawable +import android.widget.ImageView +import android.widget.TextView +import androidx.annotation.IdRes +import androidx.core.view.isVisible +import androidx.core.view.updateLayoutParams +import com.airbnb.epoxy.EpoxyAttribute +import com.bumptech.glide.load.DataSource +import com.bumptech.glide.load.engine.GlideException +import com.bumptech.glide.load.resource.bitmap.RoundedCorners +import com.bumptech.glide.request.RequestListener +import com.bumptech.glide.request.RequestOptions +import com.bumptech.glide.request.target.Target +import im.vector.app.R +import im.vector.app.core.glide.GlideApp +import im.vector.app.core.utils.DimensionConverter +import im.vector.app.features.home.room.detail.timeline.helper.LocationPinProvider +import im.vector.app.features.home.room.detail.timeline.style.TimelineMessageLayout +import im.vector.app.features.home.room.detail.timeline.style.granularRoundedCorners + +abstract class AbsMessageLocationItem : AbsMessageItem() { + + @EpoxyAttribute + var locationUrl: String? = null + + @EpoxyAttribute + var locationUserId: String? = null + + @EpoxyAttribute + var mapWidth: Int = 0 + + @EpoxyAttribute + var mapHeight: Int = 0 + + @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) + var locationPinProvider: LocationPinProvider? = null + + override fun bind(holder: H) { + super.bind(holder) + renderSendState(holder.view, null) + bindMap(holder) + } + + private fun bindMap(holder: Holder) { + val location = locationUrl ?: return + val messageLayout = attributes.informationData.messageLayout + val imageCornerTransformation = if (messageLayout is TimelineMessageLayout.Bubble) { + messageLayout.cornersRadius.granularRoundedCorners() + } else { + val dimensionConverter = DimensionConverter(holder.view.resources) + RoundedCorners(dimensionConverter.dpToPx(8)) + } + holder.staticMapImageView.updateLayoutParams { + width = mapWidth + height = mapHeight + } + GlideApp.with(holder.staticMapImageView) + .load(location) + .apply(RequestOptions.centerCropTransform()) + .listener(object : RequestListener { + override fun onLoadFailed(e: GlideException?, + model: Any?, + target: Target?, + isFirstResource: Boolean): Boolean { + holder.staticMapPinImageView.setImageResource(R.drawable.ic_location_pin_failed) + holder.staticMapErrorTextView.isVisible = true + return false + } + + override fun onResourceReady(resource: Drawable?, + model: Any?, + target: Target?, + dataSource: DataSource?, + isFirstResource: Boolean): Boolean { + locationPinProvider?.create(locationUserId) { pinDrawable -> + // we are not using Glide since it does not display it correctly when there is no user photo + holder.staticMapPinImageView.setImageDrawable(pinDrawable) + } + holder.staticMapErrorTextView.isVisible = false + return false + } + }) + .transform(imageCornerTransformation) + .into(holder.staticMapImageView) + } + + abstract class Holder(@IdRes stubId: Int) : AbsMessageItem.Holder(stubId) { + val staticMapImageView by bind(R.id.staticMapImageView) + val staticMapPinImageView by bind(R.id.staticMapPinImageView) + val staticMapErrorTextView by bind(R.id.staticMapErrorTextView) + } +} diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BaseEventItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BaseEventItem.kt index 8ea761830a..b72f492c8c 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BaseEventItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/BaseEventItem.kt @@ -28,7 +28,7 @@ import im.vector.app.core.epoxy.VectorEpoxyModel import im.vector.app.core.platform.CheckableView /** - * Children must override getViewType() + * Children must override getViewType(). */ abstract class BaseEventItem : VectorEpoxyModel(), ItemWithEvents { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/DefaultLiveLocationShareStatusItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/DefaultLiveLocationShareStatusItem.kt new file mode 100644 index 0000000000..c421efda12 --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/DefaultLiveLocationShareStatusItem.kt @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.home.room.detail.timeline.item + +import android.content.res.Resources +import android.graphics.drawable.ColorDrawable +import android.widget.ImageView +import androidx.core.view.updateLayoutParams +import com.bumptech.glide.load.resource.bitmap.GranularRoundedCorners +import com.bumptech.glide.load.resource.bitmap.RoundedCorners +import im.vector.app.R +import im.vector.app.core.glide.GlideApp +import im.vector.app.core.utils.DimensionConverter +import im.vector.app.features.home.room.detail.timeline.style.TimelineMessageLayout +import im.vector.app.features.home.room.detail.timeline.style.granularRoundedCorners +import im.vector.app.features.themes.ThemeUtils + +/** + * Default implementation of common methods for item representing the status of a live location share. + */ +class DefaultLiveLocationShareStatusItem : LiveLocationShareStatusItem { + + override fun bindMap( + mapImageView: ImageView, + mapWidth: Int, + mapHeight: Int, + messageLayout: TimelineMessageLayout + ) { + val mapCornerTransformation = if (messageLayout is TimelineMessageLayout.Bubble) { + messageLayout.cornersRadius.granularRoundedCorners() + } else { + RoundedCorners(getDefaultLayoutCornerRadiusInDp(mapImageView.resources)) + } + mapImageView.updateLayoutParams { + width = mapWidth + height = mapHeight + } + GlideApp.with(mapImageView) + .load(R.drawable.bg_no_location_map) + .transform(mapCornerTransformation) + .into(mapImageView) + } + + override fun bindBottomBanner(bannerImageView: ImageView, messageLayout: TimelineMessageLayout) { + val imageCornerTransformation = if (messageLayout is TimelineMessageLayout.Bubble) { + GranularRoundedCorners( + 0f, + 0f, + messageLayout.cornersRadius.bottomEndRadius, + messageLayout.cornersRadius.bottomStartRadius + ) + } else { + val bottomCornerRadius = getDefaultLayoutCornerRadiusInDp(bannerImageView.resources).toFloat() + GranularRoundedCorners(0f, 0f, bottomCornerRadius, bottomCornerRadius) + } + GlideApp.with(bannerImageView) + .load(ColorDrawable(ThemeUtils.getColor(bannerImageView.context, android.R.attr.colorBackground))) + .transform(imageCornerTransformation) + .into(bannerImageView) + } + + private fun getDefaultLayoutCornerRadiusInDp(resources: Resources): Int { + val dimensionConverter = DimensionConverter(resources) + return dimensionConverter.dpToPx(8) + } +} diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/ItemWithEvents.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/ItemWithEvents.kt index d508023668..8730c1a00d 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/ItemWithEvents.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/ItemWithEvents.kt @@ -28,7 +28,7 @@ interface ItemWithEvents { fun isVisible(): Boolean = true /** - * Returns false if you want epoxy controller to rebuild the event each time a built is triggered + * Returns false if you want epoxy controller to rebuild the event each time a built is triggered. */ fun isCacheable(): Boolean = true } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingShareRequestCommon.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/LiveLocationShareStatusItem.kt similarity index 52% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingShareRequestCommon.kt rename to vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/LiveLocationShareStatusItem.kt index 97c369db3e..2f79f2fc9e 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/IncomingShareRequestCommon.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/LiveLocationShareStatusItem.kt @@ -1,5 +1,5 @@ /* - * Copyright 2020 The Matrix.org Foundation C.I.C. + * Copyright (c) 2022 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,23 +14,18 @@ * limitations under the License. */ -package org.matrix.android.sdk.internal.crypto +package im.vector.app.features.home.room.detail.timeline.item -internal interface IncomingShareRequestCommon { - /** - * The user id - */ - val userId: String? +import android.widget.ImageView +import im.vector.app.features.home.room.detail.timeline.style.TimelineMessageLayout - /** - * The device id - */ - val deviceId: String? +interface LiveLocationShareStatusItem { + fun bindMap( + mapImageView: ImageView, + mapWidth: Int, + mapHeight: Int, + messageLayout: TimelineMessageLayout + ) - /** - * The request id - */ - val requestId: String? - - val localCreationTimestamp: Long? + fun bindBottomBanner(bannerImageView: ImageView, messageLayout: TimelineMessageLayout) } diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageInformationData.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageInformationData.kt index 9620077fd8..258424c7de 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageInformationData.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageInformationData.kt @@ -42,7 +42,7 @@ data class MessageInformationData( val e2eDecoration: E2EDecoration = E2EDecoration.NONE, val sendStateDecoration: SendStateDecoration = SendStateDecoration.NONE, val isFirstFromThisSender: Boolean = false, - val isLastFromThisSender: Boolean = false + val isLastFromThisSender: Boolean = false, ) : Parcelable { val matrixItem: MatrixItem diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationInactiveItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationInactiveItem.kt new file mode 100644 index 0000000000..bb85316bf1 --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationInactiveItem.kt @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.home.room.detail.timeline.item + +import android.widget.ImageView +import com.airbnb.epoxy.EpoxyAttribute +import com.airbnb.epoxy.EpoxyModelClass +import im.vector.app.R + +@EpoxyModelClass(layout = R.layout.item_timeline_event_base) +abstract class MessageLiveLocationInactiveItem : + AbsMessageItem(), + LiveLocationShareStatusItem by DefaultLiveLocationShareStatusItem() { + + @EpoxyAttribute + var mapWidth: Int = 0 + + @EpoxyAttribute + var mapHeight: Int = 0 + + override fun bind(holder: Holder) { + super.bind(holder) + renderSendState(holder.view, null) + bindMap(holder.noLocationMapImageView, mapWidth, mapHeight, attributes.informationData.messageLayout) + bindBottomBanner(holder.bannerImageView, attributes.informationData.messageLayout) + } + + override fun getViewStubId() = STUB_ID + + class Holder : AbsMessageItem.Holder(STUB_ID) { + val bannerImageView by bind(R.id.locationLiveInactiveBanner) + val noLocationMapImageView by bind(R.id.locationLiveInactiveMap) + } + + companion object { + private const val STUB_ID = R.id.messageContentLiveLocationInactiveStub + } +} diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationItem.kt new file mode 100644 index 0000000000..838fbd46de --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationItem.kt @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.home.room.detail.timeline.item + +import androidx.core.view.isVisible +import com.airbnb.epoxy.EpoxyAttribute +import com.airbnb.epoxy.EpoxyModelClass +import im.vector.app.R +import im.vector.app.core.date.DateFormatKind +import im.vector.app.core.date.VectorDateFormatter +import im.vector.app.core.resources.toTimestamp +import im.vector.app.core.utils.DimensionConverter +import im.vector.app.features.home.room.detail.RoomDetailAction +import im.vector.app.features.home.room.detail.timeline.style.TimelineMessageLayout +import im.vector.app.features.location.live.LocationLiveMessageBannerView +import im.vector.app.features.location.live.LocationLiveMessageBannerViewState +import org.threeten.bp.LocalDateTime + +@EpoxyModelClass(layout = R.layout.item_timeline_event_base) +abstract class MessageLiveLocationItem : AbsMessageLocationItem() { + + @EpoxyAttribute + var currentUserId: String? = null + + @EpoxyAttribute + var endOfLiveDateTime: LocalDateTime? = null + + @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) + lateinit var vectorDateFormatter: VectorDateFormatter + + override fun bind(holder: Holder) { + super.bind(holder) + bindLocationLiveBanner(holder) + } + + private fun bindLocationLiveBanner(holder: Holder) { + // TODO in a future PR add check on device id to confirm that is the one that sent the beacon + val isEmitter = currentUserId != null && currentUserId == locationUserId + val messageLayout = attributes.informationData.messageLayout + val viewState = buildViewState(holder, messageLayout, isEmitter) + holder.locationLiveMessageBanner.isVisible = true + holder.locationLiveMessageBanner.render(viewState) + holder.locationLiveMessageBanner.stopButton.setOnClickListener { + attributes.callback?.onTimelineItemAction(RoomDetailAction.StopLiveLocationSharing) + } + } + + private fun buildViewState( + holder: Holder, + messageLayout: TimelineMessageLayout, + isEmitter: Boolean + ): LocationLiveMessageBannerViewState { + return when { + messageLayout is TimelineMessageLayout.Bubble && isEmitter -> + LocationLiveMessageBannerViewState.Emitter( + remainingTimeInMillis = getRemainingTimeOfLiveInMillis(), + bottomStartCornerRadiusInDp = messageLayout.cornersRadius.bottomStartRadius, + bottomEndCornerRadiusInDp = messageLayout.cornersRadius.bottomEndRadius, + isStopButtonCenteredVertically = false + ) + messageLayout is TimelineMessageLayout.Bubble -> + LocationLiveMessageBannerViewState.Watcher( + bottomStartCornerRadiusInDp = messageLayout.cornersRadius.bottomStartRadius, + bottomEndCornerRadiusInDp = messageLayout.cornersRadius.bottomEndRadius, + formattedLocalTimeOfEndOfLive = getFormattedLocalTimeEndOfLive(), + ) + isEmitter -> { + val cornerRadius = getBannerCornerRadiusForDefaultLayout(holder) + LocationLiveMessageBannerViewState.Emitter( + remainingTimeInMillis = getRemainingTimeOfLiveInMillis(), + bottomStartCornerRadiusInDp = cornerRadius, + bottomEndCornerRadiusInDp = cornerRadius, + isStopButtonCenteredVertically = true + ) + } + else -> { + val cornerRadius = getBannerCornerRadiusForDefaultLayout(holder) + LocationLiveMessageBannerViewState.Watcher( + bottomStartCornerRadiusInDp = cornerRadius, + bottomEndCornerRadiusInDp = cornerRadius, + formattedLocalTimeOfEndOfLive = getFormattedLocalTimeEndOfLive(), + ) + } + } + } + + private fun getBannerCornerRadiusForDefaultLayout(holder: Holder): Float { + val dimensionConverter = DimensionConverter(holder.view.resources) + return dimensionConverter.dpToPx(8).toFloat() + } + + private fun getFormattedLocalTimeEndOfLive() = + endOfLiveDateTime?.toTimestamp()?.let { vectorDateFormatter.format(it, DateFormatKind.MESSAGE_SIMPLE) }.orEmpty() + + private fun getRemainingTimeOfLiveInMillis() = + (endOfLiveDateTime?.toTimestamp() ?: 0) - LocalDateTime.now().toTimestamp() + + override fun getViewStubId() = STUB_ID + + class Holder : AbsMessageLocationItem.Holder(STUB_ID) { + val locationLiveMessageBanner by bind(R.id.locationLiveMessageBanner) + } + + companion object { + private const val STUB_ID = R.id.messageContentLiveLocationStub + } +} diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationStartItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationStartItem.kt index 390db0ef50..001774b579 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationStartItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/MessageLiveLocationStartItem.kt @@ -16,22 +16,15 @@ package im.vector.app.features.home.room.detail.timeline.item -import android.graphics.drawable.ColorDrawable import android.widget.ImageView -import androidx.core.view.updateLayoutParams import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass -import com.bumptech.glide.load.resource.bitmap.GranularRoundedCorners -import com.bumptech.glide.load.resource.bitmap.RoundedCorners import im.vector.app.R -import im.vector.app.core.glide.GlideApp -import im.vector.app.core.utils.DimensionConverter -import im.vector.app.features.home.room.detail.timeline.style.TimelineMessageLayout -import im.vector.app.features.home.room.detail.timeline.style.granularRoundedCorners -import im.vector.app.features.themes.ThemeUtils @EpoxyModelClass(layout = R.layout.item_timeline_event_base) -abstract class MessageLiveLocationStartItem : AbsMessageItem() { +abstract class MessageLiveLocationStartItem : + AbsMessageItem(), + LiveLocationShareStatusItem by DefaultLiveLocationShareStatusItem() { @EpoxyAttribute var mapWidth: Int = 0 @@ -42,44 +35,8 @@ abstract class MessageLiveLocationStartItem : AbsMessageItem() { - - @EpoxyAttribute - var locationUrl: String? = null - - @EpoxyAttribute - var userId: String? = null - - @EpoxyAttribute - var mapWidth: Int = 0 - - @EpoxyAttribute - var mapHeight: Int = 0 - - @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) - var locationPinProvider: LocationPinProvider? = null - - override fun bind(holder: Holder) { - super.bind(holder) - renderSendState(holder.view, null) - val location = locationUrl ?: return - val messageLayout = attributes.informationData.messageLayout - val dimensionConverter = DimensionConverter(holder.view.resources) - val imageCornerTransformation = if (messageLayout is TimelineMessageLayout.Bubble) { - messageLayout.cornersRadius.granularRoundedCorners() - } else { - RoundedCorners(dimensionConverter.dpToPx(8)) - } - holder.staticMapImageView.updateLayoutParams { - width = mapWidth - height = mapHeight - } - GlideApp.with(holder.staticMapImageView) - .load(location) - .apply(RequestOptions.centerCropTransform()) - .listener(object : RequestListener { - override fun onLoadFailed(e: GlideException?, - model: Any?, - target: Target?, - isFirstResource: Boolean): Boolean { - holder.staticMapPinImageView.setImageResource(R.drawable.ic_location_pin_failed) - holder.staticMapErrorTextView.isVisible = true - return false - } - - override fun onResourceReady(resource: Drawable?, - model: Any?, - target: Target?, - dataSource: DataSource?, - isFirstResource: Boolean): Boolean { - locationPinProvider?.create(userId) { pinDrawable -> - GlideApp.with(holder.staticMapPinImageView) - .load(pinDrawable) - .into(holder.staticMapPinImageView) - } - holder.staticMapErrorTextView.isVisible = false - return false - } - }) - .transform(imageCornerTransformation) - .into(holder.staticMapImageView) - } +abstract class MessageLocationItem : AbsMessageLocationItem() { override fun getViewStubId() = STUB_ID - class Holder : AbsMessageItem.Holder(STUB_ID) { - val staticMapImageView by bind(R.id.staticMapImageView) - val staticMapPinImageView by bind(R.id.staticMapPinImageView) - val staticMapErrorTextView by bind(R.id.staticMapErrorTextView) - } + class Holder : AbsMessageLocationItem.Holder(STUB_ID) companion object { private const val STUB_ID = R.id.messageContentLocationStub diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt index ae900d0406..fe17f9e9e7 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/item/PollOptionViewState.kt @@ -26,7 +26,7 @@ sealed class PollOptionViewState(open val optionId: String, ) : PollOptionViewState(optionId, optionAnswer) /** - * Represents a poll that is sent but not voted by the user + * Represents a poll that is sent but not voted by the user. */ data class PollReady(override val optionId: String, override val optionAnswer: String diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ReactionInfoSimpleItem.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ReactionInfoSimpleItem.kt index f150e13016..741cb1324f 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ReactionInfoSimpleItem.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ReactionInfoSimpleItem.kt @@ -28,7 +28,7 @@ import im.vector.app.core.epoxy.onClick import im.vector.lib.core.utils.epoxy.charsequence.EpoxyCharSequence /** - * Item displaying an emoji reaction (single line with emoji, author, time) + * Item displaying an emoji reaction (single line with emoji, author, time). */ @EpoxyModelClass(layout = R.layout.item_simple_reaction_info) abstract class ReactionInfoSimpleItem : EpoxyModelWithHolder() { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsBottomSheet.kt index 57b2f2fd40..6c6a722f02 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsBottomSheet.kt @@ -35,7 +35,7 @@ import im.vector.app.features.home.room.detail.timeline.item.MessageInformationD import javax.inject.Inject /** - * Bottom sheet displaying list of reactions for a given event ordered by timestamp + * Bottom sheet displaying list of reactions for a given event ordered by timestamp. */ @AndroidEntryPoint class ViewReactionsBottomSheet : diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt index 86e5c529ee..a4677da1d9 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsEpoxyController.kt @@ -30,7 +30,7 @@ import im.vector.lib.core.utils.epoxy.charsequence.toEpoxyCharSequence import javax.inject.Inject /** - * Epoxy controller for reaction event list + * Epoxy controller for reaction event list. */ class ViewReactionsEpoxyController @Inject constructor( private val stringProvider: StringProvider, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt index deb22bbe04..1c9127aa1e 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/reactions/ViewReactionsViewModel.kt @@ -56,7 +56,7 @@ data class ReactionInfo( ) /** - * Used to display the list of members that reacted to a given event + * Used to display the list of members that reacted to a given event. */ class ViewReactionsViewModel @AssistedInject constructor( @Assisted initialState: DisplayReactionsViewState, diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt index f083c70100..a0d10a8a75 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/style/TimelineMessageLayoutFactory.kt @@ -66,6 +66,11 @@ class TimelineMessageLayoutFactory @Inject constructor(private val session: Sess MessageType.MSGTYPE_VIDEO, MessageType.MSGTYPE_BEACON_INFO, ) + + private val MSG_TYPES_WITH_LOCATION_DATA = setOf( + MessageType.MSGTYPE_LOCATION, + MessageType.MSGTYPE_BEACON_LOCATION_DATA + ) } private val cornerRadius: Float by lazy { @@ -145,9 +150,11 @@ class TimelineMessageLayoutFactory @Inject constructor(private val session: Sess } private fun MessageContent?.timestampInsideMessage(): Boolean { - if (this == null) return false - if (msgType == MessageType.MSGTYPE_LOCATION) return vectorPreferences.labsRenderLocationsInTimeline() - return this.msgType in MSG_TYPES_WITH_TIMESTAMP_INSIDE_MESSAGE + return when { + this == null -> false + msgType in MSG_TYPES_WITH_LOCATION_DATA -> vectorPreferences.labsRenderLocationsInTimeline() + else -> msgType in MSG_TYPES_WITH_TIMESTAMP_INSIDE_MESSAGE + } } private fun MessageContent?.shouldAddMessageOverlay(): Boolean { @@ -197,7 +204,7 @@ class TimelineMessageLayoutFactory @Inject constructor(private val session: Sess /** * Tiles type message never show the sender information (like verification request), so we should repeat it for next message - * even if same sender + * even if same sender. */ private fun isTileTypeMessage(event: TimelineEvent?): Boolean { return when (event?.root?.getClearType()) { diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt index a8f8f7b0cb..29a314d1b3 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlUiState.kt @@ -19,7 +19,7 @@ package im.vector.app.features.home.room.detail.timeline.url import org.matrix.android.sdk.api.session.media.PreviewUrlData /** - * The state representing a preview url UI state for an Event + * The state representing a preview url UI state for an Event. */ sealed class PreviewUrlUiState { // No info diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt index bb306c2016..3ae6a1fea5 100755 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/timeline/url/PreviewUrlView.kt @@ -35,7 +35,7 @@ import im.vector.app.features.themes.ThemeUtils import org.matrix.android.sdk.api.session.media.PreviewUrlData /** - * A View to display a PreviewUrl and some other state + * A View to display a PreviewUrl and some other state. */ class PreviewUrlView @JvmOverloads constructor( context: Context, @@ -56,7 +56,7 @@ class PreviewUrlView @JvmOverloads constructor( private var state: PreviewUrlUiState = PreviewUrlUiState.Unknown /** - * This methods is responsible for rendering the view according to the newState + * This methods is responsible for rendering the view according to the newState. * * @param newState the newState representing the view */ @@ -157,7 +157,7 @@ class PreviewUrlView @JvmOverloads constructor( } /** - * Hide all views that are not visible in all state + * Hide all views that are not visible in all state. */ private fun hideAll() { views.urlPreviewTitle.isVisible = false diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsBottomSheet.kt index 65f3d16ad4..72f9688ad8 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsBottomSheet.kt @@ -37,7 +37,7 @@ import org.matrix.android.sdk.api.session.widgets.model.Widget import javax.inject.Inject /** - * Bottom sheet displaying active widgets in a room + * Bottom sheet displaying active widgets in a room. */ @AndroidEntryPoint class RoomWidgetsBottomSheet : diff --git a/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt b/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt index 87392c5d7a..0f91f7b7c6 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/detail/widget/RoomWidgetsController.kt @@ -27,7 +27,7 @@ import org.matrix.android.sdk.api.session.widgets.model.Widget import javax.inject.Inject /** - * Epoxy controller for room widgets list + * Epoxy controller for room widgets list. */ class RoomWidgetsController @Inject constructor( val stringProvider: StringProvider, diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewEvents.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewEvents.kt index 15e16c464f..386352be9b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewEvents.kt @@ -21,7 +21,7 @@ import im.vector.app.core.platform.VectorViewEvents import org.matrix.android.sdk.api.session.room.model.RoomSummary /** - * Transient events for RoomList + * Transient events for RoomList. */ sealed class RoomListViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : RoomListViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt index 9fd6de1a74..73540ac76a 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewModel.kt @@ -90,7 +90,7 @@ class RoomListViewModel @AssistedInject constructor( */ ALL_IF_SPACE_NULL, - /** Do not filter based on space*/ + /** Do not filter based on space. */ NONE } diff --git a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingGossipingRequest.kt b/vector/src/main/java/im/vector/app/features/home/room/list/SpaceDirectoryFilterNoResults.kt similarity index 50% rename from matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingGossipingRequest.kt rename to vector/src/main/java/im/vector/app/features/home/room/list/SpaceDirectoryFilterNoResults.kt index 2438e01102..1ae017c98c 100644 --- a/matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/OutgoingGossipingRequest.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/SpaceDirectoryFilterNoResults.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 The Matrix.org Foundation C.I.C. + * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,14 +14,14 @@ * limitations under the License. */ -package org.matrix.android.sdk.internal.crypto +package im.vector.app.features.home.room.list -import org.matrix.android.sdk.api.session.crypto.model.OutgoingGossipingRequestState +import com.airbnb.epoxy.EpoxyModelClass +import im.vector.app.R +import im.vector.app.core.epoxy.VectorEpoxyHolder +import im.vector.app.core.epoxy.VectorEpoxyModel -internal interface OutgoingGossipingRequest { - val recipients: Map> - val requestId: String - val state: OutgoingGossipingRequestState - // transaction id for the cancellation, if any - // var cancellationTxnId: String? +@EpoxyModelClass(layout = R.layout.item_space_directory_filter_no_results) +abstract class SpaceDirectoryFilterNoResults : VectorEpoxyModel() { + class Holder : VectorEpoxyHolder() } diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt index 5d8cda94ae..a6b1a0de52 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsBottomSheet.kt @@ -47,7 +47,7 @@ data class RoomListActionsArgs( ) : Parcelable /** - * Bottom sheet fragment that shows room information with list of contextual actions + * Bottom sheet fragment that shows room information with list of contextual actions. */ @AndroidEntryPoint class RoomListQuickActionsBottomSheet : diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt index b343013408..7f0de584cf 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsEpoxyController.kt @@ -32,7 +32,7 @@ import org.matrix.android.sdk.api.util.toMatrixItem import javax.inject.Inject /** - * Epoxy controller for room list actions + * Epoxy controller for room list actions. */ class RoomListQuickActionsEpoxyController @Inject constructor( private val avatarRenderer: AvatarRenderer, diff --git a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedActionViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedActionViewModel.kt index 174e0fac5c..bad362d205 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedActionViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/list/actions/RoomListQuickActionsSharedActionViewModel.kt @@ -20,6 +20,6 @@ import im.vector.app.core.platform.VectorSharedActionViewModel import javax.inject.Inject /** - * Activity shared view model to handle room list quick actions + * Activity shared view model to handle room list quick actions. */ class RoomListQuickActionsSharedActionViewModel @Inject constructor() : VectorSharedActionViewModel() diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt index 13a12106c7..1ddd665ef4 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsActivity.kt @@ -117,7 +117,7 @@ class ThreadsActivity : VectorBaseActivity() { } /** - * Determine in witch fragment we should navigate + * Determine in witch fragment we should navigate. */ private fun fragmentToNavigate(): DisplayFragment { getThreadTimelineArgs()?.let { diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsManager.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsManager.kt index 545077b550..ffb42bec1b 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsManager.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/ThreadsManager.kt @@ -29,7 +29,7 @@ import org.matrix.android.sdk.api.settings.LightweightSettingsStorage import javax.inject.Inject /** - * The class is responsible for handling thread specific tasks + * The class is responsible for handling thread specific tasks. */ class ThreadsManager @Inject constructor( private val vectorPreferences: VectorPreferences, @@ -48,7 +48,7 @@ class ThreadsManager @Inject constructor( } /** - * Generates and return an Html spanned string to be rendered especially in dialogs + * Generates and return an Html spanned string to be rendered especially in dialogs. */ private fun generateLearnMoreHtmlString(@StringRes messageId: Int): Spanned { val learnMore = stringProvider.getString(R.string.action_learn_more) diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/arguments/ThreadTimelineArgs.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/arguments/ThreadTimelineArgs.kt index 19419e52de..7756c3c5a5 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/arguments/ThreadTimelineArgs.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/arguments/ThreadTimelineArgs.kt @@ -27,5 +27,6 @@ data class ThreadTimelineArgs( val avatarUrl: String?, val roomEncryptionTrustLevel: RoomEncryptionTrustLevel?, val rootThreadEventId: String? = null, - val startsThread: Boolean = false + val startsThread: Boolean = false, + val showKeyboard: Boolean = false ) : Parcelable diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt index 6b3f0dc6b8..d7dd03cbbd 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListController.kt @@ -55,8 +55,7 @@ class ThreadListController @Inject constructor( } /** - * Building thread summaries when homeserver - * supports threading + * Building thread summaries when homeserver supports threading. */ private fun buildThreadSummaries() { val safeViewState = viewState ?: return @@ -104,8 +103,7 @@ class ThreadListController @Inject constructor( } /** - * Building local thread list when homeserver do not - * support threading + * Building local thread list when homeserver do not support threading. */ private fun buildThreadList() { val safeViewState = viewState ?: return diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt index 2722ca5090..d038b14491 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/list/viewmodel/ThreadListViewModel.kt @@ -65,8 +65,7 @@ class ThreadListViewModel @AssistedInject constructor(@Assisted val initialState override fun handle(action: EmptyAction) {} /** - * Observing thread list with respect to homeserver - * capabilities + * Observing thread list with respect to homeserver capabilities. */ private fun fetchAndObserveThreads() { when (session.homeServerCapabilitiesService().getHomeServerCapabilities().canUseThreading) { @@ -79,8 +78,7 @@ class ThreadListViewModel @AssistedInject constructor(@Assisted val initialState } /** - * Observing thread summaries when homeserver support - * threading + * Observing thread summaries when homeserver support threading. */ private fun observeThreadSummaries() { room?.flow() @@ -93,8 +91,7 @@ class ThreadListViewModel @AssistedInject constructor(@Assisted val initialState } /** - * Observing thread list when homeserver do not support - * threading + * Observing thread list when homeserver do not support threading. */ private fun observeThreadsList() { room?.flow() diff --git a/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt b/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt index 04889f375f..8e762fda96 100644 --- a/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt +++ b/vector/src/main/java/im/vector/app/features/home/room/threads/list/views/ThreadListFragment.kt @@ -19,6 +19,7 @@ package im.vector.app.features.home.room.threads.list.views import android.os.Bundle import android.view.LayoutInflater import android.view.Menu +import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup @@ -70,6 +71,16 @@ class ThreadListFragment @Inject constructor( analyticsScreenName = MobileScreen.ScreenName.ThreadList } + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + super.onCreateOptionsMenu(menu, inflater) + + menu.findItem(R.id.menu_thread_list_filter)?.let { menuItem -> + menuItem.actionView.setOnClickListener { + onOptionsItemSelected(menuItem) + } + } + } + override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_thread_list_filter -> { @@ -82,6 +93,9 @@ class ThreadListFragment @Inject constructor( override fun onPrepareOptionsMenu(menu: Menu) { withState(threadListViewModel) { state -> + val filterIcon = menu.findItem(R.id.menu_thread_list_filter).actionView + val filterBadge = filterIcon.findViewById(R.id.threadListFilterBadge) + filterBadge.isVisible = state.shouldFilterThreads when (threadListViewModel.canHomeserverUseThreading()) { true -> menu.findItem(R.id.menu_thread_list_filter).isVisible = !state.threadSummaryList.invoke().isNullOrEmpty() false -> menu.findItem(R.id.menu_thread_list_filter).isVisible = !state.rootThreadEventList.invoke().isNullOrEmpty() @@ -146,9 +160,9 @@ class ThreadListFragment @Inject constructor( override fun onThreadSummaryClicked(threadSummary: ThreadSummary) { val roomThreadDetailArgs = ThreadTimelineArgs( - roomId = threadSummary.roomId, - displayName = threadSummary.rootThreadSenderInfo.displayName, - avatarUrl = threadSummary.rootThreadSenderInfo.avatarUrl, + roomId = threadListArgs.roomId, + displayName = threadListArgs.displayName, + avatarUrl = threadListArgs.avatarUrl, roomEncryptionTrustLevel = null, rootThreadEventId = threadSummary.rootEventId ) @@ -157,9 +171,9 @@ class ThreadListFragment @Inject constructor( override fun onThreadListClicked(timelineEvent: TimelineEvent) { val threadTimelineArgs = ThreadTimelineArgs( - roomId = timelineEvent.roomId, - displayName = timelineEvent.senderInfo.displayName, - avatarUrl = timelineEvent.senderInfo.avatarUrl, + roomId = threadListArgs.roomId, + displayName = threadListArgs.displayName, + avatarUrl = threadListArgs.avatarUrl, roomEncryptionTrustLevel = null, rootThreadEventId = timelineEvent.eventId ) diff --git a/vector/src/main/java/im/vector/app/features/homeserver/ServerUrlsRepository.kt b/vector/src/main/java/im/vector/app/features/homeserver/ServerUrlsRepository.kt index e815b7b0f3..4eca377e28 100644 --- a/vector/src/main/java/im/vector/app/features/homeserver/ServerUrlsRepository.kt +++ b/vector/src/main/java/im/vector/app/features/homeserver/ServerUrlsRepository.kt @@ -22,7 +22,7 @@ import im.vector.app.R import im.vector.app.core.di.DefaultSharedPreferences /** - * Object to store and retrieve home and identity server urls + * Object to store and retrieve home and identity server urls. */ object ServerUrlsRepository { @@ -35,7 +35,7 @@ object ServerUrlsRepository { const val IDENTITY_SERVER_URL_PREF = "identity_server_url" /** - * Save home and identity sever urls received by the Referrer receiver + * Save home and identity sever urls received by the Referrer receiver. */ fun setDefaultUrlsFromReferrer(context: Context, homeServerUrl: String, identityServerUrl: String) { DefaultSharedPreferences.getInstance(context) @@ -51,7 +51,7 @@ object ServerUrlsRepository { } /** - * Save home and identity sever urls entered by the user. May be custom or default value + * Save home and identity sever urls entered by the user. May be custom or default value. */ fun saveServerUrls(context: Context, homeServerUrl: String, identityServerUrl: String) { DefaultSharedPreferences.getInstance(context) @@ -62,7 +62,7 @@ object ServerUrlsRepository { } /** - * Return last used homeserver url, or the default one from referrer or the default one from resources + * Return last used homeserver url, or the default one from referrer or the default one from resources. */ fun getLastHomeServerUrl(context: Context): String { val prefs = DefaultSharedPreferences.getInstance(context) @@ -77,12 +77,12 @@ object ServerUrlsRepository { } /** - * Return true if url is the default homeserver url form resources + * Return true if url is the default homeserver url form resources. */ fun isDefaultHomeServerUrl(context: Context, url: String) = url == getDefaultHomeServerUrl(context) /** - * Return default homeserver url from resources + * Return default homeserver url from resources. */ fun getDefaultHomeServerUrl(context: Context): String = context.getString(R.string.matrix_org_server_url) } diff --git a/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt b/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt index 6a925997b7..5327d70ec9 100644 --- a/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt +++ b/vector/src/main/java/im/vector/app/features/html/FontTagHandler.kt @@ -24,7 +24,7 @@ import io.noties.markwon.html.HtmlTag import io.noties.markwon.html.tag.SimpleTagHandler /** - * custom to matrix for IRC-style font coloring + * custom to matrix for IRC-style font coloring. */ class FontTagHandler : SimpleTagHandler() { diff --git a/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt b/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt index 5b44f69821..a51491e85b 100644 --- a/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt +++ b/vector/src/main/java/im/vector/app/features/link/LinkHandlerActivity.kt @@ -101,7 +101,7 @@ class LinkHandlerActivity : VectorBaseActivity() { } /** - * Start the login screen with identity server and homeserver pre-filled, if any + * Start the login screen with identity server and homeserver pre-filled, if any. */ private fun startLoginActivity(uri: Uri? = null) { navigator.openLogin( @@ -113,7 +113,7 @@ class LinkHandlerActivity : VectorBaseActivity() { } /** - * Propose to disconnect from a previous HS, when clicking on an auto config link + * Propose to disconnect from a previous HS, when clicking on an auto config link. */ private fun displayAlreadyLoginPopup(uri: Uri) { MaterialAlertDialogBuilder(this) diff --git a/vector/src/main/java/im/vector/app/features/location/Config.kt b/vector/src/main/java/im/vector/app/features/location/Config.kt index 6f947290e2..c29e2e911a 100644 --- a/vector/src/main/java/im/vector/app/features/location/Config.kt +++ b/vector/src/main/java/im/vector/app/features/location/Config.kt @@ -22,5 +22,5 @@ const val DEFAULT_PIN_ID = "DEFAULT_PIN_ID" const val INITIAL_MAP_ZOOM_IN_PREVIEW = 15.0 const val INITIAL_MAP_ZOOM_IN_TIMELINE = 17.0 -const val MIN_TIME_TO_UPDATE_LOCATION_MILLIS = 5 * 1_000L // every 5 seconds +const val MIN_TIME_TO_UPDATE_LOCATION_MILLIS = 2 * 1_000L // every 2 seconds const val MIN_DISTANCE_TO_UPDATE_LOCATION_METERS = 10f diff --git a/vector/src/main/java/im/vector/app/features/location/LocationData.kt b/vector/src/main/java/im/vector/app/features/location/LocationData.kt index a69d8d20e3..b3466ff871 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationData.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationData.kt @@ -29,7 +29,7 @@ data class LocationData( ) : Parcelable /** - * Creates location data from a LocationContent + * Creates location data from a MessageLocationContent. * "geo:40.05,29.24;30" -> LocationData(40.05, 29.24, 30) * @return location data or null if geo uri is not valid */ @@ -37,6 +37,15 @@ fun MessageLocationContent.toLocationData(): LocationData? { return parseGeo(getBestGeoUri()) } +/** + * Creates location data from a geoUri String. + * "geo:40.05,29.24;30" -> LocationData(40.05, 29.24, 30) + * @return location data or null if geo uri is null or not valid + */ +fun String?.toLocationData(): LocationData? { + return this?.let { parseGeo(it) } +} + @VisibleForTesting fun parseGeo(geo: String): LocationData? { val geoParts = geo diff --git a/vector/src/main/java/im/vector/app/features/location/LocationPreviewFragment.kt b/vector/src/main/java/im/vector/app/features/location/LocationPreviewFragment.kt index 5d823e53a6..7fce09cad7 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationPreviewFragment.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationPreviewFragment.kt @@ -32,7 +32,7 @@ import im.vector.app.features.home.room.detail.timeline.helper.LocationPinProvid import java.lang.ref.WeakReference import javax.inject.Inject -/** +/* * TODO Move locationPinProvider to a ViewModel */ class LocationPreviewFragment @Inject constructor( diff --git a/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt b/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt index 38b96142b5..e472c568b6 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationSharingFragment.kt @@ -47,7 +47,7 @@ import java.lang.ref.WeakReference import javax.inject.Inject /** - * We should consider using SupportMapFragment for a out of the box lifecycle handling + * We should consider using SupportMapFragment for a out of the box lifecycle handling. */ class LocationSharingFragment @Inject constructor( private val urlMapProvider: UrlMapProvider, diff --git a/vector/src/main/java/im/vector/app/features/location/LocationSharingService.kt b/vector/src/main/java/im/vector/app/features/location/LocationSharingService.kt index 362b82ccf5..8b9a1c75ae 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationSharingService.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationSharingService.kt @@ -55,7 +55,10 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { private val binder = LocalBinder() - private var roomArgsList = mutableListOf() + /** + * Keep track of a map between beacon event Id starting the live and RoomArgs. + */ + private var roomArgsMap = mutableMapOf() private var timers = mutableListOf() override fun onCreate() { @@ -73,8 +76,6 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { Timber.i("### LocationSharingService.onStartCommand. sessionId - roomId ${roomArgs?.sessionId} - ${roomArgs?.roomId}") if (roomArgs != null) { - roomArgsList.add(roomArgs) - // Show a sticky notification val notification = notificationUtils.buildLiveLocationSharingNotification() startForeground(roomArgs.roomId.hashCode(), notification) @@ -87,7 +88,7 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { .getSafeActiveSession() ?.let { session -> session.coroutineScope.launch(session.coroutineDispatchers.io) { - sendLiveBeaconInfo(session, roomArgs) + sendStartingLiveBeaconInfo(session, roomArgs) } } } @@ -95,7 +96,7 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { return START_STICKY } - private suspend fun sendLiveBeaconInfo(session: Session, roomArgs: RoomArgs) { + private suspend fun sendStartingLiveBeaconInfo(session: Session, roomArgs: RoomArgs) { val beaconContent = MessageBeaconInfoContent( timeout = roomArgs.durationMillis, isLive = true, @@ -103,7 +104,7 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { ).toContent() val stateKey = session.myUserId - session + val beaconEventId = session .getRoom(roomArgs.roomId) ?.stateService() ?.sendStateEvent( @@ -111,6 +112,16 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { stateKey = stateKey, body = beaconContent ) + + beaconEventId + ?.takeUnless { it.isEmpty() } + ?.let { + roomArgsMap[it] = roomArgs + locationTracker.requestLastKnownLocation() + } + ?: run { + Timber.w("### LocationSharingService.sendStartingLiveBeaconInfo error, no received beacon info id") + } } private fun scheduleTimer(roomId: String, durationMillis: Long) { @@ -134,9 +145,13 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { // Send a new beacon info state by setting live field as false sendStoppedBeaconInfo(roomId) - synchronized(roomArgsList) { - roomArgsList.removeAll { it.roomId == roomId } - if (roomArgsList.isEmpty()) { + synchronized(roomArgsMap) { + val beaconIds = roomArgsMap + .filter { it.value.roomId == roomId } + .map { it.key } + beaconIds.forEach { roomArgsMap.remove(it) } + + if (roomArgsMap.isEmpty()) { Timber.i("### LocationSharingService. Destroying self, time is up for all rooms") destroyMe() } @@ -156,16 +171,17 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { override fun onLocationUpdate(locationData: LocationData) { Timber.i("### LocationSharingService.onLocationUpdate. Uncertainty: ${locationData.uncertainty}") - val session = activeSessionHolder.getSafeActiveSession() // Emit location update to all rooms in which live location sharing is active - session?.coroutineScope?.launch(session.coroutineDispatchers.io) { - roomArgsList.toList().forEach { roomArg -> - sendLiveLocation(roomArg.roomId, locationData) - } + roomArgsMap.toMap().forEach { item -> + sendLiveLocation(item.value.roomId, item.key, locationData) } } - private suspend fun sendLiveLocation(roomId: String, locationData: LocationData) { + private fun sendLiveLocation( + roomId: String, + beaconInfoEventId: String, + locationData: LocationData + ) { val session = activeSessionHolder.getSafeActiveSession() val room = session?.getRoom(roomId) val userId = session?.myUserId @@ -174,18 +190,12 @@ class LocationSharingService : VectorService(), LocationTracker.Callback { return } - room - .stateService() - .getLiveLocationBeaconInfo(userId, true) - ?.eventId - ?.let { - room.sendService().sendLiveLocation( - beaconInfoEventId = it, - latitude = locationData.latitude, - longitude = locationData.longitude, - uncertainty = locationData.uncertainty - ) - } + room.sendService().sendLiveLocation( + beaconInfoEventId = beaconInfoEventId, + latitude = locationData.latitude, + longitude = locationData.longitude, + uncertainty = locationData.uncertainty + ) } override fun onLocationProviderIsNotAvailable() { diff --git a/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt b/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt index b7006370a6..4e56e7954c 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt @@ -40,10 +40,12 @@ class LocationTracker @Inject constructor( fun onLocationProviderIsNotAvailable() } - private var callbacks = mutableListOf() + private val callbacks = mutableListOf() private var hasGpsProviderLiveLocation = false + private var lastLocation: LocationData? = null + @RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) fun start() { Timber.d("## LocationTracker. start()") @@ -92,6 +94,14 @@ class LocationTracker @Inject constructor( callbacks.clear() } + /** + * Request the last known location. It will be given async through Callback. + * Please ensure adding a callback to receive the value. + */ + fun requestLastKnownLocation() { + lastLocation?.let { location -> callbacks.forEach { it.onLocationUpdate(location) } } + } + fun addCallback(callback: Callback) { if (!callbacks.contains(callback)) { callbacks.add(callback) @@ -127,7 +137,9 @@ class LocationTracker @Inject constructor( } } } - callbacks.forEach { it.onLocationUpdate(location.toLocationData()) } + val locationData = location.toLocationData() + lastLocation = locationData + callbacks.forEach { it.onLocationUpdate(locationData) } } override fun onProviderDisabled(provider: String) { diff --git a/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt b/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt index e3206e231d..69e4e9fc20 100644 --- a/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt +++ b/vector/src/main/java/im/vector/app/features/location/MapTilerMapView.kt @@ -78,7 +78,7 @@ class MapTilerMapView @JvmOverloads constructor( } /** - * For location fragments + * For location fragments. */ fun initialize( url: String, diff --git a/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerView.kt b/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerView.kt new file mode 100644 index 0000000000..8cb552e3c4 --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerView.kt @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.location.live + +import android.content.Context +import android.graphics.drawable.ColorDrawable +import android.os.CountDownTimer +import android.util.AttributeSet +import android.view.LayoutInflater +import android.widget.Button +import android.widget.ImageView +import android.widget.TextView +import androidx.constraintlayout.widget.ConstraintLayout +import androidx.constraintlayout.widget.ConstraintSet +import androidx.core.view.isVisible +import com.bumptech.glide.load.resource.bitmap.GranularRoundedCorners +import im.vector.app.R +import im.vector.app.core.glide.GlideApp +import im.vector.app.core.utils.TextUtils +import im.vector.app.databinding.ViewLocationLiveMessageBannerBinding +import im.vector.app.features.themes.ThemeUtils +import org.threeten.bp.Duration + +private const val REMAINING_TIME_COUNTER_INTERVAL_IN_MS = 1000L + +class LocationLiveMessageBannerView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0 +) : ConstraintLayout(context, attrs, defStyleAttr) { + + private val binding = ViewLocationLiveMessageBannerBinding.inflate( + LayoutInflater.from(context), + this + ) + + val stopButton: Button + get() = binding.locationLiveMessageBannerStop + + private val background: ImageView + get() = binding.locationLiveMessageBannerBackground + + private val title: TextView + get() = binding.locationLiveMessageBannerTitle + + private val subTitle: TextView + get() = binding.locationLiveMessageBannerSubTitle + + private var countDownTimer: CountDownTimer? = null + + fun render(viewState: LocationLiveMessageBannerViewState) { + when (viewState) { + is LocationLiveMessageBannerViewState.Emitter -> renderEmitter(viewState) + is LocationLiveMessageBannerViewState.Watcher -> renderWatcher(viewState) + } + + GlideApp.with(context) + .load(ColorDrawable(ThemeUtils.getColor(context, android.R.attr.colorBackground))) + .transform(GranularRoundedCorners(0f, 0f, viewState.bottomEndCornerRadiusInDp, viewState.bottomStartCornerRadiusInDp)) + .into(background) + } + + private fun renderEmitter(viewState: LocationLiveMessageBannerViewState.Emitter) { + stopButton.isVisible = true + title.text = context.getString(R.string.location_share_live_enabled) + + countDownTimer?.cancel() + viewState.remainingTimeInMillis + .takeIf { it >= 0 } + ?.let { + countDownTimer = object : CountDownTimer(it, REMAINING_TIME_COUNTER_INTERVAL_IN_MS) { + override fun onTick(millisUntilFinished: Long) { + val duration = Duration.ofMillis(millisUntilFinished.coerceAtLeast(0L)) + subTitle.text = context.getString( + R.string.location_share_live_remaining_time, + TextUtils.formatDurationWithUnits(context, duration) + ) + } + + override fun onFinish() { + subTitle.text = context.getString( + R.string.location_share_live_remaining_time, + TextUtils.formatDurationWithUnits(context, Duration.ofMillis(0L)) + ) + } + } + countDownTimer?.start() + } + + val rootLayout: ConstraintLayout? = (binding.root as? ConstraintLayout) + rootLayout?.let { parentLayout -> + val constraintSet = ConstraintSet() + constraintSet.clone(rootLayout) + + if (viewState.isStopButtonCenteredVertically) { + constraintSet.connect( + R.id.locationLiveMessageBannerStop, + ConstraintSet.BOTTOM, + R.id.locationLiveMessageBannerBackground, + ConstraintSet.BOTTOM, + 0 + ) + } else { + constraintSet.clear(R.id.locationLiveMessageBannerStop, ConstraintSet.BOTTOM) + } + + constraintSet.applyTo(parentLayout) + } + } + + private fun renderWatcher(viewState: LocationLiveMessageBannerViewState.Watcher) { + stopButton.isVisible = false + title.text = context.getString(R.string.location_share_live_view) + subTitle.text = context.getString(R.string.location_share_live_until, viewState.formattedLocalTimeOfEndOfLive) + } +} diff --git a/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerViewState.kt b/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerViewState.kt new file mode 100644 index 0000000000..976085386b --- /dev/null +++ b/vector/src/main/java/im/vector/app/features/location/live/LocationLiveMessageBannerViewState.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.app.features.location.live + +sealed class LocationLiveMessageBannerViewState( + open val bottomStartCornerRadiusInDp: Float, + open val bottomEndCornerRadiusInDp: Float, +) { + + data class Emitter( + override val bottomStartCornerRadiusInDp: Float, + override val bottomEndCornerRadiusInDp: Float, + val remainingTimeInMillis: Long, + val isStopButtonCenteredVertically: Boolean + ) : LocationLiveMessageBannerViewState(bottomStartCornerRadiusInDp, bottomEndCornerRadiusInDp) + + data class Watcher( + override val bottomStartCornerRadiusInDp: Float, + override val bottomEndCornerRadiusInDp: Float, + val formattedLocalTimeOfEndOfLive: String, + ) : LocationLiveMessageBannerViewState(bottomStartCornerRadiusInDp, bottomEndCornerRadiusInDp) +} diff --git a/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt b/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt index f5e48e84e7..2308f2c544 100644 --- a/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/AbstractLoginFragment.kt @@ -34,7 +34,7 @@ import org.matrix.android.sdk.api.failure.MatrixError import javax.net.ssl.HttpsURLConnection /** - * Parent Fragment for all the login/registration screens + * Parent Fragment for all the login/registration screens. */ abstract class AbstractLoginFragment : VectorBaseFragment(), OnBackPressed { diff --git a/vector/src/main/java/im/vector/app/features/login/JavascriptResponse.kt b/vector/src/main/java/im/vector/app/features/login/JavascriptResponse.kt index 3e2d712210..55908abb92 100644 --- a/vector/src/main/java/im/vector/app/features/login/JavascriptResponse.kt +++ b/vector/src/main/java/im/vector/app/features/login/JavascriptResponse.kt @@ -26,13 +26,13 @@ data class JavascriptResponse( val action: String? = null, /** - * Use for captcha result + * Use for captcha result. */ @Json(name = "response") val response: String? = null, /** - * Used for login/registration result + * Used for login/registration result. */ @Json(name = "credentials") val credentials: Credentials? = null diff --git a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt index d4730ecc8b..42a9b18558 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginActivity.kt @@ -49,7 +49,7 @@ import org.matrix.android.sdk.api.auth.toLocalizedLoginTerms import org.matrix.android.sdk.api.extensions.tryOrNull /** - * The LoginActivity manages the fragment navigation and also display the loading View + * The LoginActivity manages the fragment navigation and also display the loading View. */ @AndroidEntryPoint open class LoginActivity : VectorBaseActivity(), UnlockedActivity { @@ -288,7 +288,7 @@ open class LoginActivity : VectorBaseActivity(), UnlockedA } /** - * Handle the SSO redirection here + * Handle the SSO redirection here. */ override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) diff --git a/vector/src/main/java/im/vector/app/features/login/LoginCaptchaFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginCaptchaFragment.kt index 45b6e5b8cd..1b49f9bfa1 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginCaptchaFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginCaptchaFragment.kt @@ -49,7 +49,7 @@ data class LoginCaptchaFragmentArgument( ) : Parcelable /** - * In this screen, the user is asked to confirm he is not a robot + * In this screen, the user is asked to confirm he is not a robot. */ class LoginCaptchaFragment @Inject constructor( private val assetReader: AssetReader @@ -157,12 +157,14 @@ class LoginCaptchaFragment @Inject constructor( } } + @Deprecated("Deprecated in Java") override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { @Suppress("DEPRECATION") super.onReceivedError(view, errorCode, description, failingUrl) onError(description) } + @Deprecated("Deprecated in Java") override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { if (url?.startsWith("js:") == true) { var json = url.substring(3) diff --git a/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt index 14587b7c09..e8c0b25027 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginFragment.kt @@ -311,7 +311,7 @@ class LoginFragment @Inject constructor() : AbstractSSOLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordFragment.kt index 1d32944f9f..a5e01fdaa9 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordFragment.kt @@ -39,7 +39,7 @@ import reactivecircus.flowbinding.android.widget.textChanges import javax.inject.Inject /** - * In this screen, the user is asked for email and new password to reset his password + * In this screen, the user is asked for email and new password to reset his password. */ class LoginResetPasswordFragment @Inject constructor() : AbstractLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordMailConfirmationFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordMailConfirmationFragment.kt index 232e7ab622..e0bea738ed 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordMailConfirmationFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordMailConfirmationFragment.kt @@ -28,7 +28,7 @@ import org.matrix.android.sdk.api.failure.is401 import javax.inject.Inject /** - * In this screen, the user is asked to check his email and to click on a button once it's done + * In this screen, the user is asked to check their email and to click on a button once it's done. */ class LoginResetPasswordMailConfirmationFragment @Inject constructor() : AbstractLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordSuccessFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordSuccessFragment.kt index 031addb54a..d2f1f620bd 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordSuccessFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginResetPasswordSuccessFragment.kt @@ -24,7 +24,7 @@ import im.vector.app.databinding.FragmentLoginResetPasswordSuccessBinding import javax.inject.Inject /** - * In this screen, we confirm to the user that his password has been reset + * In this screen, we confirm to the user that his password has been reset. */ class LoginResetPasswordSuccessFragment @Inject constructor() : AbstractLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginServerSelectionFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginServerSelectionFragment.kt index a29967096a..6c49bafbba 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginServerSelectionFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginServerSelectionFragment.kt @@ -27,7 +27,7 @@ import me.gujun.android.span.span import javax.inject.Inject /** - * In this screen, the user will choose between matrix.org, modular or other type of homeserver + * In this screen, the user will choose between matrix.org, modular or other type of homeserver. */ class LoginServerSelectionFragment @Inject constructor() : AbstractLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginServerUrlFormFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginServerUrlFormFragment.kt index ca9582b44b..faaf12708a 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginServerUrlFormFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginServerUrlFormFragment.kt @@ -41,7 +41,7 @@ import java.net.UnknownHostException import javax.inject.Inject /** - * In this screen, the user is prompted to enter a homeserver url + * In this screen, the user is prompted to enter a homeserver url. */ class LoginServerUrlFormFragment @Inject constructor() : AbstractLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginSignUpSignInSelectionFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginSignUpSignInSelectionFragment.kt index 4f8f95192e..ebefbbec24 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginSignUpSignInSelectionFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginSignUpSignInSelectionFragment.kt @@ -28,7 +28,7 @@ import im.vector.app.databinding.FragmentLoginSignupSigninSelectionBinding import javax.inject.Inject /** - * In this screen, the user is asked to sign up or to sign in to the homeserver + * In this screen, the user is asked to sign up or to sign in to the homeserver. */ class LoginSignUpSignInSelectionFragment @Inject constructor() : AbstractSSOLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginSplashFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginSplashFragment.kt index 5e476be8ac..f3287ae333 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginSplashFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginSplashFragment.kt @@ -33,7 +33,7 @@ import java.net.UnknownHostException import javax.inject.Inject /** - * In this screen, the user is viewing an introduction to what he can do with this application + * In this screen, the user is viewing an introduction to what he can do with this application. */ class LoginSplashFragment @Inject constructor( private val vectorPreferences: VectorPreferences diff --git a/vector/src/main/java/im/vector/app/features/login/LoginViewEvents.kt b/vector/src/main/java/im/vector/app/features/login/LoginViewEvents.kt index dc14a0091d..4719cd972a 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginViewEvents.kt @@ -21,7 +21,7 @@ import im.vector.app.core.platform.VectorViewEvents import org.matrix.android.sdk.api.auth.registration.FlowResult /** - * Transient events for Login + * Transient events for Login. */ sealed class LoginViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : LoginViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/login/LoginViewModel.kt b/vector/src/main/java/im/vector/app/features/login/LoginViewModel.kt index c9cb4612a8..1b08d2a86f 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginViewModel.kt @@ -36,7 +36,7 @@ import im.vector.app.core.resources.StringProvider import im.vector.app.core.utils.ensureTrailingSlash import kotlinx.coroutines.Job import kotlinx.coroutines.launch -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.auth.AuthenticationService import org.matrix.android.sdk.api.auth.HomeServerHistoryService import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig @@ -607,7 +607,7 @@ class LoginViewModel @AssistedInject constructor( identityServerUri = wellKnownPrompt.identityServerUrl?.let { Uri.parse(it) } ) ?: HomeServerConnectionConfig( - homeServerUri = Uri.parse("https://${action.username.getDomain()}"), + homeServerUri = Uri.parse("https://${action.username.getServerName()}"), homeServerUriBase = Uri.parse(wellKnownPrompt.homeServerUrl), identityServerUri = wellKnownPrompt.identityServerUrl?.let { Uri.parse(it) } ) diff --git a/vector/src/main/java/im/vector/app/features/login/LoginWaitForEmailFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginWaitForEmailFragment.kt index cfc627fbfd..07251f52a2 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginWaitForEmailFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginWaitForEmailFragment.kt @@ -34,7 +34,7 @@ data class LoginWaitForEmailFragmentArgument( ) : Parcelable /** - * In this screen, the user is asked to check his emails + * In this screen, the user is asked to check their emails. */ class LoginWaitForEmailFragment @Inject constructor() : AbstractLoginFragment() { diff --git a/vector/src/main/java/im/vector/app/features/login/LoginWebFragment.kt b/vector/src/main/java/im/vector/app/features/login/LoginWebFragment.kt index b55e393339..02ce0bb670 100644 --- a/vector/src/main/java/im/vector/app/features/login/LoginWebFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/LoginWebFragment.kt @@ -45,7 +45,7 @@ import javax.inject.Inject /** * This screen is displayed when the application does not support login flow or registration flow - * of the homeserver, as a fallback to login or to create an account + * of the homeserver, as a fallback to login or to create an account. */ class LoginWebFragment @Inject constructor( private val assetReader: AssetReader @@ -141,6 +141,7 @@ class LoginWebFragment @Inject constructor( .show() } + @Deprecated("Deprecated in Java") override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { super.onReceivedError(view, errorCode, description, failingUrl) @@ -188,11 +189,12 @@ class LoginWebFragment @Inject constructor( * } * } * } - *
  • + *
    . * @param view * @param url * @return */ + @Deprecated("Deprecated in Java") override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { if (url == null) return super.shouldOverrideUrlLoading(view, url as String?) diff --git a/vector/src/main/java/im/vector/app/features/login/ReAuthHelper.kt b/vector/src/main/java/im/vector/app/features/login/ReAuthHelper.kt index f379048568..b29c930234 100644 --- a/vector/src/main/java/im/vector/app/features/login/ReAuthHelper.kt +++ b/vector/src/main/java/im/vector/app/features/login/ReAuthHelper.kt @@ -21,7 +21,7 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Will store the account password for 3 minutes + * Will store the account password for 3 minutes. */ @Singleton class ReAuthHelper @Inject constructor() : TemporaryStore() diff --git a/vector/src/main/java/im/vector/app/features/login/SupportedStage.kt b/vector/src/main/java/im/vector/app/features/login/SupportedStage.kt index 5ff00f7e85..f338f04401 100644 --- a/vector/src/main/java/im/vector/app/features/login/SupportedStage.kt +++ b/vector/src/main/java/im/vector/app/features/login/SupportedStage.kt @@ -19,7 +19,7 @@ package im.vector.app.features.login import org.matrix.android.sdk.api.auth.registration.Stage /** - * Stage.Other is not supported, as well as any other new stages added to the SDK before it is added to the list below + * Stage.Other is not supported, as well as any other new stages added to the SDK before it is added to the list below. */ fun Stage.isSupported(): Boolean { return this is Stage.ReCaptcha || diff --git a/vector/src/main/java/im/vector/app/features/login/terms/LoginTermsFragment.kt b/vector/src/main/java/im/vector/app/features/login/terms/LoginTermsFragment.kt index 262b79226e..ce499f290b 100755 --- a/vector/src/main/java/im/vector/app/features/login/terms/LoginTermsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login/terms/LoginTermsFragment.kt @@ -40,7 +40,7 @@ data class LoginTermsFragmentArgument( ) : Parcelable /** - * LoginTermsFragment displays the list of policies the user has to accept + * LoginTermsFragment displays the list of policies the user has to accept. */ class LoginTermsFragment @Inject constructor( private val policyController: PolicyController diff --git a/vector/src/main/java/im/vector/app/features/login2/AbstractLoginFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/AbstractLoginFragment2.kt index 68568d1420..0b82ea445d 100644 --- a/vector/src/main/java/im/vector/app/features/login2/AbstractLoginFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/AbstractLoginFragment2.kt @@ -32,7 +32,7 @@ import kotlinx.coroutines.CancellationException import org.matrix.android.sdk.api.failure.Failure /** - * Parent Fragment for all the login/registration screens + * Parent Fragment for all the login/registration screens. */ abstract class AbstractLoginFragment2 : VectorBaseFragment(), OnBackPressed { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginCaptchaFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginCaptchaFragment2.kt index f729584f51..5fabe0ca32 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginCaptchaFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginCaptchaFragment2.kt @@ -44,7 +44,7 @@ import java.util.Formatter import javax.inject.Inject /** - * In this screen, the user is asked to confirm he is not a robot + * In this screen, the user is asked to confirm he is not a robot. */ class LoginCaptchaFragment2 @Inject constructor( private val assetReader: AssetReader @@ -152,12 +152,14 @@ class LoginCaptchaFragment2 @Inject constructor( } } + @Deprecated("Deprecated in Java") override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { @Suppress("DEPRECATION") super.onReceivedError(view, errorCode, description, failingUrl) onError(description) } + @Deprecated("Deprecated in Java") override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { if (url?.startsWith("js:") == true) { var json = url.substring(3) diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninPassword2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninPassword2.kt index 5c9cefd2db..34bebd655a 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninPassword2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninPassword2.kt @@ -157,7 +157,7 @@ class LoginFragmentSigninPassword2 @Inject constructor( } /** - * Detect if password ends or starts with spaces + * Detect if password ends or starts with spaces. */ private fun spaceInPassword() = views.passwordField.text.toString().let { it.trim() != it } } diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninUsername2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninUsername2.kt index b90887dba1..cb346451de 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninUsername2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginFragmentSigninUsername2.kt @@ -36,7 +36,7 @@ import javax.inject.Inject /** * In this screen: - * - the user is asked for its matrix ID, and have the possibility to open the screen to select a server + * - the user is asked for its matrix ID, and have the possibility to open the screen to select a server. */ class LoginFragmentSigninUsername2 @Inject constructor() : AbstractLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginFragmentToAny2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginFragmentToAny2.kt index 3fa0e6c549..064889876b 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginFragmentToAny2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginFragmentToAny2.kt @@ -195,7 +195,7 @@ class LoginFragmentToAny2 @Inject constructor() : AbstractSSOLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordFragment2.kt index 038a12bea7..7916d9bbf2 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordFragment2.kt @@ -40,7 +40,7 @@ import reactivecircus.flowbinding.android.widget.textChanges import javax.inject.Inject /** - * In this screen, the user is asked for email and new password to reset his password + * In this screen, the user is asked for email and new password to reset his password. */ class LoginResetPasswordFragment2 @Inject constructor() : AbstractLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordMailConfirmationFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordMailConfirmationFragment2.kt index b5b091f530..de1bcb8eea 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordMailConfirmationFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordMailConfirmationFragment2.kt @@ -27,7 +27,7 @@ import org.matrix.android.sdk.api.failure.is401 import javax.inject.Inject /** - * In this screen, the user is asked to check his email and to click on a button once it's done + * In this screen, the user is asked to check their email and to click on a button once it's done. */ class LoginResetPasswordMailConfirmationFragment2 @Inject constructor() : AbstractLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordSuccessFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordSuccessFragment2.kt index 25c27fa9ed..33ebd13f2a 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordSuccessFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginResetPasswordSuccessFragment2.kt @@ -24,7 +24,7 @@ import im.vector.app.databinding.FragmentLoginResetPasswordSuccess2Binding import javax.inject.Inject /** - * In this screen, we confirm to the user that his password has been reset + * In this screen, we confirm to the user that his password has been reset. */ class LoginResetPasswordSuccessFragment2 @Inject constructor() : AbstractLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginServerSelectionFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginServerSelectionFragment2.kt index 60e381b047..27fb74c3b0 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginServerSelectionFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginServerSelectionFragment2.kt @@ -28,7 +28,7 @@ import im.vector.app.features.login.EMS_LINK import javax.inject.Inject /** - * In this screen, the user will choose between matrix.org, or other type of homeserver + * In this screen, the user will choose between matrix.org, or other type of homeserver. */ class LoginServerSelectionFragment2 @Inject constructor() : AbstractLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginServerUrlFormFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginServerUrlFormFragment2.kt index b0201abc9a..0561594eeb 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginServerUrlFormFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginServerUrlFormFragment2.kt @@ -41,7 +41,7 @@ import javax.inject.Inject import javax.net.ssl.HttpsURLConnection /** - * In this screen, the user is prompted to enter a homeserver url + * In this screen, the user is prompted to enter a homeserver url. */ class LoginServerUrlFormFragment2 @Inject constructor() : AbstractLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginSplashSignUpSignInSelectionFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginSplashSignUpSignInSelectionFragment2.kt index db6e86250b..611b5f4cd2 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginSplashSignUpSignInSelectionFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginSplashSignUpSignInSelectionFragment2.kt @@ -28,8 +28,8 @@ import im.vector.app.features.settings.VectorPreferences import javax.inject.Inject /** - * In this screen, the user is asked to sign up or to sign in to the homeserver - * This is the new splash screen + * In this screen, the user is asked to sign up or to sign in to the homeserver. + * This is the new splash screen. */ class LoginSplashSignUpSignInSelectionFragment2 @Inject constructor( private val vectorPreferences: VectorPreferences diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginSsoOnlyFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginSsoOnlyFragment2.kt index 4e41ed20ac..7aa2150c98 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginSsoOnlyFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginSsoOnlyFragment2.kt @@ -28,7 +28,7 @@ import im.vector.app.features.login.SSORedirectRouterActivity import javax.inject.Inject /** - * In this screen, the user is asked to sign up or to sign in to the homeserver + * In this screen, the user is asked to sign up or to sign in to the homeserver. */ class LoginSsoOnlyFragment2 @Inject constructor() : AbstractSSOLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginViewEvents2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginViewEvents2.kt index ee145d786f..11a441923e 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginViewEvents2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginViewEvents2.kt @@ -21,7 +21,7 @@ import im.vector.app.core.platform.VectorViewEvents import org.matrix.android.sdk.api.auth.registration.FlowResult /** - * Transient events for Login + * Transient events for Login. */ sealed class LoginViewEvents2 : VectorViewEvents { data class Failure(val throwable: Throwable) : LoginViewEvents2() diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginViewModel2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginViewModel2.kt index 62f0007104..6b9d255937 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginViewModel2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginViewModel2.kt @@ -38,7 +38,7 @@ import im.vector.app.features.login.LoginMode import im.vector.app.features.login.ReAuthHelper import kotlinx.coroutines.Job import kotlinx.coroutines.launch -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.auth.AuthenticationService import org.matrix.android.sdk.api.auth.HomeServerHistoryService import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig @@ -310,7 +310,7 @@ class LoginViewModel2 @AssistedInject constructor( } /** - * Check that the user name is available + * Check that the user name is available. */ private fun handleSetUserNameForSignUp(action: LoginAction2.SetUserName) { setState { copy(isLoading = true) } @@ -562,7 +562,7 @@ class LoginViewModel2 @AssistedInject constructor( } /** - * Perform wellknown request + * Perform wellknown request. */ private fun handleSetUserNameForSignIn(action: LoginAction2.SetUserName, homeServerConnectionConfig: HomeServerConnectionConfig?) { setState { copy(isLoading = true) } @@ -640,7 +640,7 @@ class LoginViewModel2 @AssistedInject constructor( } viewEvent?.let { _viewEvents.post(it) } - val urlFromUser = action.username.getDomain() + val urlFromUser = action.username.getServerName() setState { copy( isLoading = false, diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginWaitForEmailFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginWaitForEmailFragment2.kt index 0cac52b306..772db7be5f 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginWaitForEmailFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginWaitForEmailFragment2.kt @@ -28,7 +28,7 @@ import org.matrix.android.sdk.api.failure.is401 import javax.inject.Inject /** - * In this screen, the user is asked to check his emails + * In this screen, the user is asked to check their emails. */ class LoginWaitForEmailFragment2 @Inject constructor() : AbstractLoginFragment2() { diff --git a/vector/src/main/java/im/vector/app/features/login2/LoginWebFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/LoginWebFragment2.kt index 789cd459ac..cf8952b944 100644 --- a/vector/src/main/java/im/vector/app/features/login2/LoginWebFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/LoginWebFragment2.kt @@ -46,7 +46,7 @@ import javax.inject.Inject /** * This screen is displayed when the application does not support login flow or registration flow - * of the homeserver, as a fallback to login or to create an account + * of the homeserver, as a fallback to login or to create an account. */ class LoginWebFragment2 @Inject constructor( private val assetReader: AssetReader @@ -142,6 +142,7 @@ class LoginWebFragment2 @Inject constructor( .show() } + @Deprecated("Deprecated in Java") override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { super.onReceivedError(view, errorCode, description, failingUrl) @@ -189,11 +190,13 @@ class LoginWebFragment2 @Inject constructor( * } * } * } + * . *
    * @param view * @param url * @return */ + @Deprecated("Deprecated in Java") override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { if (url == null) return super.shouldOverrideUrlLoading(view, url as String?) diff --git a/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedFragment.kt b/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedFragment.kt index 87363854b1..d549c22028 100644 --- a/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedFragment.kt +++ b/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedFragment.kt @@ -47,7 +47,7 @@ import javax.inject.Inject /** * In this screen: - * - the account has been created and we propose the user to set an avatar and a display name + * - the account has been created and we propose the user to set an avatar and a display name. */ class AccountCreatedFragment @Inject constructor( private val avatarRenderer: AvatarRenderer, diff --git a/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedViewEvents.kt b/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedViewEvents.kt index 4677e1abd5..6a23409f5c 100644 --- a/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/login2/created/AccountCreatedViewEvents.kt @@ -20,7 +20,7 @@ package im.vector.app.features.login2.created import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for Account Created + * Transient events for Account Created. */ sealed class AccountCreatedViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : AccountCreatedViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/login2/terms/LoginTermsFragment2.kt b/vector/src/main/java/im/vector/app/features/login2/terms/LoginTermsFragment2.kt index 303fc5ef17..a48996a16f 100755 --- a/vector/src/main/java/im/vector/app/features/login2/terms/LoginTermsFragment2.kt +++ b/vector/src/main/java/im/vector/app/features/login2/terms/LoginTermsFragment2.kt @@ -37,7 +37,7 @@ import org.matrix.android.sdk.api.auth.data.LocalizedFlowDataLoginTerms import javax.inject.Inject /** - * LoginTermsFragment displays the list of policies the user has to accept + * LoginTermsFragment displays the list of policies the user has to accept. */ class LoginTermsFragment2 @Inject constructor( private val policyController: PolicyController diff --git a/vector/src/main/java/im/vector/app/features/matrixto/MatrixToBottomSheetViewModel.kt b/vector/src/main/java/im/vector/app/features/matrixto/MatrixToBottomSheetViewModel.kt index 18070c8e6c..22082a36e7 100644 --- a/vector/src/main/java/im/vector/app/features/matrixto/MatrixToBottomSheetViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/matrixto/MatrixToBottomSheetViewModel.kt @@ -246,7 +246,7 @@ class MatrixToBottomSheetViewModel @AssistedInject constructor( /** * Let's try to get some information about that room, - * main thing is trying to see if it's a space or a room + * main thing is trying to see if it's a space or a room. */ private suspend fun resolveRoom(roomIdOrAlias: String): PeekResult { return session.roomService().peekRoom(roomIdOrAlias) diff --git a/vector/src/main/java/im/vector/app/features/media/BigImageViewerActivity.kt b/vector/src/main/java/im/vector/app/features/media/BigImageViewerActivity.kt index a6b166815c..4a9304846e 100644 --- a/vector/src/main/java/im/vector/app/features/media/BigImageViewerActivity.kt +++ b/vector/src/main/java/im/vector/app/features/media/BigImageViewerActivity.kt @@ -27,7 +27,7 @@ import im.vector.app.databinding.ActivityBigImageViewerBinding import javax.inject.Inject /** - * Simple Activity to display an avatar in fullscreen + * Simple Activity to display an avatar in fullscreen. */ @AndroidEntryPoint class BigImageViewerActivity : VectorBaseActivity() { diff --git a/vector/src/main/java/im/vector/app/features/media/ImageContentRenderer.kt b/vector/src/main/java/im/vector/app/features/media/ImageContentRenderer.kt index 50325327db..49bced7e81 100644 --- a/vector/src/main/java/im/vector/app/features/media/ImageContentRenderer.kt +++ b/vector/src/main/java/im/vector/app/features/media/ImageContentRenderer.kt @@ -91,7 +91,7 @@ class ImageContentRenderer @Inject constructor(private val localFilesHelper: Loc } /** - * For url preview + * For url preview. */ fun render(previewUrlData: PreviewUrlData, imageView: ImageView): Boolean { val contentUrlResolver = activeSessionHolder.getActiveSession().contentUrlResolver() @@ -112,7 +112,7 @@ class ImageContentRenderer @Inject constructor(private val localFilesHelper: Loc } /** - * For gallery + * For gallery. */ fun render(data: Data, imageView: ImageView, size: Int) { // a11y @@ -149,7 +149,7 @@ class ImageContentRenderer @Inject constructor(private val localFilesHelper: Loc } /** - * Used by Attachment Viewer + * Used by Attachment Viewer. */ fun render(data: Data, contextView: View, target: CustomViewTarget<*, Drawable>) { val req = if (data.elementToDecrypt != null) { diff --git a/vector/src/main/java/im/vector/app/features/navigation/DefaultNavigator.kt b/vector/src/main/java/im/vector/app/features/navigation/DefaultNavigator.kt index 7cc42ec57f..0f921ab80a 100644 --- a/vector/src/main/java/im/vector/app/features/navigation/DefaultNavigator.kt +++ b/vector/src/main/java/im/vector/app/features/navigation/DefaultNavigator.kt @@ -317,6 +317,7 @@ class DefaultNavigator @Inject constructor( if (context is AppCompatActivity) { if (context !is MatrixToBottomSheet.InteractionListener) { fatalError("Caller context should implement MatrixToBottomSheet.InteractionListener", vectorPreferences.failFast()) + return } // TODO check if there is already one?? MatrixToBottomSheet.withLink(link, origin) diff --git a/vector/src/main/java/im/vector/app/features/notifications/CircularCache.kt b/vector/src/main/java/im/vector/app/features/notifications/CircularCache.kt index 1ac66d0ae8..5c751e0d55 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/CircularCache.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/CircularCache.kt @@ -17,8 +17,8 @@ package im.vector.app.features.notifications /** - * A FIFO circular buffer of T - * This class is not thread safe + * A FIFO circular buffer of T. + * This class is not thread safe. */ class CircularCache(cacheSize: Int, factory: (Int) -> Array) { diff --git a/vector/src/main/java/im/vector/app/features/notifications/NotifiableEvent.kt b/vector/src/main/java/im/vector/app/features/notifications/NotifiableEvent.kt index a9ad79febf..0f33c525e5 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/NotifiableEvent.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/NotifiableEvent.kt @@ -18,7 +18,7 @@ package im.vector.app.features.notifications import java.io.Serializable /** - * Parent interface for all events which can be displayed as a Notification + * Parent interface for all events which can be displayed as a Notification. */ sealed interface NotifiableEvent : Serializable { val eventId: String diff --git a/vector/src/main/java/im/vector/app/features/notifications/NotifiableEventResolver.kt b/vector/src/main/java/im/vector/app/features/notifications/NotifiableEventResolver.kt index 80f5f47b3b..b9d9261abe 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/NotifiableEventResolver.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/NotifiableEventResolver.kt @@ -215,7 +215,7 @@ class NotifiableEventResolver @Inject constructor( keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) }, forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain ) - } catch (e: MXCryptoError) { + } catch (ignore: MXCryptoError) { } } } diff --git a/vector/src/main/java/im/vector/app/features/notifications/NotificationBitmapLoader.kt b/vector/src/main/java/im/vector/app/features/notifications/NotificationBitmapLoader.kt index 518b011ffd..c289d79ee8 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/NotificationBitmapLoader.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/NotificationBitmapLoader.kt @@ -33,7 +33,7 @@ import javax.inject.Singleton class NotificationBitmapLoader @Inject constructor(private val context: Context) { /** - * Get icon of a room + * Get icon of a room. */ @WorkerThread fun getRoomBitmap(path: String?): Bitmap? { diff --git a/vector/src/main/java/im/vector/app/features/notifications/NotificationBroadcastReceiver.kt b/vector/src/main/java/im/vector/app/features/notifications/NotificationBroadcastReceiver.kt index 4205f2ca5a..a4022f75c8 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/NotificationBroadcastReceiver.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/NotificationBroadcastReceiver.kt @@ -39,7 +39,7 @@ import java.util.UUID import javax.inject.Inject /** - * Receives actions broadcast by notification (on click, on dismiss, inline replies, etc.) + * Receives actions broadcast by notification (on click, on dismiss, inline replies, etc.). */ @AndroidEntryPoint class NotificationBroadcastReceiver : BroadcastReceiver() { diff --git a/vector/src/main/java/im/vector/app/features/notifications/NotificationDrawerManager.kt b/vector/src/main/java/im/vector/app/features/notifications/NotificationDrawerManager.kt index 1243d3f798..5819e02897 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/NotificationDrawerManager.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/NotificationDrawerManager.kt @@ -57,7 +57,7 @@ class NotificationDrawerManager @Inject constructor( get() = activeSessionDataSource.currentValue?.orNull() /** - * Lazily initializes the NotificationState as we rely on having a current session in order to fetch the persisted queue of events + * Lazily initializes the NotificationState as we rely on having a current session in order to fetch the persisted queue of events. */ private val notificationState by lazy { createInitialNotificationState() } private val avatarSize = context.resources.getDimensionPixelSize(R.dimen.profile_avatar_size) @@ -102,7 +102,7 @@ class NotificationDrawerManager @Inject constructor( } /** - * Clear all known events and refresh the notification drawer + * Clear all known events and refresh the notification drawer. */ fun clearAllEvents() { updateEvents { it.clear() } diff --git a/vector/src/main/java/im/vector/app/features/notifications/NotificationState.kt b/vector/src/main/java/im/vector/app/features/notifications/NotificationState.kt index 193116a6bc..3114cd45ca 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/NotificationState.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/NotificationState.kt @@ -18,19 +18,19 @@ package im.vector.app.features.notifications class NotificationState( /** - * The notifiable events queued for rendering or currently rendered + * The notifiable events queued for rendering or currently rendered. * - * this is our source of truth for notifications, any changes to this list will be rendered as notifications - * when events are removed the previously rendered notifications will be cancelled - * when adding or updating, the notifications will be notified + * This is our source of truth for notifications, any changes to this list will be rendered as notifications. + * When events are removed the previously rendered notifications will be cancelled. + * When adding or updating, the notifications will be notified. * - * Events are unique by their properties, we should be careful not to insert multiple events with the same event-id + * Events are unique by their properties, we should be careful not to insert multiple events with the same event-id. */ private val queuedEvents: NotificationEventQueue, /** - * The last known rendered notifiable events - * we keep track of them in order to know which events have been removed from the eventList + * The last known rendered notifiable events. + * We keep track of them in order to know which events have been removed from the eventList * allowing us to cancel any notifications previous displayed by now removed events */ private val renderedEvents: MutableList>, diff --git a/vector/src/main/java/im/vector/app/features/notifications/NotificationUtils.kt b/vector/src/main/java/im/vector/app/features/notifications/NotificationUtils.kt index 78d771ee1c..d03fcadcfa 100755 --- a/vector/src/main/java/im/vector/app/features/notifications/NotificationUtils.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/NotificationUtils.kt @@ -230,7 +230,7 @@ class NotificationUtils @Inject constructor( } /** - * Build a polling thread listener notification + * Build a polling thread listener notification. * * @param subTitleResId subtitle string resource Id of the notification * @return the polling thread listener notification @@ -428,7 +428,7 @@ class NotificationUtils @Inject constructor( } /** - * Build a pending call notification + * Build a pending call notification. * * @param isVideo true if this is a video call, false for voice call * @param roomName the room name in which the call is pending. @@ -489,7 +489,7 @@ class NotificationUtils @Inject constructor( } /** - * Build a temporary (because service will be stopped just after) notification for the CallService, when a call is ended + * Build a temporary (because service will be stopped just after) notification for the CallService, when a call is ended. */ fun buildCallEndedNotification(isVideoCall: Boolean): Notification { return NotificationCompat.Builder(context, SILENT_NOTIFICATION_CHANNEL_ID) @@ -508,7 +508,7 @@ class NotificationUtils @Inject constructor( } /** - * Build notification for the CallService, when a call is missed + * Build notification for the CallService, when a call is missed. */ fun buildCallMissedNotification(callInformation: CallService.CallInformation): Notification { val builder = NotificationCompat.Builder(context, SILENT_NOTIFICATION_CHANNEL_ID) @@ -588,7 +588,7 @@ class NotificationUtils @Inject constructor( } /** - * Build a notification for a Room + * Build a notification for a Room. */ fun buildMessagesListNotification(messageStyle: NotificationCompat.MessagingStyle, roomInfo: RoomEventGroupInfo, @@ -889,7 +889,7 @@ class NotificationUtils @Inject constructor( // // Number of new notifications for API <24 (M and below) devices. /** - * Build the summary notification + * Build the summary notification. */ fun buildSummaryListNotification(style: NotificationCompat.InboxStyle?, compatSummary: String, @@ -951,14 +951,14 @@ class NotificationUtils @Inject constructor( } /** - * Cancel the foreground notification service + * Cancel the foreground notification service. */ fun cancelNotificationForegroundService() { notificationManager.cancel(NOTIFICATION_ID_FOREGROUND_SERVICE) } /** - * Cancel all the notification + * Cancel all the notification. */ fun cancelAllNotifications() { // Keep this try catch (reported by GA) @@ -1007,7 +1007,7 @@ class NotificationUtils @Inject constructor( } /** - * Return true it the user has enabled the do not disturb mode + * Return true it the user has enabled the do not disturb mode. */ fun isDoNotDisturbModeOn(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { diff --git a/vector/src/main/java/im/vector/app/features/notifications/RoomEventGroupInfo.kt b/vector/src/main/java/im/vector/app/features/notifications/RoomEventGroupInfo.kt index 6ec4645382..fa1df1e753 100644 --- a/vector/src/main/java/im/vector/app/features/notifications/RoomEventGroupInfo.kt +++ b/vector/src/main/java/im/vector/app/features/notifications/RoomEventGroupInfo.kt @@ -17,7 +17,7 @@ package im.vector.app.features.notifications /** - * Data class to hold information about a group of notifications for a room + * Data class to hold information about a group of notifications for a room. */ data class RoomEventGroupInfo( val roomId: String, diff --git a/vector/src/main/java/im/vector/app/features/onboarding/DirectLoginUseCase.kt b/vector/src/main/java/im/vector/app/features/onboarding/DirectLoginUseCase.kt index 171d8f7bb5..3014b199b4 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/DirectLoginUseCase.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/DirectLoginUseCase.kt @@ -20,7 +20,7 @@ import im.vector.app.R import im.vector.app.core.extensions.andThen import im.vector.app.core.resources.StringProvider import im.vector.app.features.onboarding.OnboardingAction.LoginOrRegister -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.auth.AuthenticationService import org.matrix.android.sdk.api.auth.data.HomeServerConnectionConfig import org.matrix.android.sdk.api.auth.wellknown.WellknownResult @@ -75,7 +75,7 @@ class DirectLoginUseCase @Inject constructor( ) private fun fallbackConfig(action: LoginOrRegister, wellKnownPrompt: WellknownResult.Prompt) = HomeServerConnectionConfig( - homeServerUri = uriFactory.parse("https://${action.username.getDomain()}"), + homeServerUri = uriFactory.parse("https://${action.username.getServerName()}"), homeServerUriBase = uriFactory.parse(wellKnownPrompt.homeServerUrl), identityServerUri = wellKnownPrompt.identityServerUrl?.let { uriFactory.parse(it) } ) diff --git a/vector/src/main/java/im/vector/app/features/onboarding/Login2Variant.kt b/vector/src/main/java/im/vector/app/features/onboarding/Login2Variant.kt index 9f63ff3e22..e6b5cfc95c 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/Login2Variant.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/Login2Variant.kt @@ -309,9 +309,9 @@ class Login2Variant( activity.finish() } - private fun updateWithState(LoginViewState2: LoginViewState2) { + private fun updateWithState(loginViewState2: LoginViewState2) { // Loading - setIsLoading(LoginViewState2.isLoading) + setIsLoading(loginViewState2.isLoading) } // Hack for AccountCreatedFragment @@ -332,7 +332,7 @@ class Login2Variant( } /** - * Handle the SSO redirection here + * Handle the SSO redirection here. */ override fun onNewIntent(intent: Intent?) { intent?.data diff --git a/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewEvents.kt b/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewEvents.kt index ee406aff48..6ffece4ab6 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewEvents.kt @@ -23,7 +23,7 @@ import im.vector.app.features.login.SignMode import org.matrix.android.sdk.api.auth.registration.FlowResult /** - * Transient events for Login + * Transient events for Login. */ sealed class OnboardingViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : OnboardingViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewModel.kt b/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewModel.kt index 25ae0327a8..03526b47a5 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/OnboardingViewModel.kt @@ -677,8 +677,8 @@ class OnboardingViewModel @AssistedInject constructor( } /** - * If user has entered https://matrix.org, ensure that server type is ServerType.MatrixOrg - * It is also useful to set the value again in the case of a certificate error on matrix.org + * If user has entered https://matrix.org, ensure that server type is ServerType.MatrixOrg. + * It is also useful to set the value again in the case of a certificate error on matrix.org. **/ private fun OnboardingViewState.alignServerTypeAfterSubmission(config: HomeServerConnectionConfig, serverTypeOverride: ServerType?): ServerType { return if (config.homeServerUri.toString() == matrixOrgUrl) { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/AbstractFtueAuthFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/AbstractFtueAuthFragment.kt index 64e29766c5..f5c81773ea 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/AbstractFtueAuthFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/AbstractFtueAuthFragment.kt @@ -36,7 +36,7 @@ import kotlinx.coroutines.CancellationException import org.matrix.android.sdk.api.failure.Failure /** - * Parent Fragment for all the login/registration screens + * Parent Fragment for all the login/registration screens. */ abstract class AbstractFtueAuthFragment : VectorBaseFragment(), OnBackPressed { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/CaptchaWebview.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/CaptchaWebview.kt index 558c26fe56..c4099effa7 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/CaptchaWebview.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/CaptchaWebview.kt @@ -103,12 +103,14 @@ class CaptchaWebview @Inject constructor( } } + @Deprecated("Deprecated in Java") override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { @Suppress("DEPRECATION") super.onReceivedError(view, errorCode, description, failingUrl) onError(description) } + @Deprecated("Deprecated in Java") override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { if (url?.startsWith("js:") == true) { val javascriptResponse = parseJsonFromUrl(url) diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthCaptchaFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthCaptchaFragment.kt index a3665a8f40..3720a41455 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthCaptchaFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthCaptchaFragment.kt @@ -33,7 +33,7 @@ data class FtueAuthCaptchaFragmentArgument( ) : Parcelable /** - * In this screen, the user is asked to confirm they are not a robot + * In this screen, the user is asked to confirm they are not a robot. */ class FtueAuthCaptchaFragment @Inject constructor( private val captchaWebview: CaptchaWebview diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthGenericTextInputFormFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthGenericTextInputFormFragment.kt index 466e141fdf..ce3dee7a19 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthGenericTextInputFormFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthGenericTextInputFormFragment.kt @@ -55,7 +55,7 @@ data class FtueAuthGenericTextInputFormFragmentArgument( ) : Parcelable /** - * In this screen, the user is asked for a text input + * In this screen, the user is asked for a text input. */ class FtueAuthGenericTextInputFormFragment @Inject constructor() : AbstractFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLegacyStyleCaptchaFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLegacyStyleCaptchaFragment.kt index 2accab00e0..b8b30529a6 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLegacyStyleCaptchaFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLegacyStyleCaptchaFragment.kt @@ -33,7 +33,7 @@ data class FtueAuthLegacyStyleCaptchaFragmentArgument( ) : Parcelable /** - * In this screen, the user is asked to confirm they are not a robot + * In this screen, the user is asked to confirm they are not a robot. */ class FtueAuthLegacyStyleCaptchaFragment @Inject constructor( private val captchaWebview: CaptchaWebview diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLoginFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLoginFragment.kt index 696ebb4786..2308280400 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLoginFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthLoginFragment.kt @@ -310,7 +310,7 @@ class FtueAuthLoginFragment @Inject constructor() : AbstractSSOFtueAuthFragment< } /** - * Detect if password ends or starts with spaces + * Detect if password ends or starts with spaces. */ private fun spaceInPassword() = views.passwordField.text.toString().let { it.trim() != it } } diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordFragment.kt index 4ec02f677a..9bef084750 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordFragment.kt @@ -38,7 +38,7 @@ import reactivecircus.flowbinding.android.widget.textChanges import javax.inject.Inject /** - * In this screen, the user is asked for email and new password to reset his password + * In this screen, the user is asked for email and new password to reset his password. */ class FtueAuthResetPasswordFragment @Inject constructor() : AbstractFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordMailConfirmationFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordMailConfirmationFragment.kt index f6141a4900..fd7f14b1cc 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordMailConfirmationFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordMailConfirmationFragment.kt @@ -29,7 +29,7 @@ import org.matrix.android.sdk.api.failure.is401 import javax.inject.Inject /** - * In this screen, the user is asked to check his email and to click on a button once it's done + * In this screen, the user is asked to check their email and to click on a button once it's done. */ class FtueAuthResetPasswordMailConfirmationFragment @Inject constructor() : AbstractFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordSuccessFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordSuccessFragment.kt index 74b1a7f8c2..adc6e1b214 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordSuccessFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthResetPasswordSuccessFragment.kt @@ -26,7 +26,7 @@ import im.vector.app.features.onboarding.OnboardingViewEvents import javax.inject.Inject /** - * In this screen, we confirm to the user that his password has been reset + * In this screen, we confirm to the user that his password has been reset. */ class FtueAuthResetPasswordSuccessFragment @Inject constructor() : AbstractFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerSelectionFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerSelectionFragment.kt index f72bd2c5d3..d4396d81d2 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerSelectionFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerSelectionFragment.kt @@ -32,7 +32,7 @@ import me.gujun.android.span.span import javax.inject.Inject /** - * In this screen, the user will choose between matrix.org, modular or other type of homeserver + * In this screen, the user will choose between matrix.org, modular or other type of homeserver. */ class FtueAuthServerSelectionFragment @Inject constructor() : AbstractFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerUrlFormFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerUrlFormFragment.kt index c542f80712..7c2fb1b8e2 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerUrlFormFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthServerUrlFormFragment.kt @@ -45,7 +45,7 @@ import java.net.UnknownHostException import javax.inject.Inject /** - * In this screen, the user is prompted to enter a homeserver url + * In this screen, the user is prompted to enter a homeserver url. */ class FtueAuthServerUrlFormFragment @Inject constructor() : AbstractFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSignUpSignInSelectionFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSignUpSignInSelectionFragment.kt index dda5e0c36a..69fbd3459b 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSignUpSignInSelectionFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSignUpSignInSelectionFragment.kt @@ -37,7 +37,7 @@ import im.vector.app.features.onboarding.OnboardingViewState import javax.inject.Inject /** - * In this screen, the user is asked to sign up or to sign in to the homeserver + * In this screen, the user is asked to sign up or to sign in to the homeserver. */ class FtueAuthSignUpSignInSelectionFragment @Inject constructor() : AbstractSSOFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSplashFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSplashFragment.kt index 031579db5f..2fa3b52706 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSplashFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthSplashFragment.kt @@ -36,7 +36,7 @@ import java.net.UnknownHostException import javax.inject.Inject /** - * In this screen, the user is viewing an introduction to what he can do with this application + * In this screen, the user is viewing an introduction to what he can do with this application. */ class FtueAuthSplashFragment @Inject constructor( private val vectorPreferences: VectorPreferences, diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthVariant.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthVariant.kt index 2fe9a82fbd..6f1b85df4f 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthVariant.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthVariant.kt @@ -288,8 +288,8 @@ class FtueAuthVariant( .show() } - private fun onServerSelectionDone(OnboardingViewEvents: OnboardingViewEvents.OnServerSelectionDone) { - when (OnboardingViewEvents.serverType) { + private fun onServerSelectionDone(onboardingViewEvents: OnboardingViewEvents.OnServerSelectionDone) { + when (onboardingViewEvents.serverType) { ServerType.MatrixOrg -> Unit // In this case, we wait for the login flow ServerType.EMS, ServerType.Other -> activity.addFragmentToBackstack( @@ -301,9 +301,9 @@ class FtueAuthVariant( } } - private fun onSignModeSelected(OnboardingViewEvents: OnboardingViewEvents.OnSignModeSelected) = withState(onboardingViewModel) { state -> + private fun onSignModeSelected(onboardingViewEvents: OnboardingViewEvents.OnSignModeSelected) = withState(onboardingViewModel) { state -> // state.signMode could not be ready yet. So use value from the ViewEvent - when (OnboardingViewEvents.signMode) { + when (onboardingViewEvents.signMode) { SignMode.Unknown -> error("Sign mode has to be set before calling this method") SignMode.SignUp -> Unit // This case is processed in handleOnboardingViewEvents SignMode.SignIn -> handleSignInSelected(state) @@ -362,7 +362,7 @@ class FtueAuthVariant( } /** - * Handle the SSO redirection here + * Handle the SSO redirection here. */ override fun onNewIntent(intent: Intent?) { intent?.data diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWaitForEmailFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWaitForEmailFragment.kt index 6056cd30d3..d78e0fe74d 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWaitForEmailFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWaitForEmailFragment.kt @@ -36,7 +36,7 @@ data class FtueAuthWaitForEmailFragmentArgument( ) : Parcelable /** - * In this screen, the user is asked to check his emails + * In this screen, the user is asked to check their emails. */ class FtueAuthWaitForEmailFragment @Inject constructor() : AbstractFtueAuthFragment() { diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWebFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWebFragment.kt index 26b9a38d83..68e8632608 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWebFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/FtueAuthWebFragment.kt @@ -47,7 +47,7 @@ import javax.inject.Inject /** * This screen is displayed when the application does not support login flow or registration flow - * of the homeserver, as a fallback to login or to create an account + * of the homeserver, as a fallback to login or to create an account. */ class FtueAuthWebFragment @Inject constructor( private val assetReader: AssetReader @@ -138,6 +138,7 @@ class FtueAuthWebFragment @Inject constructor( .show() } + @Deprecated("Deprecated in Java") override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { super.onReceivedError(view, errorCode, description, failingUrl) @@ -186,10 +187,12 @@ class FtueAuthWebFragment @Inject constructor( * } * } *
    + * . * @param view * @param url * @return */ + @Deprecated("Deprecated in Java") override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { if (url == null) return super.shouldOverrideUrlLoading(view, url as String?) diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthLegacyStyleTermsFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthLegacyStyleTermsFragment.kt index 727e3d5cbd..af38062663 100755 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthLegacyStyleTermsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthLegacyStyleTermsFragment.kt @@ -44,7 +44,7 @@ data class FtueAuthTermsLegacyStyleFragmentArgument( ) : Parcelable /** - * LoginTermsFragment displays the list of policies the user has to accept + * LoginTermsFragment displays the list of policies the user has to accept. */ class FtueAuthLegacyStyleTermsFragment @Inject constructor( private val policyController: PolicyController diff --git a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthTermsFragment.kt b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthTermsFragment.kt index 4a25e35537..f168536575 100644 --- a/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthTermsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/onboarding/ftueauth/terms/FtueAuthTermsFragment.kt @@ -41,7 +41,7 @@ import javax.inject.Inject import kotlin.math.roundToInt /** - * LoginTermsFragment displays the list of policies the user has to accept + * LoginTermsFragment displays the list of policies the user has to accept. */ class FtueAuthTermsFragment @Inject constructor( private val policyController: PolicyController diff --git a/vector/src/main/java/im/vector/app/features/permalink/PermalinkHandler.kt b/vector/src/main/java/im/vector/app/features/permalink/PermalinkHandler.kt index 74b696510f..5d1ba4e20c 100644 --- a/vector/src/main/java/im/vector/app/features/permalink/PermalinkHandler.kt +++ b/vector/src/main/java/im/vector/app/features/permalink/PermalinkHandler.kt @@ -165,7 +165,7 @@ class PermalinkHandler @Inject constructor(private val activeSessionHolder: Acti } /** - * Open room either joined, or not + * Open room either joined, or not. */ private fun openRoom( navigationInterceptor: NavigationInterceptor?, @@ -238,14 +238,14 @@ class PermalinkHandler @Inject constructor(private val activeSessionHolder: Acti interface NavigationInterceptor { /** - * Return true if the navigation has been intercepted + * Return true if the navigation has been intercepted. */ fun navToRoom(roomId: String?, eventId: String?, deepLink: Uri? = null, rootThreadEventId: String? = null): Boolean { return false } /** - * Return true if the navigation has been intercepted + * Return true if the navigation has been intercepted. */ fun navToMemberProfile(userId: String, deepLink: Uri): Boolean { return false diff --git a/vector/src/main/java/im/vector/app/features/pin/PinCodeStore.kt b/vector/src/main/java/im/vector/app/features/pin/PinCodeStore.kt index d3632edbca..d067503158 100644 --- a/vector/src/main/java/im/vector/app/features/pin/PinCodeStore.kt +++ b/vector/src/main/java/im/vector/app/features/pin/PinCodeStore.kt @@ -44,17 +44,17 @@ interface PinCodeStore { fun getRemainingBiometricsAttemptsNumber(): Int /** - * Will return the number of remaining attempts + * Will return the number of remaining attempts. */ fun onWrongPin(): Int /** - * Will return the number of remaining attempts + * Will return the number of remaining attempts. */ fun onWrongBiometrics(): Int /** - * Will reset the counters + * Will reset the counters. */ fun resetCounters() diff --git a/vector/src/main/java/im/vector/app/features/pin/PinLocker.kt b/vector/src/main/java/im/vector/app/features/pin/PinLocker.kt index f848a3174e..e41ea320ac 100644 --- a/vector/src/main/java/im/vector/app/features/pin/PinLocker.kt +++ b/vector/src/main/java/im/vector/app/features/pin/PinLocker.kt @@ -22,6 +22,7 @@ import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import im.vector.app.features.settings.VectorPreferences +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import timber.log.Timber @@ -59,7 +60,7 @@ class PinLocker @Inject constructor( return liveState } - @Suppress("EXPERIMENTAL_API_USAGE") + @OptIn(DelicateCoroutinesApi::class) private fun computeState() { GlobalScope.launch { val state = if (shouldBeLocked && pinCodeStore.hasEncodedPin()) { diff --git a/vector/src/main/java/im/vector/app/features/popup/PopupAlertManager.kt b/vector/src/main/java/im/vector/app/features/popup/PopupAlertManager.kt index 5d16fabbfd..3ebcb3f318 100644 --- a/vector/src/main/java/im/vector/app/features/popup/PopupAlertManager.kt +++ b/vector/src/main/java/im/vector/app/features/popup/PopupAlertManager.kt @@ -90,7 +90,7 @@ class PopupAlertManager @Inject constructor( } /** - * Cancel all alerts, after a sign out for instance + * Cancel all alerts, after a sign out for instance. */ fun cancelAll() { synchronized(alertQueue) { diff --git a/vector/src/main/java/im/vector/app/features/popup/VectorAlert.kt b/vector/src/main/java/im/vector/app/features/popup/VectorAlert.kt index 8b855fa542..ffdba8e04d 100644 --- a/vector/src/main/java/im/vector/app/features/popup/VectorAlert.kt +++ b/vector/src/main/java/im/vector/app/features/popup/VectorAlert.kt @@ -46,7 +46,7 @@ interface VectorAlert { var contentAction: Runnable? var dismissedAction: Runnable? - /** If this timestamp is after current time, this alert will be skipped */ + /** If this timestamp is after current time, this alert will be skipped. */ var expirationTimestamp: Long? fun addButton(title: String, action: Runnable, autoClose: Boolean = true) { @@ -77,7 +77,7 @@ open class DefaultVectorAlert( override val description: String, @DrawableRes override val iconId: Int?, /** - * Alert are displayed by default, but let this lambda return false to prevent displaying + * Alert are displayed by default, but let this lambda return false to prevent displaying. */ override val shouldBeDisplayedIn: ((Activity) -> Boolean) = { true } ) : VectorAlert { @@ -90,7 +90,7 @@ open class DefaultVectorAlert( override var contentAction: Runnable? = null override var dismissedAction: Runnable? = null - /** If this timestamp is after current time, this alert will be skipped */ + /** If this timestamp is after current time, this alert will be skipped. */ override var expirationTimestamp: Long? = null @LayoutRes diff --git a/vector/src/main/java/im/vector/app/features/popup/VerificationVectorAlert.kt b/vector/src/main/java/im/vector/app/features/popup/VerificationVectorAlert.kt index 228c629161..d02d5dbfe8 100644 --- a/vector/src/main/java/im/vector/app/features/popup/VerificationVectorAlert.kt +++ b/vector/src/main/java/im/vector/app/features/popup/VerificationVectorAlert.kt @@ -30,7 +30,7 @@ class VerificationVectorAlert(uid: String, override val description: String, @DrawableRes override val iconId: Int?, /** - * Alert are displayed by default, but let this lambda return false to prevent displaying + * Alert are displayed by default, but let this lambda return false to prevent displaying. */ override val shouldBeDisplayedIn: ((Activity) -> Boolean) = { true } ) : DefaultVectorAlert(uid, title, description, iconId, shouldBeDisplayedIn) { diff --git a/vector/src/main/java/im/vector/app/features/qrcode/QrCodeScannerActivity.kt b/vector/src/main/java/im/vector/app/features/qrcode/QrCodeScannerActivity.kt index b23f2f171d..7af7db27cf 100644 --- a/vector/src/main/java/im/vector/app/features/qrcode/QrCodeScannerActivity.kt +++ b/vector/src/main/java/im/vector/app/features/qrcode/QrCodeScannerActivity.kt @@ -29,7 +29,7 @@ import im.vector.app.core.platform.VectorBaseActivity import im.vector.app.databinding.ActivitySimpleBinding @AndroidEntryPoint -class QrCodeScannerActivity() : VectorBaseActivity() { +class QrCodeScannerActivity : VectorBaseActivity() { override fun getBinding() = ActivitySimpleBinding.inflate(layoutInflater) diff --git a/vector/src/main/java/im/vector/app/features/rageshake/BugReportActivity.kt b/vector/src/main/java/im/vector/app/features/rageshake/BugReportActivity.kt index 350dd13b22..9dde7e071c 100755 --- a/vector/src/main/java/im/vector/app/features/rageshake/BugReportActivity.kt +++ b/vector/src/main/java/im/vector/app/features/rageshake/BugReportActivity.kt @@ -33,7 +33,7 @@ import org.matrix.android.sdk.api.extensions.tryOrNull import timber.log.Timber /** - * Form to send a bug report + * Form to send a bug report. */ @AndroidEntryPoint class BugReportActivity : VectorBaseActivity() { @@ -146,7 +146,7 @@ class BugReportActivity : VectorBaseActivity() { } /** - * Send the bug report + * Send the bug report. */ private fun sendBugReport() = withState(viewModel) { state -> views.bugReportScrollview.alpha = 0.3f diff --git a/vector/src/main/java/im/vector/app/features/rageshake/BugReporter.kt b/vector/src/main/java/im/vector/app/features/rageshake/BugReporter.kt index f723a281a0..b7ce7ffdb4 100755 --- a/vector/src/main/java/im/vector/app/features/rageshake/BugReporter.kt +++ b/vector/src/main/java/im/vector/app/features/rageshake/BugReporter.kt @@ -102,7 +102,7 @@ class BugReporter @Inject constructor( .adapter(Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java)) /** - * Get current Screenshot + * Get current Screenshot. * * @return screenshot or null if not available */ @@ -125,11 +125,11 @@ class BugReporter @Inject constructor( private val LOGCAT_CMD_DEBUG = arrayOf("logcat", "-d", "-v", "threadtime", "*:*") /** - * Bug report upload listener + * Bug report upload listener. */ interface IMXBugReportListener { /** - * The bug report has been cancelled + * The bug report has been cancelled. */ fun onUploadCancelled() @@ -141,7 +141,7 @@ class BugReporter @Inject constructor( fun onUploadFailed(reason: String?) /** - * The upload progress (in percent) + * The upload progress (in percent). * * @param progress the upload progress */ @@ -512,7 +512,7 @@ class BugReporter @Inject constructor( // ============================================================================================================== /** - * Provides the crash file + * Provides the crash file. * * @return the crash file */ @@ -521,7 +521,7 @@ class BugReporter @Inject constructor( } /** - * Remove the crash file + * Remove the crash file. */ fun deleteCrashFile() { val crashFile = getCrashFile() @@ -535,7 +535,7 @@ class BugReporter @Inject constructor( } /** - * Save the crash report + * Save the crash report. * * @param crashDescription teh crash description */ @@ -648,7 +648,7 @@ class BugReporter @Inject constructor( // ============================================================================================================== /** - * Save the logcat + * Save the logcat. * * @param isErrorLogcat true to save the error logcat * @return the file if the operation succeeds @@ -676,7 +676,7 @@ class BugReporter @Inject constructor( } /** - * Retrieves the logs + * Retrieves the logs. * * @param streamWriter the stream writer * @param isErrorLogCat true to save the error logs @@ -709,7 +709,7 @@ class BugReporter @Inject constructor( // ============================================================================================================== /** - * GZip a file + * GZip a file. * * @param fin the input file * @return the gzipped file diff --git a/vector/src/main/java/im/vector/app/features/rageshake/RageShake.kt b/vector/src/main/java/im/vector/app/features/rageshake/RageShake.kt index b5dd3f1ef0..ce738b85b9 100644 --- a/vector/src/main/java/im/vector/app/features/rageshake/RageShake.kt +++ b/vector/src/main/java/im/vector/app/features/rageshake/RageShake.kt @@ -105,7 +105,7 @@ class RageShake @Inject constructor(private val activity: FragmentActivity, companion object { /** - * Check if the feature is available + * Check if the feature is available. */ fun isAvailable(context: Context): Boolean { return context.getSystemService()?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null diff --git a/vector/src/main/java/im/vector/app/features/rageshake/VectorFileLogger.kt b/vector/src/main/java/im/vector/app/features/rageshake/VectorFileLogger.kt index 2f8e013f46..f16db4a66d 100644 --- a/vector/src/main/java/im/vector/app/features/rageshake/VectorFileLogger.kt +++ b/vector/src/main/java/im/vector/app/features/rageshake/VectorFileLogger.kt @@ -19,6 +19,7 @@ package im.vector.app.features.rageshake import android.content.Context import android.util.Log import im.vector.app.features.settings.VectorPreferences +import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch @@ -88,7 +89,7 @@ class VectorFileLogger @Inject constructor( } } - @Suppress("EXPERIMENTAL_API_USAGE") + @OptIn(DelicateCoroutinesApi::class) override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { fileHandler ?: return GlobalScope.launch(Dispatchers.IO) { @@ -128,7 +129,7 @@ class VectorFileLogger @Inject constructor( } /** - * Log an Throwable + * Log an Throwable. * * @param throwable the throwable to log */ diff --git a/vector/src/main/java/im/vector/app/features/rageshake/VectorUncaughtExceptionHandler.kt b/vector/src/main/java/im/vector/app/features/rageshake/VectorUncaughtExceptionHandler.kt index bd2f0b67bd..bc78b84088 100644 --- a/vector/src/main/java/im/vector/app/features/rageshake/VectorUncaughtExceptionHandler.kt +++ b/vector/src/main/java/im/vector/app/features/rageshake/VectorUncaughtExceptionHandler.kt @@ -47,7 +47,7 @@ class VectorUncaughtExceptionHandler @Inject constructor( private val preferences = DefaultSharedPreferences.getInstance(context) /** - * Activate this handler + * Activate this handler. */ fun activate() { previousHandler = Thread.getDefaultUncaughtExceptionHandler() @@ -55,12 +55,13 @@ class VectorUncaughtExceptionHandler @Inject constructor( } /** - * An uncaught exception has been triggered + * An uncaught exception has been triggered. * * @param thread the thread * @param throwable the throwable * @return the exception description */ + @Suppress("PrintStackTrace") override fun uncaughtException(thread: Thread, throwable: Throwable) { Timber.v("Uncaught exception: $throwable") preferences.edit(commit = true) { @@ -112,7 +113,7 @@ class VectorUncaughtExceptionHandler @Inject constructor( } /** - * Tells if the application crashed + * Tells if the application crashed. * * @return true if the application crashed */ @@ -121,7 +122,7 @@ class VectorUncaughtExceptionHandler @Inject constructor( } /** - * Clear the crash status + * Clear the crash status. */ fun clearAppCrashStatus() { preferences.edit { diff --git a/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnown.kt b/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnown.kt index 91b0f4d2f7..c451c35f20 100644 --- a/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnown.kt +++ b/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnown.kt @@ -22,7 +22,7 @@ import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class ElementWellKnown( /** - * Preferred Jitsi domain + * Preferred Jitsi domain. */ @Json(name = "im.vector.riot.jitsi") val jitsiServer: WellKnownPreferredConfig? = null, diff --git a/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnownExt.kt b/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnownExt.kt index 4dd5a68673..91269cb114 100644 --- a/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnownExt.kt +++ b/vector/src/main/java/im/vector/app/features/raw/wellknown/ElementWellKnownExt.kt @@ -16,14 +16,14 @@ package im.vector.app.features.raw.wellknown -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.auth.data.SessionParams import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.raw.RawService suspend fun RawService.getElementWellknown(sessionParams: SessionParams): ElementWellKnown? { // By default we use the domain of the userId to retrieve the .well-known data - val domain = sessionParams.userId.getDomain() + val domain = sessionParams.userId.getServerName() return tryOrNull { getWellknown(domain) } ?.let { ElementWellKnownMapper.from(it) } } diff --git a/vector/src/main/java/im/vector/app/features/reactions/EmojiReactionPickerActivity.kt b/vector/src/main/java/im/vector/app/features/reactions/EmojiReactionPickerActivity.kt index 7062a5d02d..f47b5b2411 100644 --- a/vector/src/main/java/im/vector/app/features/reactions/EmojiReactionPickerActivity.kt +++ b/vector/src/main/java/im/vector/app/features/reactions/EmojiReactionPickerActivity.kt @@ -44,8 +44,8 @@ import javax.inject.Inject /** * - * TODO: Loading indicator while getting emoji data source? - * TODO: Finish Refactor to vector base activity + * TODO Loading indicator while getting emoji data source? + * TODO Finish Refactor to vector base activity */ @AndroidEntryPoint class EmojiReactionPickerActivity : VectorBaseActivity(), diff --git a/vector/src/main/java/im/vector/app/features/reactions/EmojiRecyclerAdapter.kt b/vector/src/main/java/im/vector/app/features/reactions/EmojiRecyclerAdapter.kt index 5c0d2f36f5..8b04e9cfd6 100644 --- a/vector/src/main/java/im/vector/app/features/reactions/EmojiRecyclerAdapter.kt +++ b/vector/src/main/java/im/vector/app/features/reactions/EmojiRecyclerAdapter.kt @@ -39,11 +39,10 @@ import kotlinx.coroutines.launch import javax.inject.Inject import kotlin.math.abs -/** - * - * TODO: Configure Span using available width and emoji size - * TODO: Performances - * TODO: Scroll to section - Find a way to snap section to the top +/* + * TODO Configure Span using available width and emoji size + * TODO Performances + * TODO Scroll to section - Find a way to snap section to the top */ class EmojiRecyclerAdapter @Inject constructor() : RecyclerView.Adapter() { diff --git a/vector/src/main/java/im/vector/app/features/reactions/data/EmojiItem.kt b/vector/src/main/java/im/vector/app/features/reactions/data/EmojiItem.kt index 5a532c78f1..ed9aff4176 100644 --- a/vector/src/main/java/im/vector/app/features/reactions/data/EmojiItem.kt +++ b/vector/src/main/java/im/vector/app/features/reactions/data/EmojiItem.kt @@ -20,6 +20,7 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** + * Example: * name: 'a', * unified: 'b', * non_qualified: 'c', @@ -34,7 +35,7 @@ import com.squareup.moshi.JsonClass * emoticons: 'l', * text: 'm', * short_names: 'n', - * added_in: 'o' + * added_in: 'o'. */ @JsonClass(generateAdapter = true) data class EmojiItem( diff --git a/vector/src/main/java/im/vector/app/features/room/RequireActiveMembershipViewModel.kt b/vector/src/main/java/im/vector/app/features/room/RequireActiveMembershipViewModel.kt index 663bb1b372..0cd289cf64 100644 --- a/vector/src/main/java/im/vector/app/features/room/RequireActiveMembershipViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/room/RequireActiveMembershipViewModel.kt @@ -46,7 +46,7 @@ import org.matrix.android.sdk.flow.flow import org.matrix.android.sdk.flow.unwrap /** - * This ViewModel observe a room summary and notify when the room is left + * This ViewModel observe a room summary and notify when the room is left. */ class RequireActiveMembershipViewModel @AssistedInject constructor( @Assisted initialState: RequireActiveMembershipViewState, diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/JoinState.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/JoinState.kt index 12c264aa65..16c8491b2a 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/JoinState.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/JoinState.kt @@ -17,7 +17,7 @@ package im.vector.app.features.roomdirectory /** - * Join state of a room + * Join state of a room. */ enum class JoinState { NOT_JOINED, diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/PublicRoomsFragment.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/PublicRoomsFragment.kt index 4802e36c42..9562c3b504 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/PublicRoomsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/PublicRoomsFragment.kt @@ -48,7 +48,7 @@ import javax.inject.Inject /** * What can be improved: - * - When filtering more (when entering new chars), we could filter on result we already have, during the new server request, to avoid empty screen effect + * - When filtering more (when entering new chars), we could filter on result we already have, during the new server request, to avoid empty screen effect. */ class PublicRoomsFragment @Inject constructor( private val publicRoomsController: PublicRoomsController, diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryData.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryData.kt index ae87de2bdf..c54d10f682 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryData.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryData.kt @@ -21,28 +21,28 @@ package im.vector.app.features.roomdirectory */ data class RoomDirectoryData( /** - * The server name (might be null) + * The server name (might be null). * Set null when the server is the current user's homeserver. */ val homeServer: String? = null, /** - * The display name (the server description) + * The display name (the server description). */ val displayName: String = MATRIX_PROTOCOL_NAME, /** - * the avatar url + * The avatar url. */ val avatarUrl: String? = null, /** - * The third party server identifier + * The third party server identifier. */ val thirdPartyInstanceId: String? = null, /** - * Tell if all the federated servers must be included + * Tell if all the federated servers must be included. */ val includeAllNetworks: Boolean = false ) { diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryServer.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryServer.kt index 0f29ae5986..bea27df312 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryServer.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryServer.kt @@ -20,17 +20,17 @@ data class RoomDirectoryServer( val serverName: String, /** - * True if this is the current user server + * True if this is the current user server. */ val isUserServer: Boolean, /** - * True if manually added, so it can be removed by the user + * True if manually added, so it can be removed by the user. */ val isManuallyAdded: Boolean, /** - * Supported protocols + * Supported protocols. * TODO Rename RoomDirectoryData to RoomDirectoryProtocols */ val protocols: List diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectorySharedAction.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectorySharedAction.kt index ea9211cc7b..fb3b619392 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectorySharedAction.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectorySharedAction.kt @@ -19,7 +19,7 @@ package im.vector.app.features.roomdirectory import im.vector.app.core.platform.VectorSharedAction /** - * Supported navigation actions for [RoomDirectoryActivity] + * Supported navigation actions for [RoomDirectoryActivity]. */ sealed class RoomDirectorySharedAction : VectorSharedAction { object Back : RoomDirectorySharedAction() diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryViewEvents.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryViewEvents.kt index 60b1d11c4a..1805abc369 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/RoomDirectoryViewEvents.kt @@ -19,7 +19,7 @@ package im.vector.app.features.roomdirectory import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for room directory screen + * Transient events for room directory screen. */ sealed class RoomDirectoryViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : RoomDirectoryViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomActivity.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomActivity.kt index d5ea954b64..154c0bbb9d 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomActivity.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomActivity.kt @@ -33,7 +33,7 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach /** - * Simple container for [CreateRoomFragment] + * Simple container for [CreateRoomFragment]. */ @AndroidEntryPoint class CreateRoomActivity : VectorBaseActivity() { diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewEvents.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewEvents.kt index af745ce5ff..1964f9617e 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewEvents.kt @@ -19,7 +19,7 @@ package im.vector.app.features.roomdirectory.createroom import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for room creation screen + * Transient events for room creation screen. */ sealed class CreateRoomViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : CreateRoomViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewModel.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewModel.kt index caf17e09d6..f1306d9851 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewModel.kt @@ -35,7 +35,7 @@ import im.vector.app.features.raw.wellknown.getElementWellknown import im.vector.app.features.raw.wellknown.isE2EByDefault import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.raw.RawService @@ -98,7 +98,7 @@ class CreateRoomViewModel @AssistedInject constructor( private fun initHomeServerName() { setState { copy( - homeServerName = session.myUserId.getDomain() + homeServerName = session.myUserId.getServerName() ) } } @@ -297,7 +297,7 @@ class CreateRoomViewModel @AssistedInject constructor( } } - // TODO: Should this be non-cancellable? + // TODO Should this be non-cancellable? viewModelScope.launch { runCatching { session.roomService().createRoom(createRoomParams) }.fold( { roomId -> diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewState.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewState.kt index cf8cc669ab..2a6ee3727f 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewState.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/createroom/CreateRoomViewState.kt @@ -51,7 +51,7 @@ data class CreateRoomViewState( ) /** - * Return true if there is not important input from user + * Return true if there is not important input from user. */ fun isEmpty() = avatarUri == null && roomName.isEmpty() && diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/picker/RoomDirectoryListCreator.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/picker/RoomDirectoryListCreator.kt index 90283de77c..a168ea749c 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/picker/RoomDirectoryListCreator.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/picker/RoomDirectoryListCreator.kt @@ -20,7 +20,7 @@ import im.vector.app.R import im.vector.app.core.resources.StringArrayProvider import im.vector.app.features.roomdirectory.RoomDirectoryData import im.vector.app.features.roomdirectory.RoomDirectoryServer -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.room.model.thirdparty.ThirdPartyProtocol import javax.inject.Inject @@ -37,7 +37,7 @@ class RoomDirectoryListCreator @Inject constructor( val protocols = ArrayList() // Add user homeserver name - val userHsName = session.myUserId.getDomain() + val userHsName = session.myUserId.getServerName() // Add default protocol protocols.add( diff --git a/vector/src/main/java/im/vector/app/features/roomdirectory/roompreview/RoomPreviewNoPreviewFragment.kt b/vector/src/main/java/im/vector/app/features/roomdirectory/roompreview/RoomPreviewNoPreviewFragment.kt index 6eed1cae36..f197479692 100644 --- a/vector/src/main/java/im/vector/app/features/roomdirectory/roompreview/RoomPreviewNoPreviewFragment.kt +++ b/vector/src/main/java/im/vector/app/features/roomdirectory/roompreview/RoomPreviewNoPreviewFragment.kt @@ -50,7 +50,7 @@ import org.matrix.android.sdk.api.util.MatrixItem import javax.inject.Inject /** - * Note: this Fragment is also used for world readable room for the moment + * Note: this Fragment is also used for world readable room for the moment. */ class RoomPreviewNoPreviewFragment @Inject constructor( private val avatarRenderer: AvatarRenderer diff --git a/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileController.kt b/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileController.kt index 545e9f7190..adc720b0a5 100644 --- a/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileController.kt +++ b/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileController.kt @@ -182,6 +182,15 @@ class RoomMemberProfileController @Inject constructor( // More buildProfileSection(stringProvider.getString(R.string.room_profile_section_more)) + if (!state.isMine) { + buildProfileAction( + id = "direct", + editable = false, + title = stringProvider.getString(R.string.room_member_open_or_create_dm), + action = { callback?.onOpenDmClicked() } + ) + } + buildProfileAction( id = "overrideColor", editable = false, @@ -194,13 +203,6 @@ class RoomMemberProfileController @Inject constructor( if (!state.isMine) { val membership = state.asyncMembership() ?: return - buildProfileAction( - id = "direct", - editable = false, - title = stringProvider.getString(R.string.room_member_open_or_create_dm), - action = { callback?.onOpenDmClicked() } - ) - if (!state.isSpace && state.hasReadReceipt) { buildProfileAction( id = "read_receipt", diff --git a/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileViewEvents.kt b/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileViewEvents.kt index efe23eeff0..46983b52a4 100644 --- a/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileViewEvents.kt @@ -19,7 +19,7 @@ package im.vector.app.features.roommemberprofile import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for RoomMemberProfile + * Transient events for RoomMemberProfile. */ sealed class RoomMemberProfileViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : RoomMemberProfileViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/roommemberprofile/devices/DeviceListBottomSheetViewEvents.kt b/vector/src/main/java/im/vector/app/features/roommemberprofile/devices/DeviceListBottomSheetViewEvents.kt index 7a2990775d..8c6cba6cd9 100644 --- a/vector/src/main/java/im/vector/app/features/roommemberprofile/devices/DeviceListBottomSheetViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roommemberprofile/devices/DeviceListBottomSheetViewEvents.kt @@ -19,7 +19,7 @@ package im.vector.app.features.roommemberprofile.devices import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for device list screen + * Transient events for device list screen. */ sealed class DeviceListBottomSheetViewEvents : VectorViewEvents { data class Verify(val userId: String, val txID: String) : DeviceListBottomSheetViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileSharedAction.kt b/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileSharedAction.kt index eb4ab56634..7d62bb86a1 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileSharedAction.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileSharedAction.kt @@ -19,7 +19,7 @@ package im.vector.app.features.roomprofile import im.vector.app.core.platform.VectorSharedAction /** - * Supported navigation actions for [RoomProfileActivity] + * Supported navigation actions for [RoomProfileActivity]. */ sealed class RoomProfileSharedAction : VectorSharedAction { object OpenRoomSettings : RoomProfileSharedAction() diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileViewEvents.kt b/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileViewEvents.kt index 181115091c..f8ffed4af6 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileViewEvents.kt @@ -20,7 +20,7 @@ import androidx.core.content.pm.ShortcutInfoCompat import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for RoomProfile + * Transient events for RoomProfile. */ sealed class RoomProfileViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : RoomProfileViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewEvents.kt b/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewEvents.kt index bbd44741b5..725755a16b 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewEvents.kt @@ -20,7 +20,7 @@ package im.vector.app.features.roomprofile.alias import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for room settings screen + * Transient events for room settings screen. */ sealed class RoomAliasViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : RoomAliasViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewModel.kt b/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewModel.kt index 2641eb4184..a66ef9a659 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/alias/RoomAliasViewModel.kt @@ -31,7 +31,7 @@ import im.vector.app.features.powerlevel.PowerLevelsFlowFactory import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch -import org.matrix.android.sdk.api.MatrixPatterns.getDomain +import org.matrix.android.sdk.api.MatrixPatterns.getServerName import org.matrix.android.sdk.api.query.QueryStringValue import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.events.model.EventType @@ -96,7 +96,7 @@ class RoomAliasViewModel @AssistedInject constructor(@Assisted initialState: Roo private fun initHomeServerName() { setState { copy( - homeServerName = session.myUserId.getDomain() + homeServerName = session.myUserId.getServerName() ) } } diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheet.kt b/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheet.kt index 6e4613c03c..6d6d4564da 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheet.kt @@ -42,7 +42,7 @@ data class RoomAliasBottomSheetArgs( ) : Parcelable /** - * Bottom sheet fragment that shows room alias information with list of contextual actions + * Bottom sheet fragment that shows room alias information with list of contextual actions. */ @AndroidEntryPoint class RoomAliasBottomSheet : diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetController.kt b/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetController.kt index bfe6847fdf..13431d1ef7 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetController.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetController.kt @@ -22,7 +22,7 @@ import im.vector.app.core.ui.bottomsheet.bottomSheetTitleItem import javax.inject.Inject /** - * Epoxy controller for room alias actions + * Epoxy controller for room alias actions. */ class RoomAliasBottomSheetController @Inject constructor() : TypedEpoxyController() { diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetSharedActionViewModel.kt b/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetSharedActionViewModel.kt index 5f71783515..9371bd3d39 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetSharedActionViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/alias/detail/RoomAliasBottomSheetSharedActionViewModel.kt @@ -20,6 +20,6 @@ import im.vector.app.core.platform.VectorSharedActionViewModel import javax.inject.Inject /** - * Activity shared view model to handle room alias quick actions + * Activity shared view model to handle room alias quick actions. */ class RoomAliasBottomSheetSharedActionViewModel @Inject constructor() : VectorSharedActionViewModel() diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/permissions/RoomPermissionsViewEvents.kt b/vector/src/main/java/im/vector/app/features/roomprofile/permissions/RoomPermissionsViewEvents.kt index 8994398cf3..8994948e1d 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/permissions/RoomPermissionsViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/permissions/RoomPermissionsViewEvents.kt @@ -20,7 +20,7 @@ package im.vector.app.features.roomprofile.permissions import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for room settings screen + * Transient events for room settings screen. */ sealed class RoomPermissionsViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : RoomPermissionsViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/roomprofile/settings/RoomSettingsViewEvents.kt b/vector/src/main/java/im/vector/app/features/roomprofile/settings/RoomSettingsViewEvents.kt index 83a768fb34..af297d962f 100644 --- a/vector/src/main/java/im/vector/app/features/roomprofile/settings/RoomSettingsViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/roomprofile/settings/RoomSettingsViewEvents.kt @@ -20,7 +20,7 @@ package im.vector.app.features.roomprofile.settings import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for room settings screen + * Transient events for room settings screen. */ sealed class RoomSettingsViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : RoomSettingsViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/session/VectorSessionStore.kt b/vector/src/main/java/im/vector/app/features/session/VectorSessionStore.kt index 79183e1808..9466fc1459 100644 --- a/vector/src/main/java/im/vector/app/features/session/VectorSessionStore.kt +++ b/vector/src/main/java/im/vector/app/features/session/VectorSessionStore.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.api.util.md5 /** * User session scoped storage for: - * - messaging use case (Enum/String) + * - messaging use case (Enum/String). */ class VectorSessionStore constructor( context: Context, diff --git a/vector/src/main/java/im/vector/app/features/settings/BackgroundSyncMode.kt b/vector/src/main/java/im/vector/app/features/settings/BackgroundSyncMode.kt index 9d8b5755b0..1712b8cd27 100644 --- a/vector/src/main/java/im/vector/app/features/settings/BackgroundSyncMode.kt +++ b/vector/src/main/java/im/vector/app/features/settings/BackgroundSyncMode.kt @@ -17,7 +17,7 @@ package im.vector.app.features.settings /** - * Different strategies for Background sync, only applicable to F-Droid version of the app + * Different strategies for Background sync, only applicable to F-Droid version of the app. */ enum class BackgroundSyncMode { /** @@ -34,7 +34,7 @@ enum class BackgroundSyncMode { FDROID_BACKGROUND_SYNC_MODE_FOR_REALTIME, /** - * The app won't sync in background + * The app won't sync in background. */ FDROID_BACKGROUND_SYNC_MODE_DISABLED; diff --git a/vector/src/main/java/im/vector/app/features/settings/FontScale.kt b/vector/src/main/java/im/vector/app/features/settings/FontScale.kt index ad678ec49d..c4ea730afd 100644 --- a/vector/src/main/java/im/vector/app/features/settings/FontScale.kt +++ b/vector/src/main/java/im/vector/app/features/settings/FontScale.kt @@ -23,7 +23,7 @@ import im.vector.app.R import im.vector.app.core.di.DefaultSharedPreferences /** - * Object to manage the Font Scale choice of the user + * Object to manage the Font Scale choice of the user. */ object FontScale { // Key for the SharedPrefs @@ -51,7 +51,7 @@ object FontScale { private val normalFontScaleValue = fontScaleValues[2] /** - * Get the font scale value from SharedPrefs. Init the SharedPrefs if necessary + * Get the font scale value from SharedPrefs. Init the SharedPrefs if necessary. * * @return the font scale value */ @@ -76,7 +76,7 @@ object FontScale { } /** - * Store the font scale vale + * Store the font scale value. * * @param fontScaleValue the font scale value to store */ diff --git a/vector/src/main/java/im/vector/app/features/settings/VectorLocale.kt b/vector/src/main/java/im/vector/app/features/settings/VectorLocale.kt index 1c67b86493..3fb3d3f7c8 100644 --- a/vector/src/main/java/im/vector/app/features/settings/VectorLocale.kt +++ b/vector/src/main/java/im/vector/app/features/settings/VectorLocale.kt @@ -29,7 +29,7 @@ import java.util.IllformedLocaleException import java.util.Locale /** - * Object to manage the Locale choice of the user + * Object to manage the Locale choice of the user. */ object VectorLocale { private const val APPLICATION_LOCALE_COUNTRY_KEY = "APPLICATION_LOCALE_COUNTRY_KEY" @@ -42,12 +42,12 @@ object VectorLocale { private const val ISO_15924_LATN = "Latn" /** - * The cache of supported application languages + * The cache of supported application languages. */ private val supportedLocales = mutableListOf() /** - * Provides the current application locale + * Provides the current application locale. */ var applicationLocale = defaultLocale private set @@ -55,7 +55,7 @@ object VectorLocale { private lateinit var context: Context /** - * Init this object + * Init this object. */ fun init(context: Context) { this.context = context @@ -118,7 +118,7 @@ object VectorLocale { } /** - * Get String from a locale + * Get String from a locale. * * @param context the context * @param locale the locale @@ -138,7 +138,7 @@ object VectorLocale { } /** - * Init the supported application locales list + * Init the supported application locales list. */ private fun initApplicationLocales() { val knownLocalesSet = HashSet>() @@ -189,7 +189,7 @@ object VectorLocale { } /** - * Convert a locale to a string + * Convert a locale to a string. * * @param locale the locale to convert * @return the string @@ -212,7 +212,7 @@ object VectorLocale { } /** - * Information about the locale in the current locale + * Information about the locale in the current locale. * * @param locale the locale to get info from * @return the string diff --git a/vector/src/main/java/im/vector/app/features/settings/VectorPreferences.kt b/vector/src/main/java/im/vector/app/features/settings/VectorPreferences.kt index ca42a07d50..c841c6a0af 100755 --- a/vector/src/main/java/im/vector/app/features/settings/VectorPreferences.kt +++ b/vector/src/main/java/im/vector/app/features/settings/VectorPreferences.kt @@ -211,6 +211,9 @@ class VectorPreferences @Inject constructor( const val SETTINGS_LABS_ENABLE_THREAD_MESSAGES = "SETTINGS_LABS_ENABLE_THREAD_MESSAGES_FINAL" const val SETTINGS_THREAD_MESSAGES_SYNCED = "SETTINGS_THREAD_MESSAGES_SYNCED" + // This key will be used to enable user for displaying live user info or not. + const val SETTINGS_TIMELINE_SHOW_LIVE_SENDER_INFO = "SETTINGS_TIMELINE_SHOW_LIVE_SENDER_INFO" + // Possible values for TAKE_PHOTO_VIDEO_MODE const val TAKE_PHOTO_VIDEO_MODE_ALWAYS_ASK = 0 const val TAKE_PHOTO_VIDEO_MODE_PHOTO = 1 @@ -396,7 +399,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the timestamp must be displayed in 12h format + * Tells if the timestamp must be displayed in 12h format. * * @return true if the time must be displayed in 12h format */ @@ -441,14 +444,14 @@ class VectorPreferences @Inject constructor( } /** - * Show all rooms in room directory + * Show all rooms in room directory. */ fun showAllPublicRooms(): Boolean { return defaultPrefs.getBoolean(SETTINGS_ROOM_DIRECTORY_SHOW_ALL_PUBLIC_ROOMS, false) } /** - * Tells which compression level to use by default + * Tells which compression level to use by default. * * @return the selected compression level */ @@ -457,7 +460,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells which media source to use by default + * Tells which media source to use by default. * * @return the selected media source */ @@ -487,7 +490,7 @@ class VectorPreferences @Inject constructor( } /** - * Update the notification ringtone + * Update the notification ringtone. * * @param uri the new notification ringtone, or null for no RingTone */ @@ -511,7 +514,7 @@ class VectorPreferences @Inject constructor( } /** - * Provides the selected notification ring tone + * Provides the selected notification ring tone. * * @return the selected ring tone or null for no RingTone */ @@ -543,7 +546,7 @@ class VectorPreferences @Inject constructor( } /** - * Provide the notification ringtone filename + * Provide the notification ringtone filename. * * @return the filename or null if "None" is selected */ @@ -565,7 +568,7 @@ class VectorPreferences @Inject constructor( } /** - * Enable or disable the lazy loading + * Enable or disable the lazy loading. * * @param newValue true to enable lazy loading, false to disable it */ @@ -576,7 +579,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the lazy loading is enabled + * Tells if the lazy loading is enabled. * * @return true if the lazy loading of room members is enabled */ @@ -586,7 +589,6 @@ class VectorPreferences @Inject constructor( /** * User explicitly refuses the lazy loading. - * */ fun setUserRefuseLazyLoading() { defaultPrefs.edit { @@ -595,7 +597,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the user has explicitly refused the lazy loading + * Tells if the user has explicitly refused the lazy loading. * * @return true if the user has explicitly refuse the lazy loading of room members */ @@ -604,7 +606,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the data save mode is enabled + * Tells if the data save mode is enabled. * * @return true if the data save mode is enabled */ @@ -622,7 +624,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the application is started on boot + * Tells if the application is started on boot. * * @return true if the application must be started on boot */ @@ -631,7 +633,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the application is started on boot + * Tells if the application is started on boot. * * @param value true to start the application on boot */ @@ -692,14 +694,14 @@ class VectorPreferences @Inject constructor( } /** - * Fix some migration issues + * Fix some migration issues. */ fun fixMigrationIssues() { // Nothing to do for the moment } /** - * Tells if the markdown is enabled + * Tells if the markdown is enabled. * * @return true if the markdown is enabled */ @@ -719,14 +721,14 @@ class VectorPreferences @Inject constructor( } /** - * Tells if a confirmation dialog should be displayed before staring a call + * Tells if a confirmation dialog should be displayed before staring a call. */ fun preventAccidentalCall(): Boolean { return defaultPrefs.getBoolean(SETTINGS_CALL_PREVENT_ACCIDENTAL_CALL_KEY, false) } /** - * Tells if the read receipts should be shown + * Tells if the read receipts should be shown. * * @return true if the read receipts should be shown */ @@ -735,7 +737,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the redacted message should be shown + * Tells if the redacted message should be shown. * * @return true if the redacted should be shown */ @@ -744,7 +746,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the help on room list should be shown + * Tells if the help on room list should be shown. * * @return true if the help on room list should be shown */ @@ -753,7 +755,7 @@ class VectorPreferences @Inject constructor( } /** - * Prevent help on room list to be shown again + * Prevent help on room list to be shown again. */ fun neverShowLongClickOnRoomHelpAgain() { defaultPrefs.edit { @@ -762,7 +764,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the message timestamps must be always shown + * Tells if the message timestamps must be always shown. * * @return true if the message timestamps must be always shown */ @@ -771,7 +773,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the typing notifications should be sent + * Tells if the typing notifications should be sent. * * @return true to send the typing notifs */ @@ -780,7 +782,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells of the missing notifications rooms must be displayed at left (home screen) + * Tells of the missing notifications rooms must be displayed at left (home screen). * * @return true to move the missed notifications to the left side */ @@ -789,7 +791,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells of the unread rooms must be displayed at left (home screen) + * Tells of the unread rooms must be displayed at left (home screen). * * @return true to move the unread room to the left side */ @@ -798,7 +800,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the phone must vibrate when mentioning + * Tells if the phone must vibrate when mentioning. * * @return true */ @@ -826,7 +828,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if the user wants to see URL previews in the timeline + * Tells if the user wants to see URL previews in the timeline. * * @return true if the user wants to see URL previews in the timeline */ @@ -835,7 +837,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if media should be previewed before sending + * Tells if media should be previewed before sending. * * @return true to preview media */ @@ -844,7 +846,7 @@ class VectorPreferences @Inject constructor( } /** - * Tells if message should be send by pressing enter on the soft keyboard + * Tells if message should be send by pressing enter on the soft keyboard. * * @return true to send message with enter */ @@ -919,7 +921,7 @@ class VectorPreferences @Inject constructor( } /** - * The user does not allow screenshots of the application + * The user does not allow screenshots of the application. */ fun useFlagSecure(): Boolean { return defaultPrefs.getBoolean(SETTINGS_SECURITY_USE_FLAG_SECURE, false) @@ -946,7 +948,7 @@ class VectorPreferences @Inject constructor( } /** - * Return true if Pin code is disabled, or if user set the settings to see full notification content + * Return true if Pin code is disabled, or if user set the settings to see full notification content. */ fun useCompleteNotificationFormat(): Boolean { return !useFlagPinCode() || @@ -1040,14 +1042,14 @@ class VectorPreferences @Inject constructor( } /** - * Indicates whether or not thread messages are enabled + * Indicates whether or not thread messages are enabled. */ fun areThreadMessagesEnabled(): Boolean { return defaultPrefs.getBoolean(SETTINGS_LABS_ENABLE_THREAD_MESSAGES, getDefault(R.bool.settings_labs_thread_messages_default)) } /** - * Manually sets thread messages enabled, useful for migrating users from io.element.thread + * Manually sets thread messages enabled, useful for migrating users from io.element.thread. */ fun setThreadMessagesEnabled() { defaultPrefs @@ -1057,15 +1059,15 @@ class VectorPreferences @Inject constructor( } /** - * Indicates whether or not the user will be notified about the new thread support - * We should notify the user only if he had old thread support enabled + * Indicates whether or not the user will be notified about the new thread support. + * We should notify the user only if he had old thread support enabled. */ fun shouldNotifyUserAboutThreads(): Boolean { return defaultPrefs.getBoolean(SETTINGS_LABS_ENABLE_THREAD_MESSAGES_OLD_CLIENTS, false) } /** - * Indicates that the user have been notified about threads migration + * Indicates that the user have been notified about threads migration. */ fun userNotifiedAboutThreads() { defaultPrefs @@ -1083,7 +1085,7 @@ class VectorPreferences @Inject constructor( } /** - * Indicates that there no longer threads migration needed + * Indicates that there no longer threads migration needed. */ fun setShouldMigrateThreads(shouldMigrate: Boolean) { defaultPrefs @@ -1091,4 +1093,8 @@ class VectorPreferences @Inject constructor( .putBoolean(SETTINGS_THREAD_MESSAGES_SYNCED, shouldMigrate) .apply() } + + fun showLiveSenderInfo(): Boolean { + return defaultPrefs.getBoolean(SETTINGS_TIMELINE_SHOW_LIVE_SENDER_INFO, getDefault(R.bool.settings_timeline_show_live_sender_info_default)) + } } diff --git a/vector/src/main/java/im/vector/app/features/settings/VectorSettingsHelpAboutFragment.kt b/vector/src/main/java/im/vector/app/features/settings/VectorSettingsHelpAboutFragment.kt index 3a999f299f..5844467a1f 100644 --- a/vector/src/main/java/im/vector/app/features/settings/VectorSettingsHelpAboutFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/VectorSettingsHelpAboutFragment.kt @@ -20,6 +20,7 @@ import android.os.Bundle import androidx.preference.Preference import im.vector.app.BuildConfig import im.vector.app.R +import im.vector.app.core.extensions.orEmpty import im.vector.app.core.preference.VectorPreference import im.vector.app.core.utils.FirstThrottler import im.vector.app.core.utils.copyToClipboard @@ -72,7 +73,7 @@ class VectorSettingsHelpAboutFragment @Inject constructor( } it.setOnPreferenceClickListener { pref -> - copyToClipboard(requireContext(), pref.summary) + copyToClipboard(requireContext(), pref.summary.orEmpty()) true } } @@ -82,7 +83,7 @@ class VectorSettingsHelpAboutFragment @Inject constructor( it.summary = Matrix.getSdkVersion() it.setOnPreferenceClickListener { pref -> - copyToClipboard(requireContext(), pref.summary) + copyToClipboard(requireContext(), pref.summary.orEmpty()) true } } diff --git a/vector/src/main/java/im/vector/app/features/settings/VectorSettingsLabsFragment.kt b/vector/src/main/java/im/vector/app/features/settings/VectorSettingsLabsFragment.kt index e1e155865a..3b9fdc5e55 100644 --- a/vector/src/main/java/im/vector/app/features/settings/VectorSettingsLabsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/VectorSettingsLabsFragment.kt @@ -60,7 +60,7 @@ class VectorSettingsLabsFragment @Inject constructor( } /** - * Intercept the click to display a user friendly dialog when their homeserver do not support threads + * Intercept the click to display a user friendly dialog when their homeserver do not support threads. */ private fun onThreadsPreferenceClickedInterceptor(vectorSwitchPreference: VectorSwitchPreference) { val userEnabledThreads = vectorPreferences.areThreadMessagesEnabled() @@ -89,7 +89,7 @@ class VectorSettingsLabsFragment @Inject constructor( } /** - * Action when threads preference switch is actually clicked + * Action when threads preference switch is actually clicked. */ private fun onThreadsPreferenceClicked() { // We should migrate threads only if threads are disabled diff --git a/vector/src/main/java/im/vector/app/features/settings/VectorSettingsSecurityPrivacyFragment.kt b/vector/src/main/java/im/vector/app/features/settings/VectorSettingsSecurityPrivacyFragment.kt index bd4f556461..622f1f3f97 100644 --- a/vector/src/main/java/im/vector/app/features/settings/VectorSettingsSecurityPrivacyFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/VectorSettingsSecurityPrivacyFragment.kt @@ -151,7 +151,7 @@ class VectorSettingsSecurityPrivacyFragment @Inject constructor( findPreference("SETTINGS_USER_ANALYTICS_CONSENT_KEY")!! } - override fun onCreateRecyclerView(inflater: LayoutInflater?, parent: ViewGroup?, savedInstanceState: Bundle?): RecyclerView { + override fun onCreateRecyclerView(inflater: LayoutInflater, parent: ViewGroup, savedInstanceState: Bundle?): RecyclerView { return super.onCreateRecyclerView(inflater, parent, savedInstanceState).also { // Insert animation are really annoying the first time the list is shown // due to the way preference fragment is done, it's not trivial to disable it for first appearance only.. diff --git a/vector/src/main/java/im/vector/app/features/settings/account/deactivation/DeactivateAccountViewEvents.kt b/vector/src/main/java/im/vector/app/features/settings/account/deactivation/DeactivateAccountViewEvents.kt index 1b0ec2de0c..b715de3387 100644 --- a/vector/src/main/java/im/vector/app/features/settings/account/deactivation/DeactivateAccountViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/settings/account/deactivation/DeactivateAccountViewEvents.kt @@ -20,7 +20,7 @@ import im.vector.app.core.platform.VectorViewEvents import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse /** - * Transient events for deactivate account settings screen + * Transient events for deactivate account settings screen. */ sealed class DeactivateAccountViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : DeactivateAccountViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsFragment.kt b/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsFragment.kt index 6df92a0e5c..f5e87fc1a0 100644 --- a/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsFragment.kt @@ -37,7 +37,7 @@ import org.matrix.android.sdk.api.auth.data.LoginFlowTypes import javax.inject.Inject /** - * This Fragment is only used when user activates developer mode from the settings + * This Fragment is only used when user activates developer mode from the settings. */ class CrossSigningSettingsFragment @Inject constructor( private val controller: CrossSigningSettingsController, diff --git a/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsViewEvents.kt b/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsViewEvents.kt index 1c11560d40..8a9ba012fe 100644 --- a/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/settings/crosssigning/CrossSigningSettingsViewEvents.kt @@ -20,7 +20,7 @@ import im.vector.app.core.platform.VectorViewEvents import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse /** - * Transient events for cross signing settings screen + * Transient events for cross signing settings screen. */ sealed class CrossSigningSettingsViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : CrossSigningSettingsViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/settings/devices/DevicesViewEvents.kt b/vector/src/main/java/im/vector/app/features/settings/devices/DevicesViewEvents.kt index 8ba7dbc871..c057e2b565 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devices/DevicesViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devices/DevicesViewEvents.kt @@ -24,7 +24,7 @@ import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo /** - * Transient events for Ignored users screen + * Transient events for Ignored users screen. */ sealed class DevicesViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : DevicesViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/settings/devices/VectorSettingsDevicesFragment.kt b/vector/src/main/java/im/vector/app/features/settings/devices/VectorSettingsDevicesFragment.kt index 6e6556caaa..ed424e7267 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devices/VectorSettingsDevicesFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devices/VectorSettingsDevicesFragment.kt @@ -43,7 +43,7 @@ import org.matrix.android.sdk.api.session.crypto.model.DeviceInfo import javax.inject.Inject /** - * Display the list of the user's device + * Display the list of the user's device. */ class VectorSettingsDevicesFragment @Inject constructor( private val devicesController: DevicesController @@ -117,7 +117,7 @@ class VectorSettingsDevicesFragment @Inject constructor( } /** - * Display an alert dialog to rename a device + * Display an alert dialog to rename a device. * * @param deviceInfo device info */ @@ -159,7 +159,7 @@ class VectorSettingsDevicesFragment @Inject constructor( } /** - * Launch the re auth activity to get credentials + * Launch the re auth activity to get credentials. */ private fun askForReAuthentication(reAuthReq: DevicesViewEvents.RequestReAuth) { ReAuthActivity.newIntent( diff --git a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailFragment.kt b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailFragment.kt index 83740c5018..ec4ef26001 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailFragment.kt @@ -27,10 +27,8 @@ import im.vector.app.core.extensions.cleanup import im.vector.app.core.extensions.configureWith import im.vector.app.core.platform.VectorBaseFragment import im.vector.app.core.resources.ColorProvider -import im.vector.app.core.utils.createJSonViewerStyleProvider import im.vector.app.databinding.FragmentGenericRecyclerBinding -import org.billcarsonfr.jsonviewer.JSonViewerDialog -import org.matrix.android.sdk.api.session.events.model.Event +import org.matrix.android.sdk.api.session.crypto.model.AuditTrail import javax.inject.Inject class GossipingEventsPaperTrailFragment @Inject constructor( @@ -64,17 +62,17 @@ class GossipingEventsPaperTrailFragment @Inject constructor( super.onDestroyView() } - override fun didTap(event: Event) { - if (event.isEncrypted()) { - event.toClearContentStringWithIndent() - } else { - event.toContentStringWithIndent() - }?.let { - JSonViewerDialog.newInstance( - it, - -1, - createJSonViewerStyleProvider(colorProvider) - ).show(childFragmentManager, "JSON_VIEWER") - } + override fun didTap(event: AuditTrail) { +// if (event.isEncrypted()) { +// event.toClearContentStringWithIndent() +// } else { +// event.toContentStringWithIndent() +// }?.let { +// JSonViewerDialog.newInstance( +// it, +// -1, +// createJSonViewerStyleProvider(colorProvider) +// ).show(childFragmentManager, "JSON_VIEWER") +// } } } diff --git a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailViewModel.kt b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailViewModel.kt index 30c2757eff..e7f09b09e0 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsPaperTrailViewModel.kt @@ -32,10 +32,10 @@ import im.vector.app.core.platform.EmptyAction import im.vector.app.core.platform.EmptyViewEvents import im.vector.app.core.platform.VectorViewModel import org.matrix.android.sdk.api.session.Session -import org.matrix.android.sdk.api.session.events.model.Event +import org.matrix.android.sdk.api.session.crypto.model.AuditTrail data class GossipingEventsPaperTrailState( - val events: Async> = Uninitialized + val events: Async> = Uninitialized ) : MavericksState class GossipingEventsPaperTrailViewModel @AssistedInject constructor(@Assisted initialState: GossipingEventsPaperTrailState, diff --git a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsSerializer.kt b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsSerializer.kt index 30c2efc3ce..b8d82699e6 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsSerializer.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingEventsSerializer.kt @@ -17,62 +17,43 @@ package im.vector.app.features.settings.devtools import im.vector.app.core.resources.DateProvider -import me.gujun.android.span.span -import org.matrix.android.sdk.api.session.crypto.model.ForwardedRoomKeyContent -import org.matrix.android.sdk.api.session.crypto.model.GossipingToDeviceObject -import org.matrix.android.sdk.api.session.crypto.model.RoomKeyShareRequest -import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest -import org.matrix.android.sdk.api.session.events.model.Event -import org.matrix.android.sdk.api.session.events.model.EventType -import org.matrix.android.sdk.api.session.events.model.content.OlmEventContent -import org.matrix.android.sdk.api.session.events.model.content.SecretSendEventContent -import org.matrix.android.sdk.api.session.events.model.toModel +import org.matrix.android.sdk.api.session.crypto.model.AuditTrail +import org.matrix.android.sdk.api.session.crypto.model.ForwardInfo +import org.matrix.android.sdk.api.session.crypto.model.TrailType +import org.matrix.android.sdk.api.session.crypto.model.WithheldInfo import org.threeten.bp.format.DateTimeFormatter class GossipingEventsSerializer { private val full24DateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") - fun serialize(eventList: List): String { + fun serialize(eventList: List): String { return buildString { - eventList.forEach { - val clearType = it.getClearType() - append("[${getFormattedDate(it.ageLocalTs)}] $clearType from:${it.senderId} - ") - when (clearType) { - EventType.ROOM_KEY_REQUEST -> { - val content = it.getClearContent().toModel() - append("reqId:${content?.requestId} action:${content?.action} ") - if (content?.action == GossipingToDeviceObject.ACTION_SHARE_REQUEST) { - append("sessionId: ${content.body?.sessionId} ") - } - append("requestedBy: ${content?.requestingDeviceId}") + eventList.forEach { trail -> + val type = trail.type + val info = trail.info + append("[${getFormattedDate(trail.ageLocalTs)}] ${type.name} ") + append("sessionId: ${info.sessionId} ") + when (type) { + TrailType.IncomingKeyRequest -> { + append("from:${info.userId}|${info.deviceId} - ") } - EventType.FORWARDED_ROOM_KEY -> { - val encryptedContent = it.content.toModel() - val content = it.getClearContent().toModel() - - append("sessionId:${content?.sessionId} From Device (sender key):${encryptedContent?.senderKey}") - span("\nFrom Device (sender key):") { - textStyle = "bold" + TrailType.OutgoingKeyForward -> { + append("to:${info.userId}|${info.deviceId} - ") + (trail.info as? ForwardInfo)?.let { + append("chainIndex: ${it.chainIndex} ") } } - EventType.ROOM_KEY -> { - val content = it.getClearContent() - append("sessionId:${content?.get("session_id")} roomId:${content?.get("room_id")} dest:${content?.get("_dest") ?: "me"}") - } - EventType.SEND_SECRET -> { - val content = it.getClearContent().toModel() - append("requestId:${content?.requestId} From Device:${it.mxDecryptionResult?.payload?.get("sender_device")}") - } - EventType.REQUEST_SECRET -> { - val content = it.getClearContent().toModel() - append("reqId:${content?.requestId} action:${content?.action} ") - if (content?.action == GossipingToDeviceObject.ACTION_SHARE_REQUEST) { - append("secretName:${content.secretName} ") + TrailType.OutgoingKeyWithheld -> { + append("to:${info.userId}|${info.deviceId} - ") + (trail.info as? WithheldInfo)?.let { + append("code: ${it.code} ") } - append("requestedBy:${content?.requestingDeviceId}") } - EventType.ENCRYPTED -> { - append("Failed to Decrypt") + TrailType.IncomingKeyForward -> { + append("from:${info.userId}|${info.deviceId} - ") + (trail.info as? ForwardInfo)?.let { + append("chainIndex: ${it.chainIndex} ") + } } else -> { append("??") diff --git a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingTrailPagedEpoxyController.kt b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingTrailPagedEpoxyController.kt index dd016c2bf5..6a45968916 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingTrailPagedEpoxyController.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devtools/GossipingTrailPagedEpoxyController.kt @@ -18,7 +18,6 @@ package im.vector.app.features.settings.devtools import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.paging.PagedListEpoxyController -import im.vector.app.R import im.vector.app.core.date.DateFormatKind import im.vector.app.core.date.VectorDateFormatter import im.vector.app.core.resources.ColorProvider @@ -26,137 +25,75 @@ import im.vector.app.core.ui.list.GenericItem_ import im.vector.app.core.utils.createUIHandler import im.vector.lib.core.utils.epoxy.charsequence.toEpoxyCharSequence import me.gujun.android.span.span -import org.matrix.android.sdk.api.session.crypto.model.ForwardedRoomKeyContent -import org.matrix.android.sdk.api.session.crypto.model.GossipingToDeviceObject -import org.matrix.android.sdk.api.session.crypto.model.RoomKeyShareRequest -import org.matrix.android.sdk.api.session.crypto.model.SecretShareRequest -import org.matrix.android.sdk.api.session.events.model.Event -import org.matrix.android.sdk.api.session.events.model.EventType -import org.matrix.android.sdk.api.session.events.model.content.OlmEventContent -import org.matrix.android.sdk.api.session.events.model.content.SecretSendEventContent -import org.matrix.android.sdk.api.session.events.model.toModel +import org.matrix.android.sdk.api.session.crypto.model.AuditTrail +import org.matrix.android.sdk.api.session.crypto.model.ForwardInfo +import org.matrix.android.sdk.api.session.crypto.model.TrailType +import org.matrix.android.sdk.api.session.crypto.model.WithheldInfo import javax.inject.Inject class GossipingTrailPagedEpoxyController @Inject constructor( private val vectorDateFormatter: VectorDateFormatter, private val colorProvider: ColorProvider -) : PagedListEpoxyController( +) : PagedListEpoxyController( // Important it must match the PageList builder notify Looper modelBuildingHandler = createUIHandler() ) { interface InteractionListener { - fun didTap(event: Event) + fun didTap(event: AuditTrail) } var interactionListener: InteractionListener? = null - override fun buildItemModel(currentPosition: Int, item: Event?): EpoxyModel<*> { + override fun buildItemModel(currentPosition: Int, item: AuditTrail?): EpoxyModel<*> { val host = this val event = item ?: return GenericItem_().apply { id(currentPosition) } return GenericItem_().apply { id(event.hashCode()) itemClickAction { host.interactionListener?.didTap(event) } - title( - if (event.isEncrypted()) { - "${event.getClearType()} [encrypted]" - } else { - event.type - }?.toEpoxyCharSequence() - ) + title(event.type.name.toEpoxyCharSequence()) description( span { +host.vectorDateFormatter.format(event.ageLocalTs, DateFormatKind.DEFAULT_DATE_AND_TIME) - span("\nfrom: ") { + span("\n${host.senderFromTo(event.type)}: ") { textStyle = "bold" } - +"${event.senderId}" + +"${event.info.userId}|${event.info.deviceId}" + span("\nroomId: ") { + textStyle = "bold" + } + +event.info.roomId + span("\nsessionId: ") { + textStyle = "bold" + } + +event.info.sessionId apply { - if (event.getClearType() == EventType.ROOM_KEY_REQUEST) { - val content = event.getClearContent().toModel() - span("\nreqId:") { - textStyle = "bold" - } - +" ${content?.requestId}" - span("\naction:") { - textStyle = "bold" - } - +" ${content?.action}" - if (content?.action == GossipingToDeviceObject.ACTION_SHARE_REQUEST) { - span("\nsessionId:") { + when (event.type) { + TrailType.OutgoingKeyForward -> { + val fInfo = event.info as ForwardInfo + span("\nchainIndex: ") { textStyle = "bold" } - +" ${content.body?.sessionId}" + +"${fInfo.chainIndex}" } - span("\nrequestedBy: ") { - textStyle = "bold" - } - +"${content?.requestingDeviceId}" - } else if (event.getClearType() == EventType.FORWARDED_ROOM_KEY) { - val encryptedContent = event.content.toModel() - val content = event.getClearContent().toModel() - if (event.mxDecryptionResult == null) { - span("**Failed to Decrypt** ${event.mCryptoError}") { - textColor = host.colorProvider.getColorFromAttribute(R.attr.colorError) - } - } - span("\nsessionId:") { - textStyle = "bold" - } - +" ${content?.sessionId}" - span("\nFrom Device (sender key):") { - textStyle = "bold" - } - +" ${encryptedContent?.senderKey}" - } else if (event.getClearType() == EventType.ROOM_KEY) { - // it's a bit of a fake event for trail reasons - val content = event.getClearContent() - span("\nsessionId:") { - textStyle = "bold" - } - +" ${content?.get("session_id")}" - span("\nroomId:") { - textStyle = "bold" - } - +" ${content?.get("room_id")}" - span("\nTo :") { - textStyle = "bold" - } - +" ${content?.get("_dest") ?: "me"}" - } else if (event.getClearType() == EventType.SEND_SECRET) { - val content = event.getClearContent().toModel() - - span("\nrequestId:") { - textStyle = "bold" - } - +" ${content?.requestId}" - span("\nFrom Device:") { - textStyle = "bold" - } - +" ${event.mxDecryptionResult?.payload?.get("sender_device")}" - } else if (event.getClearType() == EventType.REQUEST_SECRET) { - val content = event.getClearContent().toModel() - span("\nreqId:") { - textStyle = "bold" - } - +" ${content?.requestId}" - span("\naction:") { - textStyle = "bold" - } - +" ${content?.action}" - if (content?.action == GossipingToDeviceObject.ACTION_SHARE_REQUEST) { - span("\nsecretName:") { + TrailType.OutgoingKeyWithheld -> { + val fInfo = event.info as WithheldInfo + span("\ncode: ") { textStyle = "bold" } - +" ${content.secretName}" + +"${fInfo.code}" } - span("\nrequestedBy: ") { - textStyle = "bold" + TrailType.IncomingKeyRequest -> { + // no additional info } - +"${content?.requestingDeviceId}" - } else if (event.getClearType() == EventType.ENCRYPTED) { - span("**Failed to Decrypt** ${event.mCryptoError}") { - textColor = host.colorProvider.getColorFromAttribute(R.attr.colorError) + TrailType.IncomingKeyForward -> { + val fInfo = event.info as ForwardInfo + span("\nchainIndex: ") { + textStyle = "bold" + } + +"${fInfo.chainIndex}" + } + TrailType.Unknown -> { } } } @@ -164,4 +101,14 @@ class GossipingTrailPagedEpoxyController @Inject constructor( ) } } + + private fun senderFromTo(type: TrailType): String { + return when (type) { + TrailType.OutgoingKeyWithheld, + TrailType.OutgoingKeyForward -> "to" + TrailType.IncomingKeyRequest, + TrailType.IncomingKeyForward -> "from" + TrailType.Unknown -> "" + } + } } diff --git a/vector/src/main/java/im/vector/app/features/settings/devtools/IncomingKeyRequestPagedController.kt b/vector/src/main/java/im/vector/app/features/settings/devtools/IncomingKeyRequestPagedController.kt index 4653f04f2c..09dd198bee 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devtools/IncomingKeyRequestPagedController.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devtools/IncomingKeyRequestPagedController.kt @@ -53,6 +53,7 @@ class IncomingKeyRequestPagedController @Inject constructor( textStyle = "bold" } span("${roomKeyRequest.userId}") + +"\n" +host.vectorDateFormatter.format(roomKeyRequest.localCreationTimestamp, DateFormatKind.DEFAULT_DATE_AND_TIME) span("\nsessionId:") { textStyle = "bold" @@ -62,10 +63,6 @@ class IncomingKeyRequestPagedController @Inject constructor( textStyle = "bold" } +"${roomKeyRequest.deviceId}" - span("\nstate: ") { - textStyle = "bold" - } - +roomKeyRequest.state.name }.toEpoxyCharSequence() ) } diff --git a/vector/src/main/java/im/vector/app/features/settings/devtools/KeyRequestListViewModel.kt b/vector/src/main/java/im/vector/app/features/settings/devtools/KeyRequestListViewModel.kt index a8045c07e3..e0a130a1e6 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devtools/KeyRequestListViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devtools/KeyRequestListViewModel.kt @@ -32,12 +32,12 @@ import im.vector.app.core.platform.EmptyViewEvents import im.vector.app.core.platform.VectorViewModel import kotlinx.coroutines.launch import org.matrix.android.sdk.api.session.Session +import org.matrix.android.sdk.api.session.crypto.OutgoingKeyRequest import org.matrix.android.sdk.api.session.crypto.model.IncomingRoomKeyRequest -import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest data class KeyRequestListViewState( val incomingRequests: Async> = Uninitialized, - val outgoingRoomKeyRequests: Async> = Uninitialized + val outgoingRoomKeyRequests: Async> = Uninitialized ) : MavericksState class KeyRequestListViewModel @AssistedInject constructor(@Assisted initialState: KeyRequestListViewState, diff --git a/vector/src/main/java/im/vector/app/features/settings/devtools/OutgoingKeyRequestPagedController.kt b/vector/src/main/java/im/vector/app/features/settings/devtools/OutgoingKeyRequestPagedController.kt index b23bd77277..13ba4a69ac 100644 --- a/vector/src/main/java/im/vector/app/features/settings/devtools/OutgoingKeyRequestPagedController.kt +++ b/vector/src/main/java/im/vector/app/features/settings/devtools/OutgoingKeyRequestPagedController.kt @@ -22,10 +22,10 @@ import im.vector.app.core.ui.list.GenericItem_ import im.vector.app.core.utils.createUIHandler import im.vector.lib.core.utils.epoxy.charsequence.toEpoxyCharSequence import me.gujun.android.span.span -import org.matrix.android.sdk.api.session.crypto.model.OutgoingRoomKeyRequest +import org.matrix.android.sdk.api.session.crypto.OutgoingKeyRequest import javax.inject.Inject -class OutgoingKeyRequestPagedController @Inject constructor() : PagedListEpoxyController( +class OutgoingKeyRequestPagedController @Inject constructor() : PagedListEpoxyController( // Important it must match the PageList builder notify Looper modelBuildingHandler = createUIHandler() ) { @@ -36,7 +36,7 @@ class OutgoingKeyRequestPagedController @Inject constructor() : PagedListEpoxyCo var interactionListener: InteractionListener? = null - override fun buildItemModel(currentPosition: Int, item: OutgoingRoomKeyRequest?): EpoxyModel<*> { + override fun buildItemModel(currentPosition: Int, item: OutgoingKeyRequest?): EpoxyModel<*> { val roomKeyRequest = item ?: return GenericItem_().apply { id(currentPosition) } return GenericItem_().apply { diff --git a/vector/src/main/java/im/vector/app/features/settings/homeserver/HomeserverSettingsFragment.kt b/vector/src/main/java/im/vector/app/features/settings/homeserver/HomeserverSettingsFragment.kt index 28bce90424..09fd848c99 100644 --- a/vector/src/main/java/im/vector/app/features/settings/homeserver/HomeserverSettingsFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/homeserver/HomeserverSettingsFragment.kt @@ -31,7 +31,7 @@ import im.vector.app.databinding.FragmentGenericRecyclerBinding import javax.inject.Inject /** - * Display some information about the homeserver + * Display some information about the homeserver. */ class HomeserverSettingsFragment @Inject constructor( private val homeserverSettingsController: HomeserverSettingsController diff --git a/vector/src/main/java/im/vector/app/features/settings/ignored/IgnoredUsersViewEvents.kt b/vector/src/main/java/im/vector/app/features/settings/ignored/IgnoredUsersViewEvents.kt index 8d597a9189..57f5004d88 100644 --- a/vector/src/main/java/im/vector/app/features/settings/ignored/IgnoredUsersViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/settings/ignored/IgnoredUsersViewEvents.kt @@ -20,7 +20,7 @@ package im.vector.app.features.settings.ignored import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for Ignored users screen + * Transient events for Ignored users screen. */ sealed class IgnoredUsersViewEvents : VectorViewEvents { data class Loading(val message: CharSequence? = null) : IgnoredUsersViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/settings/legals/ElementLegals.kt b/vector/src/main/java/im/vector/app/features/settings/legals/ElementLegals.kt index de59f36604..9f01dea4c1 100644 --- a/vector/src/main/java/im/vector/app/features/settings/legals/ElementLegals.kt +++ b/vector/src/main/java/im/vector/app/features/settings/legals/ElementLegals.kt @@ -26,7 +26,7 @@ class ElementLegals @Inject constructor( private val stringProvider: StringProvider ) { /** - * Use ServerPolicy model + * Use ServerPolicy model. */ fun getData(): List { return listOf( diff --git a/vector/src/main/java/im/vector/app/features/settings/locale/SystemLocaleProvider.kt b/vector/src/main/java/im/vector/app/features/settings/locale/SystemLocaleProvider.kt index 03d3b0623a..43d70ec8cf 100644 --- a/vector/src/main/java/im/vector/app/features/settings/locale/SystemLocaleProvider.kt +++ b/vector/src/main/java/im/vector/app/features/settings/locale/SystemLocaleProvider.kt @@ -26,7 +26,7 @@ class SystemLocaleProvider @Inject constructor( ) { /** - * Provides the device locale + * Provides the device locale. * * @return the device locale, or null in case of error */ diff --git a/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt b/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt index 1d76ed8500..b950ca4a32 100644 --- a/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt @@ -241,7 +241,7 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor( } /** - * Convert a delay in seconds to string + * Convert a delay in seconds to string. * * @param seconds the delay in seconds * @return the text @@ -352,8 +352,8 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor( super.onDetach() } - override fun onPreferenceTreeClick(preference: Preference?): Boolean { - return when (preference?.key) { + override fun onPreferenceTreeClick(preference: Preference): Boolean { + return when (preference.key) { VectorPreferences.SETTINGS_ENABLE_ALL_NOTIF_PREFERENCE_KEY -> { updateEnabledForAccount(preference) true diff --git a/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestAccountSettings.kt b/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestAccountSettings.kt index b6e78fa580..c567026eb1 100644 --- a/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestAccountSettings.kt +++ b/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestAccountSettings.kt @@ -30,7 +30,7 @@ import org.matrix.android.sdk.api.session.pushrules.RuleKind import javax.inject.Inject /** - * Check that the main pushRule (RULE_ID_DISABLE_ALL) is correctly setup + * Check that the main pushRule (RULE_ID_DISABLE_ALL) is correctly setup. */ class TestAccountSettings @Inject constructor(private val stringProvider: StringProvider, private val activeSessionHolder: ActiveSessionHolder) : diff --git a/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestNotification.kt b/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestNotification.kt index 1efe76205a..c2e5dc4997 100644 --- a/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestNotification.kt +++ b/vector/src/main/java/im/vector/app/features/settings/troubleshoot/TestNotification.kt @@ -25,7 +25,7 @@ import im.vector.app.features.notifications.NotificationUtils import javax.inject.Inject /** - * Checks if notifications can be displayed and clicked by the user + * Checks if notifications can be displayed and clicked by the user. */ class TestNotification @Inject constructor(private val context: Context, private val notificationUtils: NotificationUtils, diff --git a/vector/src/main/java/im/vector/app/features/share/IncomingShareFragment.kt b/vector/src/main/java/im/vector/app/features/share/IncomingShareFragment.kt index a6f05c8191..a8504142b5 100644 --- a/vector/src/main/java/im/vector/app/features/share/IncomingShareFragment.kt +++ b/vector/src/main/java/im/vector/app/features/share/IncomingShareFragment.kt @@ -47,8 +47,8 @@ import org.matrix.android.sdk.api.session.room.model.RoomSummary import javax.inject.Inject /** - * Display the list of rooms - * The user can select multiple rooms to send the data to + * Display the list of rooms. + * The user can select multiple rooms to send the data to. */ class IncomingShareFragment @Inject constructor( private val incomingShareController: IncomingShareController, diff --git a/vector/src/main/java/im/vector/app/features/signout/hard/SignedOutActivity.kt b/vector/src/main/java/im/vector/app/features/signout/hard/SignedOutActivity.kt index 87b8c33aa3..600eb0e992 100644 --- a/vector/src/main/java/im/vector/app/features/signout/hard/SignedOutActivity.kt +++ b/vector/src/main/java/im/vector/app/features/signout/hard/SignedOutActivity.kt @@ -28,7 +28,7 @@ import org.matrix.android.sdk.api.failure.GlobalError import timber.log.Timber /** - * In this screen, the user is viewing a message informing that he has been logged out + * In this screen, the user is viewing a message informing that he has been logged out. */ @AndroidEntryPoint class SignedOutActivity : VectorBaseActivity() { diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutActivity.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutActivity.kt index d0d5bea536..158a818053 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutActivity.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutActivity.kt @@ -36,8 +36,8 @@ import timber.log.Timber import javax.inject.Inject /** - * In this screen, the user is viewing a message informing that he has been logged out - * Extends LoginActivity to get the login with SSO and forget password functionality for (nearly) free + * In this screen, the user is viewing a message informing that he has been logged out. + * Extends LoginActivity to get the login with SSO and forget password functionality for (nearly) free. */ @AndroidEntryPoint class SoftLogoutActivity : LoginActivity() { diff --git a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewEvents.kt b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewEvents.kt index df4d556a48..adca250a3d 100644 --- a/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/signout/soft/SoftLogoutViewEvents.kt @@ -20,7 +20,7 @@ package im.vector.app.features.signout.soft import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for SoftLogout + * Transient events for SoftLogout. */ sealed class SoftLogoutViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : SoftLogoutViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/spaces/LeaveSpaceBottomSheet.kt b/vector/src/main/java/im/vector/app/features/spaces/LeaveSpaceBottomSheet.kt deleted file mode 100644 index a292b64ddd..0000000000 --- a/vector/src/main/java/im/vector/app/features/spaces/LeaveSpaceBottomSheet.kt +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2021 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package im.vector.app.features.spaces - -import android.app.Activity -import android.graphics.Typeface -import android.os.Bundle -import android.os.Parcelable -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.core.text.toSpannable -import androidx.core.view.isInvisible -import androidx.core.view.isVisible -import androidx.lifecycle.lifecycleScope -import com.airbnb.mvrx.Fail -import com.airbnb.mvrx.Loading -import com.airbnb.mvrx.args -import com.airbnb.mvrx.parentFragmentViewModel -import com.airbnb.mvrx.withState -import dagger.hilt.android.AndroidEntryPoint -import im.vector.app.R -import im.vector.app.core.error.ErrorFormatter -import im.vector.app.core.extensions.registerStartForActivityResult -import im.vector.app.core.extensions.setTextOrHide -import im.vector.app.core.platform.VectorBaseBottomSheetDialogFragment -import im.vector.app.core.resources.ColorProvider -import im.vector.app.core.utils.styleMatchingText -import im.vector.app.databinding.BottomSheetLeaveSpaceBinding -import im.vector.app.features.displayname.getBestName -import im.vector.app.features.spaces.leave.SpaceLeaveAdvancedActivity -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.onEach -import kotlinx.parcelize.Parcelize -import me.gujun.android.span.span -import org.matrix.android.sdk.api.util.toMatrixItem -import reactivecircus.flowbinding.android.widget.checkedChanges -import javax.inject.Inject - -@AndroidEntryPoint -class LeaveSpaceBottomSheet : VectorBaseBottomSheetDialogFragment() { - - val settingsViewModel: SpaceMenuViewModel by parentFragmentViewModel() - - override fun getBinding(inflater: LayoutInflater, container: ViewGroup?): BottomSheetLeaveSpaceBinding { - return BottomSheetLeaveSpaceBinding.inflate(inflater, container, false) - } - - @Inject lateinit var colorProvider: ColorProvider - @Inject lateinit var errorFormatter: ErrorFormatter - - @Parcelize - data class Args( - val spaceId: String - ) : Parcelable - - override val showExpanded = true - - private val spaceArgs: SpaceBottomSheetSettingsArgs by args() - - private val cherryPickLeaveActivityResult = registerStartForActivityResult { activityResult -> - if (activityResult.resultCode == Activity.RESULT_OK) { - // nothing actually? - } else { - // move back to default - settingsViewModel.handle(SpaceLeaveViewAction.SetAutoLeaveAll) - } - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - views.autoLeaveRadioGroup.checkedChanges() - .onEach { - when (it) { - views.leaveAll.id -> { - settingsViewModel.handle(SpaceLeaveViewAction.SetAutoLeaveAll) - } - views.leaveNone.id -> { - settingsViewModel.handle(SpaceLeaveViewAction.SetAutoLeaveNone) - } - views.leaveSelected.id -> { - settingsViewModel.handle(SpaceLeaveViewAction.SetAutoLeaveSelected) - // launch dedicated activity - cherryPickLeaveActivityResult.launch( - SpaceLeaveAdvancedActivity.newIntent(requireContext(), spaceArgs.spaceId) - ) - } - } - } - .launchIn(viewLifecycleOwner.lifecycleScope) - - views.leaveButton.debouncedClicks { - settingsViewModel.handle(SpaceLeaveViewAction.LeaveSpace) - } - - views.cancelButton.debouncedClicks { - dismiss() - } - } - - override fun invalidate() = withState(settingsViewModel) { state -> - super.invalidate() - - val spaceSummary = state.spaceSummary ?: return@withState - val bestName = spaceSummary.toMatrixItem().getBestName() - val commonText = getString(R.string.space_leave_prompt_msg_with_name, bestName) - .toSpannable().styleMatchingText(bestName, Typeface.BOLD) - - val warningMessage: CharSequence = if (spaceSummary.otherMemberIds.isEmpty()) { - span { - +commonText - +"\n\n" - span(getString(R.string.space_leave_prompt_msg_only_you)) { - textColor = colorProvider.getColorFromAttribute(R.attr.colorError) - } - } - } else if (state.isLastAdmin) { - span { - +commonText - +"\n\n" - span(getString(R.string.space_leave_prompt_msg_as_admin)) { - textColor = colorProvider.getColorFromAttribute(R.attr.colorError) - } - } - } else if (!spaceSummary.isPublic) { - span { - +commonText - +"\n\n" - span(getString(R.string.space_leave_prompt_msg_private)) { - textColor = colorProvider.getColorFromAttribute(R.attr.colorError) - } - } - } else { - commonText - } - - views.bottomLeaveSpaceWarningText.setTextOrHide(warningMessage) - - views.inlineErrorText.setTextOrHide(null) - if (state.leavingState is Loading) { - views.leaveButton.isInvisible = true - views.cancelButton.isInvisible = true - views.leaveProgress.isVisible = true - } else { - views.leaveButton.isInvisible = false - views.cancelButton.isInvisible = false - views.leaveProgress.isVisible = false - if (state.leavingState is Fail) { - views.inlineErrorText.setTextOrHide(errorFormatter.toHumanReadable(state.leavingState.error)) - } - } - - val hasChildren = (spaceSummary.spaceChildren?.size ?: 0) > 0 - if (hasChildren) { - views.autoLeaveRadioGroup.isVisible = true - when (state.leaveMode) { - SpaceMenuState.LeaveMode.LEAVE_ALL -> { - views.autoLeaveRadioGroup.check(views.leaveAll.id) - } - SpaceMenuState.LeaveMode.LEAVE_NONE -> { - views.autoLeaveRadioGroup.check(views.leaveNone.id) - } - SpaceMenuState.LeaveMode.LEAVE_SELECTED -> { - views.autoLeaveRadioGroup.check(views.leaveSelected.id) - } - } - } else { - views.autoLeaveRadioGroup.isVisible = false - } - } - - companion object { - - fun newInstance(spaceId: String): LeaveSpaceBottomSheet { - return LeaveSpaceBottomSheet().apply { - setArguments(SpaceBottomSheetSettingsArgs(spaceId)) - } - } - } -} diff --git a/vector/src/main/java/im/vector/app/features/spaces/SpaceListViewEvents.kt b/vector/src/main/java/im/vector/app/features/spaces/SpaceListViewEvents.kt index 582f6cd144..afc72b188d 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/SpaceListViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/SpaceListViewEvents.kt @@ -19,7 +19,7 @@ package im.vector.app.features.spaces import im.vector.app.core.platform.VectorViewEvents /** - * Transient events for group list screen + * Transient events for group list screen. */ sealed class SpaceListViewEvents : VectorViewEvents { data class OpenSpace(val groupingMethodHasChanged: Boolean) : SpaceListViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/spaces/SpaceSettingsMenuBottomSheet.kt b/vector/src/main/java/im/vector/app/features/spaces/SpaceSettingsMenuBottomSheet.kt index 78eab5b97f..94aa7e19b8 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/SpaceSettingsMenuBottomSheet.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/SpaceSettingsMenuBottomSheet.kt @@ -35,6 +35,7 @@ import im.vector.app.features.home.AvatarRenderer import im.vector.app.features.navigation.Navigator import im.vector.app.features.rageshake.BugReporter import im.vector.app.features.roomprofile.RoomProfileActivity +import im.vector.app.features.spaces.leave.SpaceLeaveAdvancedActivity import im.vector.app.features.spaces.manage.ManageType import im.vector.app.features.spaces.manage.SpaceManageActivity import kotlinx.parcelize.Parcelize @@ -109,7 +110,7 @@ class SpaceSettingsMenuBottomSheet : VectorBaseBottomSheetDialogFragment() { interface InteractionListener { + fun onFilterQueryChanged(query: String?) fun onButtonClick(spaceChildInfo: SpaceChildInfo) fun onSpaceChildClick(spaceChildInfo: SpaceChildInfo) fun onRoomClick(spaceChildInfo: SpaceChildInfo) @@ -62,6 +65,7 @@ class SpaceDirectoryController @Inject constructor( } var listener: InteractionListener? = null + private val matchFilter = SpaceChildInfoMatchFilter() override fun buildModels(data: SpaceDirectoryState?) { val host = this @@ -76,7 +80,7 @@ class SpaceDirectoryController @Inject constructor( val failure = results.error if (failure is Failure.ServerError && failure.error.code == M_UNRECOGNIZED) { genericPillItem { - id("HS no Support") + id("hs_no_support") imageRes(R.drawable.error) tintIcon(false) text( @@ -132,43 +136,52 @@ class SpaceDirectoryController @Inject constructor( } } } else { - flattenChildInfo.forEach { info -> - val isSpace = info.roomType == RoomType.SPACE - val isJoined = data?.joinedRoomsIds?.contains(info.childRoomId) == true - val isLoading = data?.changeMembershipStates?.get(info.childRoomId)?.isInProgress() ?: false - val error = (data?.changeMembershipStates?.get(info.childRoomId) as? ChangeMembershipState.FailedJoining)?.throwable - // if it's known use that matrixItem because it would have a better computed name - val matrixItem = data?.knownRoomSummaries?.find { it.roomId == info.childRoomId }?.toMatrixItem() - ?: info.toMatrixItem() + matchFilter.filter = data?.currentFilter ?: "" + val filteredChildInfo = flattenChildInfo.filter { matchFilter.test(it) } - spaceChildInfoItem { - id(info.childRoomId) - matrixItem(matrixItem) - avatarRenderer(host.avatarRenderer) - topic(info.topic) - suggested(info.suggested.orFalse()) - errorLabel( - error?.let { - host.stringProvider.getString(R.string.error_failed_to_join_room, host.errorFormatter.toHumanReadable(it)) + if (filteredChildInfo.isEmpty()) { + spaceDirectoryFilterNoResults { + id("no_results") + } + } else { + filteredChildInfo.forEach { info -> + val isSpace = info.roomType == RoomType.SPACE + val isJoined = data?.joinedRoomsIds?.contains(info.childRoomId) == true + val isLoading = data?.changeMembershipStates?.get(info.childRoomId)?.isInProgress() ?: false + val error = (data?.changeMembershipStates?.get(info.childRoomId) as? ChangeMembershipState.FailedJoining)?.throwable + // if it's known use that matrixItem because it would have a better computed name + val matrixItem = data?.knownRoomSummaries?.find { it.roomId == info.childRoomId }?.toMatrixItem() + ?: info.toMatrixItem() + + spaceChildInfoItem { + id(info.childRoomId) + matrixItem(matrixItem) + avatarRenderer(host.avatarRenderer) + topic(info.topic) + suggested(info.suggested.orFalse()) + errorLabel( + error?.let { + host.stringProvider.getString(R.string.error_failed_to_join_room, host.errorFormatter.toHumanReadable(it)) + } + ) + memberCount(info.activeMemberCount ?: 0) + loading(isLoading) + buttonLabel( + when { + error != null -> host.stringProvider.getString(R.string.global_retry) + isJoined -> host.stringProvider.getString(R.string.action_open) + else -> host.stringProvider.getString(R.string.action_join) + } + ) + apply { + if (isSpace) { + itemClickListener { host.listener?.onSpaceChildClick(info) } + } else { + itemClickListener { host.listener?.onRoomClick(info) } } - ) - memberCount(info.activeMemberCount ?: 0) - loading(isLoading) - buttonLabel( - when { - error != null -> host.stringProvider.getString(R.string.global_retry) - isJoined -> host.stringProvider.getString(R.string.action_open) - else -> host.stringProvider.getString(R.string.action_join) - } - ) - apply { - if (isSpace) { - itemClickListener { host.listener?.onSpaceChildClick(info) } - } else { - itemClickListener { host.listener?.onRoomClick(info) } } + buttonClickListener { host.listener?.onButtonClick(info) } } - buttonClickListener { host.listener?.onButtonClick(info) } } } } diff --git a/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryFragment.kt b/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryFragment.kt index e59087778f..ed0bbdd911 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryFragment.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryFragment.kt @@ -23,6 +23,7 @@ import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup +import androidx.appcompat.widget.SearchView import androidx.core.text.toSpannable import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope @@ -44,7 +45,6 @@ import im.vector.app.core.utils.openUrlInExternalBrowser import im.vector.app.databinding.FragmentSpaceDirectoryBinding import im.vector.app.features.analytics.plan.MobileScreen import im.vector.app.features.home.room.detail.timeline.TimelineEventController -import im.vector.app.features.matrixto.SpaceCardRenderer import im.vector.app.features.permalink.PermalinkHandler import im.vector.app.features.spaces.manage.ManageType import im.vector.app.features.spaces.manage.SpaceAddRoomSpaceChooserBottomSheet @@ -63,7 +63,6 @@ data class SpaceDirectoryArgs( class SpaceDirectoryFragment @Inject constructor( private val epoxyController: SpaceDirectoryController, private val permalinkHandler: PermalinkHandler, - private val spaceCardRenderer: SpaceCardRenderer, private val colorProvider: ColorProvider ) : VectorBaseFragment(), SpaceDirectoryController.InteractionListener, @@ -123,9 +122,6 @@ class SpaceDirectoryFragment @Inject constructor( } } - views.spaceCard.matrixToCardMainButton.isVisible = false - views.spaceCard.matrixToCardSecondaryButton.isVisible = false - // Hide FAB when list is scrolling views.spaceDirectoryList.addOnScrollListener( object : RecyclerView.OnScrollListener() { @@ -167,18 +163,37 @@ class SpaceDirectoryFragment @Inject constructor( // it's the root toolbar?.setTitle(R.string.space_explore_activity_title) } else { - toolbar?.title = state.currentRootSummary?.name + val spaceName = state.currentRootSummary?.name ?: state.currentRootSummary?.canonicalAlias - ?: getString(R.string.space_explore_activity_title) + + if (spaceName != null) { + toolbar?.title = spaceName + toolbar?.subtitle = getString(R.string.space_explore_activity_title) + } else { + toolbar?.title = getString(R.string.space_explore_activity_title) + } } - spaceCardRenderer.render(state.currentRootSummary, emptyList(), this, views.spaceCard, showDescription = false) views.addOrCreateChatRoomButton.isVisible = state.canAddRooms } override fun onPrepareOptionsMenu(menu: Menu) = withState(viewModel) { state -> menu.findItem(R.id.spaceAddRoom)?.isVisible = state.canAddRooms menu.findItem(R.id.spaceCreateRoom)?.isVisible = false // Not yet implemented + + menu.findItem(R.id.spaceSearch)?.let { searchItem -> + val searchView = searchItem.actionView as SearchView + searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { + override fun onQueryTextSubmit(query: String?): Boolean { + return true + } + + override fun onQueryTextChange(newText: String?): Boolean { + onFilterQueryChanged(newText) + return true + } + }) + } super.onPrepareOptionsMenu(menu) } @@ -198,6 +213,10 @@ class SpaceDirectoryFragment @Inject constructor( return super.onOptionsItemSelected(item) } + override fun onFilterQueryChanged(query: String?) { + viewModel.handle(SpaceDirectoryViewAction.FilterRooms(query)) + } + override fun onButtonClick(spaceChildInfo: SpaceChildInfo) { viewModel.handle(SpaceDirectoryViewAction.JoinOrOpen(spaceChildInfo)) } diff --git a/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewAction.kt b/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewAction.kt index 2166a7e306..1d180eea4f 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewAction.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewAction.kt @@ -22,6 +22,7 @@ import org.matrix.android.sdk.api.session.room.model.SpaceChildInfo sealed class SpaceDirectoryViewAction : VectorViewModelAction { data class ExploreSubSpace(val spaceChildInfo: SpaceChildInfo) : SpaceDirectoryViewAction() data class JoinOrOpen(val spaceChildInfo: SpaceChildInfo) : SpaceDirectoryViewAction() + data class FilterRooms(val query: String?) : SpaceDirectoryViewAction() data class ShowDetails(val spaceChildInfo: SpaceChildInfo) : SpaceDirectoryViewAction() data class NavigateToRoom(val roomId: String) : SpaceDirectoryViewAction() object CreateNewRoom : SpaceDirectoryViewAction() diff --git a/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewModel.kt b/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewModel.kt index 2ddcb42e2a..7ae2feebcf 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/explore/SpaceDirectoryViewModel.kt @@ -225,9 +225,16 @@ class SpaceDirectoryViewModel @AssistedInject constructor( _viewEvents.post(SpaceDirectoryViewEvents.NavigateToCreateNewRoom(state.currentRootSummary?.roomId ?: initialState.spaceId)) } } + is SpaceDirectoryViewAction.FilterRooms -> { + filter(action.query) + } } } + private fun filter(query: String?) { + setState { copy(currentFilter = query.orEmpty()) } + } + private fun handleBack() = withState { state -> if (state.hierarchyStack.isEmpty()) { _viewEvents.post(SpaceDirectoryViewEvents.Dismiss) diff --git a/vector/src/main/java/im/vector/app/features/spaces/invite/SpaceInviteBottomSheetViewModel.kt b/vector/src/main/java/im/vector/app/features/spaces/invite/SpaceInviteBottomSheetViewModel.kt index 93bf51368b..5e56373a88 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/invite/SpaceInviteBottomSheetViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/invite/SpaceInviteBottomSheetViewModel.kt @@ -68,7 +68,7 @@ class SpaceInviteBottomSheetViewModel @AssistedInject constructor( } /** - * Try to request the room summary api to get more info + * Try to request the room summary api to get more info. */ private fun getLatestRoomSummary(roomSummary: RoomSummary) { viewModelScope.launch(Dispatchers.IO) { diff --git a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewAction.kt b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewAction.kt index 68b313ec7f..a25476bff9 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewAction.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewAction.kt @@ -21,6 +21,9 @@ import im.vector.app.core.platform.VectorViewModelAction sealed class SpaceLeaveAdvanceViewAction : VectorViewModelAction { data class ToggleSelection(val roomId: String) : SpaceLeaveAdvanceViewAction() data class UpdateFilter(val filter: String) : SpaceLeaveAdvanceViewAction() + data class SetFilteringEnabled(val isEnabled: Boolean) : SpaceLeaveAdvanceViewAction() object DoLeave : SpaceLeaveAdvanceViewAction() object ClearError : SpaceLeaveAdvanceViewAction() + object SelectAll : SpaceLeaveAdvanceViewAction() + object SelectNone : SpaceLeaveAdvanceViewAction() } diff --git a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewState.kt b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewState.kt index b8dcd3f7a2..fce5f4efa1 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewState.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvanceViewState.kt @@ -28,8 +28,11 @@ data class SpaceLeaveAdvanceViewState( val allChildren: Async> = Uninitialized, val selectedRooms: List = emptyList(), val currentFilter: String = "", - val leaveState: Async = Uninitialized + val leaveState: Async = Uninitialized, + val isFilteringEnabled: Boolean = false, + val isLastAdmin: Boolean = false ) : MavericksState { + constructor(args: SpaceBottomSheetSettingsArgs) : this( spaceId = args.spaceId ) diff --git a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedFragment.kt b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedFragment.kt index 53c7481acb..308572a30f 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedFragment.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedFragment.kt @@ -18,20 +18,23 @@ package im.vector.app.features.spaces.leave import android.os.Bundle import android.view.LayoutInflater +import android.view.Menu +import android.view.MenuItem import android.view.View import android.view.ViewGroup -import androidx.lifecycle.lifecycleScope +import androidx.appcompat.widget.SearchView +import androidx.coordinatorlayout.widget.CoordinatorLayout +import androidx.core.view.isVisible +import com.airbnb.mvrx.Success import com.airbnb.mvrx.activityViewModel import com.airbnb.mvrx.withState +import im.vector.app.R import im.vector.app.core.extensions.cleanup import im.vector.app.core.extensions.configureWith import im.vector.app.core.platform.VectorBaseFragment +import im.vector.app.core.utils.ToggleableAppBarLayoutBehavior import im.vector.app.databinding.FragmentSpaceLeaveAdvancedBinding -import kotlinx.coroutines.flow.debounce -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.onEach import org.matrix.android.sdk.api.session.room.model.RoomSummary -import reactivecircus.flowbinding.appcompat.queryTextChanges import javax.inject.Inject class SpaceLeaveAdvancedFragment @Inject constructor( @@ -44,11 +47,33 @@ class SpaceLeaveAdvancedFragment @Inject constructor( val viewModel: SpaceLeaveAdvancedViewModel by activityViewModel() + override fun getMenuRes() = R.menu.menu_space_leave + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - setupToolbar(views.toolbar) - .allowBack() + controller.listener = this + + withState(viewModel) { state -> + setupToolbar(views.toolbar) + .setSubtitle(state.spaceSummary?.name) + .allowBack() + + state.spaceSummary?.let { summary -> + val warningMessage: CharSequence? = when { + summary.otherMemberIds.isEmpty() -> getString(R.string.space_leave_prompt_msg_only_you) + state.isLastAdmin -> getString(R.string.space_leave_prompt_msg_as_admin) + !summary.isPublic -> getString(R.string.space_leave_prompt_msg_private) + else -> null + } + + views.spaceLeavePromptDescription.isVisible = warningMessage != null + views.spaceLeavePromptDescription.text = warningMessage + } + + views.spaceLeavePromptTitle.text = getString(R.string.space_leave_prompt_msg_with_name, state.spaceSummary?.name ?: "") + } + views.roomList.configureWith(controller) views.spaceLeaveCancel.debouncedClicks { requireActivity().finish() } @@ -56,12 +81,23 @@ class SpaceLeaveAdvancedFragment @Inject constructor( viewModel.handle(SpaceLeaveAdvanceViewAction.DoLeave) } - views.publicRoomsFilter.queryTextChanges() - .debounce(100) - .onEach { - viewModel.handle(SpaceLeaveAdvanceViewAction.UpdateFilter(it.toString())) - } - .launchIn(viewLifecycleOwner.lifecycleScope) + views.spaceLeaveSelectGroup.setOnCheckedChangeListener { _, optionId -> + when (optionId) { + R.id.spaceLeaveSelectAll -> viewModel.handle(SpaceLeaveAdvanceViewAction.SelectAll) + R.id.spaceLeaveSelectNone -> viewModel.handle(SpaceLeaveAdvanceViewAction.SelectNone) + } + } + } + + override fun onPrepareOptionsMenu(menu: Menu) { + menu.findItem(R.id.menu_space_leave_search)?.let { searchItem -> + searchItem.bind( + onExpanded = { viewModel.handle(SpaceLeaveAdvanceViewAction.SetFilteringEnabled(isEnabled = true)) }, + onCollapsed = { viewModel.handle(SpaceLeaveAdvanceViewAction.SetFilteringEnabled(isEnabled = false)) }, + onTextChanged = { viewModel.handle(SpaceLeaveAdvanceViewAction.UpdateFilter(it)) } + ) + } + super.onPrepareOptionsMenu(menu) } override fun onDestroyView() { @@ -72,10 +108,63 @@ class SpaceLeaveAdvancedFragment @Inject constructor( override fun invalidate() = withState(viewModel) { state -> super.invalidate() + + if (state.isFilteringEnabled) { + views.appBarLayout.setExpanded(false) + } + + updateAppBarBehaviorState(state) + updateRadioButtonsState(state) + controller.setData(state) } override fun onItemSelected(roomSummary: RoomSummary) { viewModel.handle(SpaceLeaveAdvanceViewAction.ToggleSelection(roomSummary.roomId)) } + + private fun updateAppBarBehaviorState(state: SpaceLeaveAdvanceViewState) { + val behavior = (views.appBarLayout.layoutParams as CoordinatorLayout.LayoutParams).behavior as ToggleableAppBarLayoutBehavior + behavior.isEnabled = !state.isFilteringEnabled + } + + private fun updateRadioButtonsState(state: SpaceLeaveAdvanceViewState) { + (state.allChildren as? Success)?.invoke()?.size?.let { allChildrenCount -> + when (state.selectedRooms.size) { + 0 -> views.spaceLeaveSelectNone.isChecked = true + allChildrenCount -> views.spaceLeaveSelectAll.isChecked = true + else -> views.spaceLeaveSelectSemi.isChecked = true + } + } + } + + private fun MenuItem.bind( + onExpanded: () -> Unit, + onCollapsed: () -> Unit, + onTextChanged: (String) -> Unit) { + setOnActionExpandListener(object : MenuItem.OnActionExpandListener { + override fun onMenuItemActionExpand(item: MenuItem?): Boolean { + onExpanded() + return true + } + + override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { + onCollapsed() + return true + } + }) + + val searchView = actionView as SearchView + + searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { + override fun onQueryTextSubmit(query: String?): Boolean { + return false + } + + override fun onQueryTextChange(newText: String?): Boolean { + onTextChanged(newText ?: "") + return true + } + }) + } } diff --git a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedViewModel.kt b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedViewModel.kt index 3f5a27f696..2ab417ac55 100644 --- a/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/spaces/leave/SpaceLeaveAdvancedViewModel.kt @@ -36,9 +36,14 @@ import okhttp3.internal.toImmutableList import org.matrix.android.sdk.api.query.ActiveSpaceFilter import org.matrix.android.sdk.api.query.RoomCategoryFilter import org.matrix.android.sdk.api.session.Session +import org.matrix.android.sdk.api.session.events.model.EventType +import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom -import org.matrix.android.sdk.api.session.getRoomSummary +import org.matrix.android.sdk.api.session.room.getStateEvent import org.matrix.android.sdk.api.session.room.model.Membership +import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent +import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper +import org.matrix.android.sdk.api.session.room.powerlevels.Role import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams import org.matrix.android.sdk.flow.flow import org.matrix.android.sdk.flow.unwrap @@ -50,52 +55,24 @@ class SpaceLeaveAdvancedViewModel @AssistedInject constructor( private val appStateHandler: AppStateHandler ) : VectorViewModel(initialState) { - override fun handle(action: SpaceLeaveAdvanceViewAction) = withState { state -> - when (action) { - is SpaceLeaveAdvanceViewAction.ToggleSelection -> { - val existing = state.selectedRooms.toMutableList() - if (existing.contains(action.roomId)) { - existing.remove(action.roomId) - } else { - existing.add(action.roomId) - } - setState { - copy( - selectedRooms = existing.toImmutableList() - ) - } - } - is SpaceLeaveAdvanceViewAction.UpdateFilter -> { - setState { copy(currentFilter = action.filter) } - } - SpaceLeaveAdvanceViewAction.DoLeave -> { - setState { copy(leaveState = Loading()) } - viewModelScope.launch { - try { - state.selectedRooms.forEach { - try { - session.roomService().leaveRoom(it) - } catch (failure: Throwable) { - // silently ignore? - Timber.e(failure, "Fail to leave sub rooms/spaces") - } - } + init { + val space = session.getRoom(initialState.spaceId) + val spaceSummary = space?.roomSummary() - session.spaceService().leaveSpace(initialState.spaceId) - // We observe the membership and to dismiss when we have remote echo of leaving - } catch (failure: Throwable) { - setState { copy(leaveState = Fail(failure)) } - } - } - } - SpaceLeaveAdvanceViewAction.ClearError -> { - setState { copy(leaveState = Uninitialized) } + val powerLevelsEvent = space?.getStateEvent(EventType.STATE_ROOM_POWER_LEVELS) + powerLevelsEvent?.content?.toModel()?.let { powerLevelsContent -> + val powerLevelsHelper = PowerLevelsHelper(powerLevelsContent) + val isAdmin = powerLevelsHelper.getUserRole(session.myUserId) is Role.Admin + val otherAdminCount = spaceSummary?.otherMemberIds + ?.map { powerLevelsHelper.getUserRole(it) } + ?.count { it is Role.Admin } + ?: 0 + val isLastAdmin = isAdmin && otherAdminCount == 0 + setState { + copy(isLastAdmin = isLastAdmin) } } - } - init { - val spaceSummary = session.getRoomSummary(initialState.spaceId) setState { copy(spaceSummary = spaceSummary) } session.getRoom(initialState.spaceId)?.let { room -> room.flow().liveRoomSummary() @@ -127,6 +104,62 @@ class SpaceLeaveAdvancedViewModel @AssistedInject constructor( } } + override fun handle(action: SpaceLeaveAdvanceViewAction) { + when (action) { + is SpaceLeaveAdvanceViewAction.UpdateFilter -> setState { copy(currentFilter = action.filter) } + SpaceLeaveAdvanceViewAction.ClearError -> setState { copy(leaveState = Uninitialized) } + SpaceLeaveAdvanceViewAction.SelectNone -> setState { copy(selectedRooms = emptyList()) } + is SpaceLeaveAdvanceViewAction.SetFilteringEnabled -> setState { copy(isFilteringEnabled = action.isEnabled) } + is SpaceLeaveAdvanceViewAction.ToggleSelection -> handleSelectionToggle(action) + SpaceLeaveAdvanceViewAction.DoLeave -> handleLeave() + SpaceLeaveAdvanceViewAction.SelectAll -> handleSelectAll() + } + } + + private fun handleSelectAll() = withState { state -> + val filteredRooms = (state.allChildren as? Success)?.invoke()?.filter { + it.name.contains(state.currentFilter, true) + } + filteredRooms?.let { + setState { copy(selectedRooms = it.map { it.roomId }) } + } + } + + private fun handleLeave() = withState { state -> + setState { copy(leaveState = Loading()) } + viewModelScope.launch { + try { + state.selectedRooms.forEach { + try { + session.roomService().leaveRoom(it) + } catch (failure: Throwable) { + // silently ignore? + Timber.e(failure, "Fail to leave sub rooms/spaces") + } + } + + session.spaceService().leaveSpace(initialState.spaceId) + // We observe the membership and to dismiss when we have remote echo of leaving + } catch (failure: Throwable) { + setState { copy(leaveState = Fail(failure)) } + } + } + } + + private fun handleSelectionToggle(action: SpaceLeaveAdvanceViewAction.ToggleSelection) = withState { state -> + val existing = state.selectedRooms.toMutableList() + if (existing.contains(action.roomId)) { + existing.remove(action.roomId) + } else { + existing.add(action.roomId) + } + setState { + copy( + selectedRooms = existing.toImmutableList(), + ) + } + } + @AssistedFactory interface Factory : MavericksAssistedViewModelFactory { override fun create(initialState: SpaceLeaveAdvanceViewState): SpaceLeaveAdvancedViewModel diff --git a/vector/src/main/java/im/vector/app/features/themes/ThemeUtils.kt b/vector/src/main/java/im/vector/app/features/themes/ThemeUtils.kt index 6c8ea0a3f9..3b1e8240fa 100644 --- a/vector/src/main/java/im/vector/app/features/themes/ThemeUtils.kt +++ b/vector/src/main/java/im/vector/app/features/themes/ThemeUtils.kt @@ -76,7 +76,7 @@ object ThemeUtils { } /** - * Provides the selected application theme + * Provides the selected application theme. * * @param context the context * @return the selected application theme @@ -106,7 +106,7 @@ object ThemeUtils { } /** - * Update the application theme + * Update the application theme. * * @param aTheme the new theme */ @@ -141,7 +141,7 @@ object ThemeUtils { } /** - * Translates color attributes to colors + * Translates color attributes to colors. * * @param c Context * @param colorAttribute Color Attribute @@ -173,7 +173,7 @@ object ThemeUtils { } /** - * Tint the drawable with a theme attribute + * Tint the drawable with a theme attribute. * * @param context the context * @param drawable the drawable to tint @@ -185,7 +185,7 @@ object ThemeUtils { } /** - * Tint the drawable with a color integer + * Tint the drawable with a color integer. * * @param drawable the drawable to tint * @param color the color diff --git a/vector/src/main/java/im/vector/app/features/ui/SharedPreferencesUiStateRepository.kt b/vector/src/main/java/im/vector/app/features/ui/SharedPreferencesUiStateRepository.kt index 6693d7436c..050232dd84 100644 --- a/vector/src/main/java/im/vector/app/features/ui/SharedPreferencesUiStateRepository.kt +++ b/vector/src/main/java/im/vector/app/features/ui/SharedPreferencesUiStateRepository.kt @@ -23,7 +23,7 @@ import im.vector.app.features.settings.VectorPreferences import javax.inject.Inject /** - * This class is used to persist UI state across application restart + * This class is used to persist UI state across application restart. */ class SharedPreferencesUiStateRepository @Inject constructor( private val sharedPreferences: SharedPreferences, diff --git a/vector/src/main/java/im/vector/app/features/ui/UiStateRepository.kt b/vector/src/main/java/im/vector/app/features/ui/UiStateRepository.kt index 3c48f8972d..e2a87ce226 100644 --- a/vector/src/main/java/im/vector/app/features/ui/UiStateRepository.kt +++ b/vector/src/main/java/im/vector/app/features/ui/UiStateRepository.kt @@ -19,12 +19,12 @@ package im.vector.app.features.ui import im.vector.app.features.home.RoomListDisplayMode /** - * This interface is used to persist UI state across application restart + * This interface is used to persist UI state across application restart. */ interface UiStateRepository { /** - * Reset all the saved data + * Reset all the saved data. */ fun reset() diff --git a/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewEvents.kt b/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewEvents.kt index ef29e8015a..6e244d20bb 100644 --- a/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewEvents.kt +++ b/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewEvents.kt @@ -20,7 +20,7 @@ import im.vector.app.core.platform.VectorViewEvents import im.vector.app.features.discovery.ServerAndPolicies /** - * Transient events for invite users to room screen + * Transient events for invite users to room screen. */ sealed class UserListViewEvents : VectorViewEvents { data class Failure(val throwable: Throwable) : UserListViewEvents() diff --git a/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewModel.kt b/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewModel.kt index bb1f8db6ff..b5f9d57970 100644 --- a/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/userdirectory/UserListViewModel.kt @@ -271,6 +271,6 @@ class UserListViewModel @AssistedInject constructor( private fun UserListViewState.hasNoIdentityServerConfigured() = matchingEmail is Fail && matchingEmail.error == IdentityServiceError.NoIdentityServerConfigured /** - * Wrapper class to allow identical search terms to be re-emitted + * Wrapper class to allow identical search terms to be re-emitted. */ private data class UserSearch(val searchTerm: String, val cacheBuster: Long = 0) diff --git a/vector/src/main/java/im/vector/app/features/voice/VoicePlayerHelper.kt b/vector/src/main/java/im/vector/app/features/voice/VoicePlayerHelper.kt index 6c9b8d34c2..80db3fdc0c 100644 --- a/vector/src/main/java/im/vector/app/features/voice/VoicePlayerHelper.kt +++ b/vector/src/main/java/im/vector/app/features/voice/VoicePlayerHelper.kt @@ -36,7 +36,7 @@ class VoicePlayerHelper @Inject constructor( } /** - * Ensure the file is encoded using aac audio codec + * Ensure the file is encoded using aac audio codec. */ fun convertFile(file: File): File? { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { diff --git a/vector/src/main/java/im/vector/app/features/voice/VoiceRecorder.kt b/vector/src/main/java/im/vector/app/features/voice/VoiceRecorder.kt index 691e064b8f..a5f4b52982 100644 --- a/vector/src/main/java/im/vector/app/features/voice/VoiceRecorder.kt +++ b/vector/src/main/java/im/vector/app/features/voice/VoiceRecorder.kt @@ -27,30 +27,30 @@ interface VoiceRecorder { fun initializeRecord(attachmentData: ContentAttachmentData) /** - * Start the recording + * Start the recording. * @param roomId id of the room to start record */ fun startRecord(roomId: String) /** - * Stop the recording + * Stop the recording. */ fun stopRecord() /** - * Remove the file + * Remove the file. */ fun cancelRecord() fun getMaxAmplitude(): Int /** - * Not guaranteed to be a ogg file + * Not guaranteed to be a ogg file. */ fun getCurrentRecord(): File? /** - * Guaranteed to be a ogg file + * Guaranteed to be a ogg file. */ fun getVoiceMessageFile(): File? } diff --git a/vector/src/main/java/im/vector/app/features/webview/ConsentWebViewEventListener.kt b/vector/src/main/java/im/vector/app/features/webview/ConsentWebViewEventListener.kt index 91253383ea..e7f5ac29b9 100644 --- a/vector/src/main/java/im/vector/app/features/webview/ConsentWebViewEventListener.kt +++ b/vector/src/main/java/im/vector/app/features/webview/ConsentWebViewEventListener.kt @@ -44,7 +44,7 @@ class ConsentWebViewEventListener(activity: VectorBaseActivity<*>, } /** - * This methods try to create the RiotBot room when the user gives his agreement + * This methods try to create the RiotBot room when the user gives his agreement. */ private fun createRiotBotRoomIfNeeded() { safeActivity?.let { @@ -72,7 +72,7 @@ class ConsentWebViewEventListener(activity: VectorBaseActivity<*>, } /** - * APICallback instance + * APICallback instance. */ private val createRiotBotRoomCallback = object : MatrixCallback { override fun onSuccess(data: String) { diff --git a/vector/src/main/java/im/vector/app/features/webview/WebViewEventListener.kt b/vector/src/main/java/im/vector/app/features/webview/WebViewEventListener.kt index 897c913257..bd77283029 100644 --- a/vector/src/main/java/im/vector/app/features/webview/WebViewEventListener.kt +++ b/vector/src/main/java/im/vector/app/features/webview/WebViewEventListener.kt @@ -68,7 +68,7 @@ interface WebViewEventListener { } /** - * Triggered when a webview load an url + * Triggered when a webview load an url. * * @param url The url about to be rendered. * @return true if the method needs to manage some custom handling diff --git a/vector/src/main/java/im/vector/app/features/widgets/WidgetPostAPIHandler.kt b/vector/src/main/java/im/vector/app/features/widgets/WidgetPostAPIHandler.kt index e397eeb9a4..3c88ea65a3 100644 --- a/vector/src/main/java/im/vector/app/features/widgets/WidgetPostAPIHandler.kt +++ b/vector/src/main/java/im/vector/app/features/widgets/WidgetPostAPIHandler.kt @@ -108,7 +108,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Retrieve the latest botOptions event + * Retrieve the latest botOptions event. * * @param eventData the modular data */ @@ -169,7 +169,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Provides the membership state + * Provides the membership state. * * @param eventData the modular data */ @@ -188,7 +188,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Request the latest joined room event + * Request the latest joined room event. * * @param eventData the modular data */ @@ -206,7 +206,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Provide the widgets list + * Provide the widgets list. * * @param eventData the modular data */ @@ -226,7 +226,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Set a new widget + * Set a new widget. * * @param eventData the modular data */ @@ -301,7 +301,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Update the 'plumbing state" + * Update the 'plumbing state". * * @param eventData the modular data */ @@ -326,7 +326,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Update the bot options + * Update the bot options. * * @param eventData the modular data */ @@ -351,7 +351,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Update the bot power levels + * Update the bot power levels. * * @param eventData the modular data */ @@ -373,7 +373,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Invite an user to this room + * Invite an user to this room. * * @param eventData the modular data */ @@ -395,7 +395,7 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Provides the number of members in the rooms + * Provides the number of members in the rooms. * * @param eventData the modular data */ @@ -425,8 +425,8 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Check if roomId is present in the event and match - * Send response and return true in case of error + * Check if roomId is present in the event and match. + * Send response and return true in case of error. * * @return true in case of error */ @@ -448,8 +448,8 @@ class WidgetPostAPIHandler @AssistedInject constructor(@Assisted private val roo } /** - * Check if userId is present in the event - * Send response and return true in case of error + * Check if userId is present in the event. + * Send response and return true in case of error. * * @return true in case of error */ diff --git a/vector/src/main/java/im/vector/app/features/workers/signout/ServerBackupStatusViewModel.kt b/vector/src/main/java/im/vector/app/features/workers/signout/ServerBackupStatusViewModel.kt index 1c55145e16..8c24b2893a 100644 --- a/vector/src/main/java/im/vector/app/features/workers/signout/ServerBackupStatusViewModel.kt +++ b/vector/src/main/java/im/vector/app/features/workers/signout/ServerBackupStatusViewModel.kt @@ -48,8 +48,8 @@ data class ServerBackupStatusViewState( ) : MavericksState /** - * The state representing the view - * It can take one state at a time + * The state representing the view. + * It can take one state at a time. */ sealed class BannerState { @@ -121,21 +121,21 @@ class ServerBackupStatusViewModel @AssistedInject constructor(@Assisted initialS } /** - * Safe way to get the current KeysBackup version + * Safe way to get the current KeysBackup version. */ fun getCurrentBackupVersion(): String { return session.cryptoService().keysBackupService().currentBackupVersion ?: "" } /** - * Safe way to get the number of keys to backup + * Safe way to get the number of keys to backup. */ fun getNumberOfKeysToBackup(): Int { return session.cryptoService().inboundGroupSessionsCount(false) } /** - * Safe way to tell if there are more keys on the server + * Safe way to tell if there are more keys on the server. */ fun canRestoreKeys(): Boolean { return session.cryptoService().keysBackupService().canRestoreKeys() diff --git a/vector/src/main/res/drawable-hdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-hdpi/bg_no_location_map.webp index 23a45700f0..3241b5dc82 100644 Binary files a/vector/src/main/res/drawable-hdpi/bg_no_location_map.webp and b/vector/src/main/res/drawable-hdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-mdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-mdpi/bg_no_location_map.webp index a6130fba78..03f9ba5062 100644 Binary files a/vector/src/main/res/drawable-mdpi/bg_no_location_map.webp and b/vector/src/main/res/drawable-mdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-night-hdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-night-hdpi/bg_no_location_map.webp new file mode 100644 index 0000000000..76e0a75dd6 Binary files /dev/null and b/vector/src/main/res/drawable-night-hdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-night-mdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-night-mdpi/bg_no_location_map.webp new file mode 100644 index 0000000000..79900cec1b Binary files /dev/null and b/vector/src/main/res/drawable-night-mdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-night-xhdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-night-xhdpi/bg_no_location_map.webp new file mode 100644 index 0000000000..14f7e0e44c Binary files /dev/null and b/vector/src/main/res/drawable-night-xhdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-night-xxhdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-night-xxhdpi/bg_no_location_map.webp new file mode 100644 index 0000000000..91cb7c8eb6 Binary files /dev/null and b/vector/src/main/res/drawable-night-xxhdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-night-xxxhdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-night-xxxhdpi/bg_no_location_map.webp new file mode 100644 index 0000000000..e4864a9eb2 Binary files /dev/null and b/vector/src/main/res/drawable-night-xxxhdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-xhdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-xhdpi/bg_no_location_map.webp index e908191371..513089b55b 100644 Binary files a/vector/src/main/res/drawable-xhdpi/bg_no_location_map.webp and b/vector/src/main/res/drawable-xhdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-xxhdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-xxhdpi/bg_no_location_map.webp index e062178367..50284965a7 100644 Binary files a/vector/src/main/res/drawable-xxhdpi/bg_no_location_map.webp and b/vector/src/main/res/drawable-xxhdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable-xxxhdpi/bg_no_location_map.webp b/vector/src/main/res/drawable-xxxhdpi/bg_no_location_map.webp index 8b110d33fe..881af0055a 100644 Binary files a/vector/src/main/res/drawable-xxxhdpi/bg_no_location_map.webp and b/vector/src/main/res/drawable-xxxhdpi/bg_no_location_map.webp differ diff --git a/vector/src/main/res/drawable/ic_presence_away.xml b/vector/src/main/res/drawable/ic_presence_away.xml new file mode 100644 index 0000000000..617fe735b6 --- /dev/null +++ b/vector/src/main/res/drawable/ic_presence_away.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/vector/src/main/res/drawable/ic_presence_busy.xml b/vector/src/main/res/drawable/ic_presence_busy.xml new file mode 100644 index 0000000000..9155a6b4a5 --- /dev/null +++ b/vector/src/main/res/drawable/ic_presence_busy.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/vector/src/main/res/drawable/ic_settings_root_flair.xml b/vector/src/main/res/drawable/ic_settings_root_flair.xml deleted file mode 100644 index b074ae478e..0000000000 --- a/vector/src/main/res/drawable/ic_settings_root_flair.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/vector/src/main/res/drawable/thread_filter_badge.xml b/vector/src/main/res/drawable/thread_filter_badge.xml new file mode 100644 index 0000000000..c9a01197c8 --- /dev/null +++ b/vector/src/main/res/drawable/thread_filter_badge.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + diff --git a/vector/src/main/res/layout/bottom_sheet_leave_space.xml b/vector/src/main/res/layout/bottom_sheet_leave_space.xml deleted file mode 100644 index 9e5a7c7ebf..0000000000 --- a/vector/src/main/res/layout/bottom_sheet_leave_space.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -