diff --git a/.github/renovate.json5 b/.github/renovate.json5 index c16310cf43..86ab2f1b1e 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -7,7 +7,6 @@ "PR-Dependencies", ], "ignoreDeps": [ - "string:app_name", "gradle", ], "minimumReleaseAge": "7 days", diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 69152b7e2d..48f67099ea 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -51,12 +51,12 @@ jobs: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.ref }} persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Assemble debug APKs diff --git a/.github/workflows/build_enterprise.yml b/.github/workflows/build_enterprise.yml index f2658bb342..7560c36a06 100644 --- a/.github/workflows/build_enterprise.yml +++ b/.github/workflows/build_enterprise.yml @@ -56,12 +56,12 @@ jobs: - name: Clone submodules run: git submodule update --init --recursive - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Assemble debug Gplay Enterprise APK diff --git a/.github/workflows/generate_github_pages.yml b/.github/workflows/generate_github_pages.yml index 45e886f904..300058ec87 100644 --- a/.github/workflows/generate_github_pages.yml +++ b/.github/workflows/generate_github_pages.yml @@ -19,12 +19,12 @@ jobs: - name: ⏬ Checkout with LFS uses: nschloe/action-cached-lfs-checkout@385a8ecc719e50b8c71af6ab01a624b486b7c3bc # v1.2.5 - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Set up Python 3.12 diff --git a/.github/workflows/gradle-wrapper-update.yml b/.github/workflows/gradle-wrapper-update.yml index 6b64a731d7..c64ab731a3 100644 --- a/.github/workflows/gradle-wrapper-update.yml +++ b/.github/workflows/gradle-wrapper-update.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 name: Use JDK 21 with: distribution: 'temurin' # See 'Supported distributions' for available options diff --git a/.github/workflows/maestro-local.yml b/.github/workflows/maestro-local.yml index 198b462349..e2d37aadb9 100644 --- a/.github/workflows/maestro-local.yml +++ b/.github/workflows/maestro-local.yml @@ -44,13 +44,13 @@ jobs: # https://github.com/actions/checkout/issues/881 ref: ${{ github.ref }} persist-credentials: false - - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 name: Use JDK 21 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Assemble debug APK diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 9beab4e01c..67c94da9f6 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -36,7 +36,7 @@ jobs: with: persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' diff --git a/.github/workflows/nightlyReports.yml b/.github/workflows/nightlyReports.yml index 23cfffc265..929dd6680a 100644 --- a/.github/workflows/nightlyReports.yml +++ b/.github/workflows/nightlyReports.yml @@ -37,13 +37,13 @@ jobs: uses: nschloe/action-cached-lfs-checkout@385a8ecc719e50b8c71af6ab01a624b486b7c3bc # v1.2.5 - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: false @@ -80,12 +80,12 @@ jobs: with: persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Dependency analysis diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index e72ae0b4d1..14e5ee7a74 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -69,12 +69,12 @@ jobs: with: persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Set up Python 3.12 @@ -108,12 +108,12 @@ jobs: if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == 'element-hq/element-x-android' }} run: git submodule update --init --recursive - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Run Konsist tests @@ -149,12 +149,12 @@ jobs: if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == 'element-hq/element-x-android' }} run: git submodule update --init --recursive - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Run compose tests @@ -183,12 +183,12 @@ jobs: if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == 'element-hq/element-x-android' }} run: git submodule update --init --recursive - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Build Gplay Debug @@ -228,12 +228,12 @@ jobs: if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == 'element-hq/element-x-android' }} run: git submodule update --init --recursive - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Run Detekt @@ -269,12 +269,12 @@ jobs: if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == 'element-hq/element-x-android' }} run: git submodule update --init --recursive - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Run Ktlint check @@ -336,7 +336,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: zizmorcore/zizmor-action@6fc4b006235f201fdab3722e17240ab420d580e5 # v0.6.1 + - uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 upload_reports: name: Project Check Suite diff --git a/.github/workflows/recordScreenshots.yml b/.github/workflows/recordScreenshots.yml index 00502d9612..44082bd347 100644 --- a/.github/workflows/recordScreenshots.yml +++ b/.github/workflows/recordScreenshots.yml @@ -54,13 +54,13 @@ jobs: with: persist-credentials: false - name: ☕️ Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' # Add gradle cache, this should speed up the process - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Record screenshots diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4bc71a02ff..b9d8be16c9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,12 +38,12 @@ jobs: with: persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 - name: Create app bundle env: ELEMENT_ANDROID_MAPTILER_API_KEY: ${{ secrets.MAPTILER_KEY }} @@ -82,12 +82,12 @@ jobs: - name: Clone submodules run: git submodule update --init --recursive - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 - name: Create Enterprise app bundle env: ELEMENT_ANDROID_MAPTILER_API_KEY: ${{ secrets.MAPTILER_KEY }} @@ -126,12 +126,12 @@ jobs: with: persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 - name: Create APKs env: ELEMENT_ANDROID_MAPTILER_API_KEY: ${{ secrets.MAPTILER_KEY }} diff --git a/.github/workflows/scripts/recordScreenshots.sh b/.github/workflows/scripts/recordScreenshots.sh index d29353a2c2..d04ee46f72 100755 --- a/.github/workflows/scripts/recordScreenshots.sh +++ b/.github/workflows/scripts/recordScreenshots.sh @@ -78,6 +78,10 @@ else git config --local user.name "${INPUT_AUTHOR_EMAIL}" fi git add -A +if git diff --cached --quiet; then + echo "Screenshots are already up to date, nothing to commit." + exit 0 +fi git commit -m "Update screenshots" GITHUB_REPO="https://$GITHUB_ACTOR:$TOKEN@github.com/$REPO.git" diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 6d9a62a2d1..26e24f3bd4 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -45,12 +45,12 @@ jobs: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.ref }} persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Build debug code and test fixtures diff --git a/.github/workflows/sync-localazy.yml b/.github/workflows/sync-localazy.yml index 61b4a8d521..939354f12f 100644 --- a/.github/workflows/sync-localazy.yml +++ b/.github/workflows/sync-localazy.yml @@ -17,12 +17,12 @@ jobs: with: persist-credentials: false - name: Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} - name: Set up Python 3.12 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5ee7f5065d..d558baf73a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -63,12 +63,12 @@ jobs: if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == 'element-hq/element-x-android' }} run: git submodule update --init --recursive - name: ☕️ Use JDK 21 - uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' # See 'Supported distributions' for available options java-version: '21' - name: Configure gradle - uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 with: cache-read-only: ${{ github.ref != 'refs/heads/develop' }} diff --git a/.gitignore b/.gitignore index 77acaadb20..a50ae12c6e 100644 --- a/.gitignore +++ b/.gitignore @@ -31,9 +31,6 @@ __pycache__/ # Local configuration file (sdk path, etc) local.properties -# Proguard folder generated by Eclipse -proguard/ - # Log Files *.log diff --git a/.idea/copyright/Element_Enterprise.xml b/.idea/copyright/Element_Enterprise.xml index b556049368..f7637c76a5 100644 --- a/.idea/copyright/Element_Enterprise.xml +++ b/.idea/copyright/Element_Enterprise.xml @@ -1,6 +1,6 @@ - \ No newline at end of file diff --git a/.maestro/tests/account/changeServer.yaml b/.maestro/tests/account/changeServer.yaml deleted file mode 100644 index b07fa5cc09..0000000000 --- a/.maestro/tests/account/changeServer.yaml +++ /dev/null @@ -1,21 +0,0 @@ -appId: ${MAESTRO_APP_ID} ---- -- tapOn: - id: "login-change_server" -- takeScreenshot: build/maestro/200-ChangeServer -- tapOn: "matrix.org" -- tapOn: - id: "login-change_server" -- tapOn: "Other" -- tapOn: - id: "change_server-server" -- inputText: "element" -- hideKeyboard -- extendedWaitUntil: - visible: "element.io" - timeout: 10000 -- tapOn: "element.io" -# Revert to matrix.org -- tapOn: - id: "login-change_server" -- tapOn: "matrix.org" diff --git a/.maestro/tests/account/login.yaml b/.maestro/tests/account/login.yaml index 873843b22d..81922c7f38 100644 --- a/.maestro/tests/account/login.yaml +++ b/.maestro/tests/account/login.yaml @@ -3,8 +3,7 @@ appId: ${MAESTRO_APP_ID} - tapOn: "Sign in manually" - runFlow: ../assertions/assertLoginDisplayed.yaml - takeScreenshot: build/maestro/100-SignIn -- runFlow: changeServer.yaml -- runFlow: ../assertions/assertLoginDisplayed.yaml +# The account provider field defaults to matrix.org, so continue straight to the MAS login. - tapOn: id: "login-continue" ## MAS page diff --git a/.maestro/tests/assertions/assertLoginDisplayed.yaml b/.maestro/tests/assertions/assertLoginDisplayed.yaml index 6d8558c38e..c32f23c323 100644 --- a/.maestro/tests/assertions/assertLoginDisplayed.yaml +++ b/.maestro/tests/assertions/assertLoginDisplayed.yaml @@ -1,5 +1,5 @@ appId: ${MAESTRO_APP_ID} --- - extendedWaitUntil: - visible: "Change account provider" + visible: "Enter your account provider" timeout: 10000 diff --git a/AGENTS.md b/AGENTS.md index d206be98c6..917285ab30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,8 +37,9 @@ PRs must meet these rules. - Create previews for **all main states** of a Composable. - Use `@PreviewsDayNight` for consistency. -- Use `PreviewParameterProvider` (e.g., `FooStateProvider`) to provide states. +- Use `PreviewParameterProvider` (e.g., `FooStatePreviewParam`) to provide states. - Wrap previews in `ElementPreview { ... }`. +- When writing tests, never try to record the screenshots, the CI will do it. --- @@ -88,7 +89,7 @@ We use [Appyx](https://bumble-tech.github.io/appyx/) for navigation and [Molecul | `FooView.kt` | Stateless Composable rendering the UI from `FooState`. | | `FooState.kt` | Data class representing the immutable UI state. | | `FooEvent.kt` | Sealed interface for UI actions sent to the Presenter. | -| `FooStateProvider.kt` | Provides sample states for Previews and Screenshot tests. | +| `FooStatePreviewParam.kt` | Provides sample states for Previews and Screenshot tests. | | `FooPresenterTest.kt` | Unit tests for the Presenter logic using Turbine. | --- diff --git a/CHANGES.md b/CHANGES.md index 3f7360a338..db18e59251 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,178 @@ +Changes in Element X v26.08.2 +============================= + + + +**Note: this release in an internal release, it will not be pushed to the stores.** + +## What's Changed +### ✨ Features +* Remove the legacy web-based account creation for matrix.org by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7412 +### 🙌 Improvements +* Move the custom tile server URL config to the Element wellknown content by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7416 +* Explain a rate limiting push gateway in the notification troubleshooter by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7448 +* Move the `:libraries:wellknown` logic into `enterprise` modules by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7429 +* Refresh the room members when a mention is started by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7438 +* Close the invite screen once the invite has been declined by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7440 +* Use Profiles sliding sync extension check for own profile subscription by @ganfra in https://github.com/element-hq/element-x-android/pull/7403 +* Simplify choosing the account provider during sign in, with autocomplete of previously used ones by @jennaharris7 in https://github.com/element-hq/element-x-android/pull/7394 +### 🐛 Bugfixes +* Fix wrong TextComposer placeholder displayed when in a thread. by @bmarty in https://github.com/element-hq/element-x-android/pull/7413 +* Fix bug reports failing to send after the app has crashed by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7395 +* Fix outgoing session verification stuck with incomplete recovery setup by @hardcore-sushi in https://github.com/element-hq/element-x-android/pull/7433 +* Keep transparency when an image is shared into the app with an imprecise mime type by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7452 +* Don't restart the sync service if the client is shutting down by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7472 +* Normalize the applicationName used in user agent by @bmarty in https://github.com/element-hq/element-x-android/pull/7477 +* Keep playing a voice message when another app plays a short sound by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7454 +* Keep the send button when the composer is emptied while editing a message by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7456 +* Do not open the room again when the app is resumed from the recents list by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7436 +* Stop waiting for a room alias that the remote server never resolves by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7446 +### 🧱 Build +* build-rust-sdk: print the command we run by @richvdh in https://github.com/element-hq/element-x-android/pull/7407 +* Remove license check on Pro modules. by @bmarty in https://github.com/element-hq/element-x-android/pull/7418 +* Improve build time config and update the Firebase configuration by @bmarty in https://github.com/element-hq/element-x-android/pull/7473 +* Make the PUSHER_APP_ID configurable at build time. by @bmarty in https://github.com/element-hq/element-x-android/pull/7478 +### 📄 Documentation +* Add KDoc to all the interfaces of the api modules by @bmarty in https://github.com/element-hq/element-x-android/pull/7426 +### 🚧 In development 🚧 +* [LinkNewDevice] Ensure the notice screen is also protected by the timeout. by @bmarty in https://github.com/element-hq/element-x-android/pull/7428 +### Dependency upgrades +* Update kotlin to v2.3.11 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7396 +* Update plugin sonarqube to v7.4.0.8496 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7415 +* Update metro to v1.4.1 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7421 +* Update roborazzi to v1.71.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7423 +* Update dependency io.sentry:sentry-android to v8.52.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7414 +* Update dependency org.matrix.rustcomponents:sdk-android to v26.08.13 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7420 +* Update dependency io.github.sergio-sastre.ComposablePreviewScanner:android to v0.9.2 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7431 +* Update dependency org.maplibre.compose:maplibre-compose to v0.14.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7432 +* Update dependency org.matrix.rustcomponents:sdk-android to v26.08.17 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7460 +* Update dependency org.matrix.rustcomponents:sdk-android to v26.08.19 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7479 +* Update media3 to v1.11.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7427 +* Update dependency androidx.compose:compose-bom to v2026.08.00 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7483 +### 💼 Element Pro +* Add hooks to allow providing additional feature flags in EX pro by @richvdh in https://github.com/element-hq/element-x-android/pull/7419 +* Use the right base URL for the ESS config/well known endpoints by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7469 +### Others +* Do not display pinned events that the client cannot render by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7379 +* Hide the forward action on live location shares by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7343 +* Do not fail the screenshot recording job when there is nothing to commit by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7355 +* Show the account a UnifiedPush registration belongs to in the distributor by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7345 +* Stop repeating messages that are already shown in a room notification by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7370 +* Turn a matrix: URI in a message into a pill by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7354 +* Send a message with Enter on a physical keyboard, Shift+Enter for a new line by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7353 +* Do not group timeline messages sent more than five minutes apart by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7349 +* Linkify URLs whose host is a bracketed IPv6 address by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7347 +* Add missing tests for `RustTemporaryMatrixClient` by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7417 +* Revert "Keep manually revealed media visible when re-entering a room" by @bmarty in https://github.com/element-hq/element-x-android/pull/7424 +* Fix outdated documentation. by @bmarty in https://github.com/element-hq/element-x-android/pull/7430 +* Sync strings - New language supported: Arabic by @bmarty in https://github.com/element-hq/element-x-android/pull/7461 +* Keep the focused login field visible above the keyboard by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7455 +* Relax image compression so photos and screenshots keep more detail by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7451 +* Open the user profile of a user id that contains a slash by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7445 +* Remove the F-Droid dex patching step from the release script by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7442 +* Convert markdown to HTML when a caption is edited by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7441 +* Exclude carriage returns from the login and password fields by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7439 +* Show an error when the room to leave cannot be found by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7437 +* Give the room name in the timeline top bar a 48dp tap target by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7450 +* Model the fake voice recorder on a cancellable recording job by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7466 + +## New Contributors +* @hardcore-sushi made their first contribution in https://github.com/element-hq/element-x-android/pull/7433 + +**Full Changelog**: https://github.com/element-hq/element-x-android/compare/v26.08.1...v26.08.2 + +Changes in Element X v26.08.1 +============================= + + + +## What's Changed +### 🙌 Improvements +* Render push notifications for live location share starts (MSC4505) by @ara4n in https://github.com/element-hq/element-x-android/pull/7203 +* [Task] Show active call participants in the people list #7199 by @Eklavya47 in https://github.com/element-hq/element-x-android/pull/7300 +### 🐛 Bugfixes +* Fix overlap issue. by @bmarty in https://github.com/element-hq/element-x-android/pull/7331 +* Announce checked/unchecked state for user rows in invite screen by @bmarty in https://github.com/element-hq/element-x-android/pull/7136 +* Display 'add reactions' menu in the threads screen by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7388 +* Expand the emoji picker to full height when the keyboard is shown by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7382 +* UI fixes by @bmarty in https://github.com/element-hq/element-x-android/pull/7409 +### 🗣 Translations +* Sync Strings by @ElementBot in https://github.com/element-hq/element-x-android/pull/7389 +### 🧱 Build +* Don't check enterprise previews in `KonsistPreviewTest` by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7297 +* CI: split unit tests, screenshots and coverage in `tests.yml` by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7296 +* Update Gradle Wrapper from 9.6.1 to 9.7.0 by @ElementBot in https://github.com/element-hq/element-x-android/pull/7335 +### 🚧 In development 🚧 +* QR code login iteration by @bmarty in https://github.com/element-hq/element-x-android/pull/6719 +* User status last pieces by @ganfra in https://github.com/element-hq/element-x-android/pull/7328 +* [Link new device] Add timeout by @bmarty in https://github.com/element-hq/element-x-android/pull/7338 +### Dependency upgrades +* Update dependency org.maplibre.compose:maplibre-compose to v0.13.1 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7291 +* Update android.gradle.plugin to v9.3.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7248 +* Update dependency io.sentry:sentry-android to v8.50.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7298 +* Update zizmorcore/zizmor-action action to v0.6.1 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7306 +* Update android.gradle.plugin to v9.3.1 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7304 +* Update dependency com.posthog:posthog-android to v3.56.4 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7311 +* Update dependencyAnalysis to v3.18.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7318 +* Update actions/stale action to v11 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7317 +* Update dependency io.github.zxing-cpp:android to v3.1.1 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7322 +* Update dependency org.matrix.rustcomponents:sdk-android to v26.08.05 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7324 +* Update dependency androidx.constraintlayout:constraintlayout to v2.2.2 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7329 +* Update reactivecircus/android-emulator-runner action to v2.38.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7189 +* Update dependency io.sentry:sentry-android to v8.51.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7301 +* Update dependency org.maplibre.gl:android-sdk to v13.4.1 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7305 +* Update dependency io.element.android:element-call-embedded to v0.23.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7323 +* Update metro to v1.4.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7334 +* Update dependency com.google.firebase:firebase-bom to v34.17.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7333 +* Update dependency androidx.compose.material3:material3 to v1.5.0-alpha23 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7175 +* Update dependency org.jsoup:jsoup to v1.23.1 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7332 +* Update dependency androidx.constraintlayout:constraintlayout-compose to v1.1.2 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7330 +* Update zizmorcore/zizmor-action action to v0.6.2 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7383 +* Update actions/setup-java action to v5.7.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7339 +* Update gradle/actions action to v6.3.0 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7384 +* Update plugin dependencycheck to v13 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7386 +* Update dependency org.matrix.rustcomponents:sdk-android to v26.08.11 by @renovate[bot] in https://github.com/element-hq/element-x-android/pull/7402 +### 💼 Element Pro +* Add support for checking the ESS config in Element Pro by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7302 +### Others +* Add extra vertical padding to `ReplyToInvalidContent` and `ReplyToNotFoundContent` by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7288 +* Index messages locally in an encrypted on-device store so encrypted rooms can be searched at all by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7249 +* Bump enterprise module to the latest commit by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7307 +* Bump enterprise module to the latest commit by @jennaharris7 in https://github.com/element-hq/element-x-android/pull/7309 +* Move deviceId and git details to developer settings by @bmarty in https://github.com/element-hq/element-x-android/pull/7241 +* Show a Message not found placeholder when a replied to message cannot be loaded by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7376 +* Update in reply to message when message is not found. by @bmarty in https://github.com/element-hq/element-x-android/pull/7387 +* Add default `OAUTH_CLIENT_URL_PATH` alternative by @jmartinesp in https://github.com/element-hq/element-x-android/pull/7385 +* Fix the feature module template writing the impl build script into the api module by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7374 +* Let users enter their full Matrix user ID when searching for a homeserver by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7375 +* Keep manually revealed media visible when re-entering a room by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7378 +* Copy a blocked user's Matrix ID by long pressing them by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7372 +* Do not draw the media loading progress bar under the status bar by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7366 +* Do not notify about an event sent by another account on the same device by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7360 +* Keep the opened image on screen when the media gallery fails to load by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7362 +* Do not linkify the server part of a fediverse handle as an email address by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7356 +* Expose global account data get and set on MatrixClient by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7373 +* Show the alias or the direct message user's Matrix ID in the room picker by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7371 +* Use a dedicated string for the Mute room notification mode by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7367 +* Keep playing a voice message when the screen turns off by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7365 +* Let a voice message without a waveform be seeked by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7363 +* Ignore a second voice recording start while one is already running by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7346 +* Do not offer to start a call in a DM with no other member by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7352 +* Do not notify about a redaction whose target event is unknown by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7350 +* Ignore a room list filter that is incompatible with an already selected one by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7342 +* Stop a right to left sender name from reordering a room list preview by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7348 +* Do not append the application MapTiler key to a custom map style url by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7340 +* Hide space children you have left that can only be joined by invitation by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7369 +* Never re-encode a video at a higher bitrate than the source by @hayaksi1 in https://github.com/element-hq/element-x-android/pull/7351 +* Display push notifications for knocks by @ara4n in https://github.com/element-hq/element-x-android/pull/7207 + +## New Contributors +* @hayaksi1 made their first contribution in https://github.com/element-hq/element-x-android/pull/7249 +* @ara4n made their first contribution in https://github.com/element-hq/element-x-android/pull/7203 +* @Eklavya47 made their first contribution in https://github.com/element-hq/element-x-android/pull/7300 + +**Full Changelog**: https://github.com/element-hq/element-x-android/compare/v26.08.0...v26.08.1 + Changes in Element X v26.08.0 ============================= diff --git a/annotations/src/main/kotlin/io/element/android/annotations/ContributesNode.kt b/annotations/src/main/kotlin/io/element/android/annotations/ContributesNode.kt index 632bdc3e81..8091206cbd 100644 --- a/annotations/src/main/kotlin/io/element/android/annotations/ContributesNode.kt +++ b/annotations/src/main/kotlin/io/element/android/annotations/ContributesNode.kt @@ -14,16 +14,16 @@ import kotlin.reflect.KClass * Adds Node to the specified component graph. * Equivalent to the following declaration: * + * ``` * @BindingContainer * @ContributesTo(Scope::class) - * abstract class YourNodeModule { - - * @Binds - * @IntoMap - * @NodeKey(YourNode::class) - * abstract fun bindYourNodeFactory(factory: YourNode.Factory): AssistedNodeFactory<*> - *} - + * interface YourNodeBindingContainer { + * @Binds + * @IntoMap + * @NodeKey(YourNode::class) + * fun bindYourNodeAssistedFactory(factory: YourNodeAssistedFactory): AssistedNodeFactory<*> + * } + * ``` */ @Target(AnnotationTarget.CLASS) annotation class ContributesNode( diff --git a/app/build.gradle.kts b/app/build.gradle.kts index ecd5ed8e7b..f85d8dc33c 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -127,24 +127,11 @@ android { optimization { enable = true keepRules { - files.add(File(projectDir, "common-proguard-rules.pro")) - files.add(getDefaultProguardFile("proguard-android-optimize.txt")) - - // Depending on whether the app flavor is enterprise or not we want to use different proguard rules. - val flavorProguardFile = if (isEnterpriseBuild) { - // Custom rules for enterprise builds - File(projectDir, "enterprise-proguard-rules.pro") - } else { - // These default rules prevent the OSS app from being obfuscated - File(projectDir, "default-proguard-rules.pro") - } - - if (flavorProguardFile.exists()) { - files.add(flavorProguardFile) - } else { - logger.warn("Proguard file ${flavorProguardFile.absolutePath} does not exist") - } + // Equivalent of adding `getDefaultProguardFile("proguard-android-optimize.txt")` (this is the default value). + includeDefault = true } + // Our custom keep rules are registered as `keepRules` source folders in the `androidComponents` block below, + // as the former `keepRules.files` DSL is deprecated since AGP 9. } } @@ -229,6 +216,30 @@ androidComponents { ) onVariants { variant -> + // Register the R8 keep rules source folders for optimized build types (release, nightly). + // Replaces the deprecated `optimization.keepRules.files` DSL (AGP 9+). + if (variant.buildType != "debug") { + variant.sources.keepRules?.let { keepRules -> + // Common rules, always applied. + keepRules.addStaticSourceDirectory("proguard/common") + + // Depending on whether the app flavor is enterprise or not we want to use different proguard rules. + val flavorProguardDir = if (isEnterpriseBuild) { + // Custom rules for enterprise builds + "../enterprise/proguard" + } else { + // Custom fules for FOSS builds + "proguard/foss" + } + + if (File(projectDir, flavorProguardDir).exists()) { + keepRules.addStaticSourceDirectory(flavorProguardDir) + } else { + logger.warn("Proguard folder ${File(projectDir, flavorProguardDir).absolutePath} does not exist") + } + } + } + // Assigns a different version code for each output APK // other than the universal APK. variant.outputs.forEach { output -> diff --git a/app/common-proguard-rules.pro b/app/proguard/common/common-proguard-rules.keep similarity index 100% rename from app/common-proguard-rules.pro rename to app/proguard/common/common-proguard-rules.keep diff --git a/app/default-proguard-rules.pro b/app/proguard/foss/default-proguard-rules.keep similarity index 100% rename from app/default-proguard-rules.pro rename to app/proguard/foss/default-proguard-rules.keep diff --git a/app/src/main/kotlin/io/element/android/x/di/AppModule.kt b/app/src/main/kotlin/io/element/android/x/di/AppBindingContainer.kt similarity index 87% rename from app/src/main/kotlin/io/element/android/x/di/AppModule.kt rename to app/src/main/kotlin/io/element/android/x/di/AppBindingContainer.kt index 7564db5d95..3f8e94d8ef 100644 --- a/app/src/main/kotlin/io/element/android/x/di/AppModule.kt +++ b/app/src/main/kotlin/io/element/android/x/di/AppBindingContainer.kt @@ -18,7 +18,7 @@ import dev.zacsweers.metro.ContributesTo import dev.zacsweers.metro.Provides import dev.zacsweers.metro.SingleIn import io.element.android.appconfig.ApplicationConfig -import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.features.enterprise.api.IsEnterpriseBuild import io.element.android.libraries.androidutils.system.getVersionCodeFromManifest import io.element.android.libraries.core.coroutine.CoroutineDispatchers import io.element.android.libraries.core.meta.BuildMeta @@ -38,7 +38,7 @@ import java.io.File @BindingContainer @ContributesTo(AppScope::class) -object AppModule { +object AppBindingContainer { @Provides @BaseDirectory fun providesBaseDirectory(@ApplicationContext context: Context): File { @@ -74,17 +74,18 @@ object AppModule { fun providesBuildMeta( @ApplicationContext context: Context, buildType: BuildType, - enterpriseService: EnterpriseService, + isEnterpriseBuild: IsEnterpriseBuild, ): BuildMeta { val applicationName = ApplicationConfig.APPLICATION_NAME.takeIf { it.isNotEmpty() } ?: context.getString(R.string.app_name) + val isEnterprise = isEnterpriseBuild() return BuildMeta( isDebuggable = BuildConfig.DEBUG, buildType = buildType, applicationName = applicationName, - productionApplicationName = if (enterpriseService.isEnterpriseBuild) applicationName else ApplicationConfig.PRODUCTION_APPLICATION_NAME, - desktopApplicationName = if (enterpriseService.isEnterpriseBuild) applicationName else ApplicationConfig.DESKTOP_APPLICATION_NAME, + productionApplicationName = if (isEnterprise) applicationName else ApplicationConfig.PRODUCTION_APPLICATION_NAME, + desktopApplicationName = if (isEnterprise) applicationName else ApplicationConfig.DESKTOP_APPLICATION_NAME, applicationId = BuildConfig.APPLICATION_ID, - isEnterpriseBuild = enterpriseService.isEnterpriseBuild, + isEnterpriseBuild = isEnterprise, // TODO EAx Config.LOW_PRIVACY_LOG_ENABLE, lowPrivacyLoggingEnabled = false, versionName = BuildConfig.VERSION_NAME, @@ -110,7 +111,7 @@ object AppModule { @Provides @SingleIn(AppScope::class) - fun provideSnackbarDispatcher(): SnackbarDispatcher { + fun providesSnackbarDispatcher(): SnackbarDispatcher { return SnackbarDispatcher() } } diff --git a/appconfig/src/main/kotlin/io/element/android/appconfig/PushConfig.kt b/appconfig/src/main/kotlin/io/element/android/appconfig/PushConfig.kt deleted file mode 100644 index d36fb742b0..0000000000 --- a/appconfig/src/main/kotlin/io/element/android/appconfig/PushConfig.kt +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.appconfig - -object PushConfig { - /** - * Note: pusher_app_id cannot exceed 64 chars. - */ - const val PUSHER_APP_ID: String = "im.vector.app.android" -} diff --git a/appconfig/src/main/kotlin/io/element/android/appconfig/RageshakeConfig.kt b/appconfig/src/main/kotlin/io/element/android/appconfig/RageshakeConfig.kt index 6dd2143d95..82d2145ecc 100644 --- a/appconfig/src/main/kotlin/io/element/android/appconfig/RageshakeConfig.kt +++ b/appconfig/src/main/kotlin/io/element/android/appconfig/RageshakeConfig.kt @@ -35,4 +35,11 @@ object RageshakeConfig { * The maximum number of log lines a rageshake can contain. */ const val MAX_LOG_LINES_SIZE = 1_000_000 + + /** + * The maximum size of the description. The bug report server copies it verbatim into a GitHub issue body, + * which GitHub rejects above 65536 characters. The remaining budget is left to the other reported fields, + * mainly the list of the omitted log file names. + */ + const val MAX_DESCRIPTION_SIZE = 40 * 1024 } diff --git a/appnav/build.gradle.kts b/appnav/build.gradle.kts index ce9764360b..12b95d9a09 100644 --- a/appnav/build.gradle.kts +++ b/appnav/build.gradle.kts @@ -44,6 +44,7 @@ dependencies { implementation(projects.libraries.sessionStorage.api) implementation(projects.libraries.uiCommon) implementation(projects.libraries.uiStrings) + implementation(projects.libraries.wellknown.api) implementation(projects.features.login.api) implementation(libs.coil) @@ -60,16 +61,23 @@ dependencies { testCommonDependencies(libs) testImplementation(projects.features.login.test) testImplementation(projects.features.share.test) + testImplementation(projects.libraries.accountselect.test) + testImplementation(projects.libraries.featureflag.test) testImplementation(projects.libraries.matrix.test) + testImplementation(projects.libraries.matrixmedia.test) testImplementation(projects.libraries.oauth.test) testImplementation(projects.libraries.permissions.test) testImplementation(projects.libraries.preferences.test) testImplementation(projects.libraries.push.test) testImplementation(projects.libraries.pushproviders.test) + testImplementation(projects.libraries.sessionStorage.test) + testImplementation(projects.features.announcement.test) testImplementation(projects.features.forward.test) testImplementation(projects.features.messages.test) testImplementation(projects.features.networkmonitor.test) + testImplementation(projects.features.preferences.test) testImplementation(projects.features.rageshake.test) + testImplementation(projects.features.signedout.test) testImplementation(projects.services.apperror.test) testImplementation(projects.services.appnavstate.test) testImplementation(projects.services.analytics.test) diff --git a/appnav/src/main/kotlin/io/element/android/appnav/LoggedInFlowNode.kt b/appnav/src/main/kotlin/io/element/android/appnav/LoggedInFlowNode.kt index 14230d7c5a..dab9b7828c 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/LoggedInFlowNode.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/LoggedInFlowNode.kt @@ -11,8 +11,10 @@ package io.element.android.appnav import android.os.Parcelable import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.lifecycle.lifecycleScope @@ -49,11 +51,13 @@ import io.element.android.compound.colors.SemanticColorsLightDark import io.element.android.features.createroom.api.CreateRoomEntryPoint import io.element.android.features.enterprise.api.EnterpriseService import io.element.android.features.enterprise.api.SessionEnterpriseService +import io.element.android.features.enterprise.api.remoteconfig.CustomMapTilerConfigProvider import io.element.android.features.ftue.api.FtueEntryPoint import io.element.android.features.ftue.api.state.FtueService import io.element.android.features.ftue.api.state.FtueState import io.element.android.features.home.api.HomeEntryPoint import io.element.android.features.linknewdevice.api.LinkNewDeviceEntryPoint +import io.element.android.features.location.api.LocalMapTilerConfig import io.element.android.features.location.api.live.ActiveLiveLocationShareManager import io.element.android.features.networkmonitor.api.NetworkMonitor import io.element.android.features.networkmonitor.api.NetworkStatus @@ -153,6 +157,7 @@ class LoggedInFlowNode( private val analyticsRoomListStateWatcher: AnalyticsRoomListStateWatcher, private val createRoomEntryPoint: CreateRoomEntryPoint, private val activeLiveLocationShareManager: ActiveLiveLocationShareManager, + private val customMapTilerConfigProvider: CustomMapTilerConfigProvider, ) : BaseFlowNode( backstack = BackStack( initialElement = NavTarget.Placeholder, @@ -330,11 +335,11 @@ class LoggedInFlowNode( } NavTarget.Home -> { val callback = object : HomeEntryPoint.Callback { - override fun navigateToRoom(roomId: RoomId, joinedRoom: JoinedRoom?) { + override fun navigateToRoom(roomId: RoomId, eventId: EventId?, joinedRoom: JoinedRoom?) { lifecycleScope.launch { attachRoom( roomIdOrAlias = roomId.toRoomIdOrAlias(), - initialElement = RoomNavigationTarget.Root(joinedRoom = joinedRoom), + initialElement = RoomNavigationTarget.Root(joinedRoom = joinedRoom, eventId = eventId), clearBackstack = false, ) } @@ -677,6 +682,12 @@ class LoggedInFlowNode( val colors by remember { enterpriseService.semanticColorsFlow(sessionId = matrixClient.sessionId) }.collectAsState(SemanticColorsLightDark.default) + + val currentMapTilerConfig = LocalMapTilerConfig.current + val updatedMapTilerConfig by produceState(currentMapTilerConfig) { + value = customMapTilerConfigProvider.get().getOrNull() ?: currentMapTilerConfig + } + ElementThemeApp( appPreferencesStore = appPreferencesStore, featureFlagService = featureFlagService, @@ -684,16 +695,18 @@ class LoggedInFlowNode( compoundDark = colors.dark, buildMeta = buildMeta, ) { - val isOnline by syncService.isOnline.collectAsState() - ConnectivityIndicatorContainer( - isOnline = isOnline, - modifier = modifier, - ) { contentModifier -> - Box(modifier = contentModifier) { - val ftueState by ftueService.state.collectAsState() - BackstackView(transitionHandler = rememberLoggedInFlowTransitionHandler(backstack)) - if (ftueState is FtueState.Complete) { - PermanentChild(permanentNavModel = permanentNavModel, navTarget = NavTarget.LoggedInPermanent) + CompositionLocalProvider(LocalMapTilerConfig provides updatedMapTilerConfig) { + val isOnline by syncService.isOnline.collectAsState() + ConnectivityIndicatorContainer( + isOnline = isOnline, + modifier = modifier, + ) { contentModifier -> + Box(modifier = contentModifier) { + val ftueState by ftueService.state.collectAsState() + BackstackView(transitionHandler = rememberLoggedInFlowTransitionHandler(backstack)) + if (ftueState is FtueState.Complete) { + PermanentChild(permanentNavModel = permanentNavModel, navTarget = NavTarget.LoggedInPermanent) + } } } } diff --git a/appnav/src/main/kotlin/io/element/android/appnav/RootFlowNode.kt b/appnav/src/main/kotlin/io/element/android/appnav/RootFlowNode.kt index acf7b66db9..c9deaeb3b3 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/RootFlowNode.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/RootFlowNode.kt @@ -32,7 +32,6 @@ import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedInject import im.vector.app.features.analytics.plan.JoinedRoom import io.element.android.annotations.ContributesNode -import io.element.android.appnav.di.MatrixSessionCache import io.element.android.appnav.intent.IntentResolver import io.element.android.appnav.intent.ResolvedIntent import io.element.android.appnav.room.RoomFlowNode @@ -40,6 +39,7 @@ import io.element.android.appnav.room.RoomNavigationTarget import io.element.android.appnav.root.RootNavStateFlowFactory import io.element.android.appnav.root.RootPresenter import io.element.android.appnav.root.RootView +import io.element.android.appnav.session.MatrixSessionCache import io.element.android.features.announcement.api.AnnouncementService import io.element.android.features.login.api.LoginParams import io.element.android.features.login.api.accesscontrol.AccountProviderAccessControl @@ -109,6 +109,13 @@ class RootFlowNode( buildContext = buildContext, plugins = plugins ) { + /** + * Login params coming from a launch or new [Intent], waiting to be consumed by the not logged in flow. + * Kept here so that the root nav target can be computed from both the logged in state and the pending + * login params, whatever the order in which the intent and the first nav state emission are processed. + */ + private var pendingLoginParams: LoginParams? = null + override fun onBuilt() { analyticsColdStartWatcher.start() appCoroutineScope.launch { @@ -152,7 +159,7 @@ class RootFlowNode( } } LoggedInState.NotLoggedIn -> { - switchToNotLoggedInFlow(null) + switchToNotLoggedInFlow(pendingLoginParams) } } } @@ -194,15 +201,18 @@ class RootFlowNode( } private fun switchToLoggedInFlow(sessionId: SessionId, navId: Int) { + pendingLoginParams = null backstack.safeRoot(NavTarget.LoggedInFlow(sessionId, navId)) } private fun switchToNotLoggedInFlow(params: LoginParams?) { + Timber.d("switchToNotLoggedInFlow, hasLoginParams=${params != null}") matrixSessionCache.removeAll() backstack.safeRoot(NavTarget.NotLoggedInFlow(params)) } private fun switchToSignedOutFlow(sessionId: SessionId) { + pendingLoginParams = null backstack.safeRoot(NavTarget.SignedOutFlow(sessionId)) } @@ -319,6 +329,7 @@ class RootFlowNode( } override fun onDone() { + pendingLoginParams = null backstack.pop() } } @@ -418,6 +429,7 @@ class RootFlowNode( Timber.w("Login link ignored, multi account is disabled") } } else { + pendingLoginParams = params switchToNotLoggedInFlow(params) } } else { diff --git a/appnav/src/main/kotlin/io/element/android/appnav/intent/IntentResolver.kt b/appnav/src/main/kotlin/io/element/android/appnav/intent/IntentResolver.kt index ee316f00aa..5d3a85fa9a 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/intent/IntentResolver.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/intent/IntentResolver.kt @@ -76,6 +76,7 @@ class IntentResolver( } private fun Intent.canBeIgnored(): Boolean { + if (flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0) return true return action == Intent.ACTION_MAIN && categories?.contains(Intent.CATEGORY_LAUNCHER) == true } diff --git a/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInPresenter.kt b/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInPresenter.kt index 0723ad4606..5cd3efa801 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInPresenter.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInPresenter.kt @@ -120,6 +120,12 @@ class LoggedInPresenter( }.launchIn(this) } + LaunchedEffect(Unit) { + // Keep automatic call status (m.call) in sync with homeserver support. + val enabled = matrixClient.isUserStatusSupported().getOrDefault(false) + matrixClient.enableAutomaticCallStatus(enabled) + } + val networkConnectivity by networkMonitor.connectivity.collectAsState() LaunchedEffect(networkConnectivity) { if (networkConnectivity == NetworkStatus.Connected) { diff --git a/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInStateProvider.kt b/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInStatePreviewParam.kt similarity index 95% rename from appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInStateProvider.kt rename to appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInStatePreviewParam.kt index 67fcb95c2c..b479e00279 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInStateProvider.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.permissions.api.localnetwork.LocalNetworkPermissionDialog import io.element.android.libraries.push.api.PusherRegistrationFailure -open class LoggedInStateProvider : PreviewParameterProvider { +open class LoggedInStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLoggedInState(), diff --git a/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInView.kt b/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInView.kt index e57d378da4..7e607e7d92 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInView.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/loggedin/LoggedInView.kt @@ -124,7 +124,7 @@ private fun ForceNativeSlidingSyncMigrationDialog( @PreviewsDayNight @Composable -internal fun LoggedInViewPreview(@PreviewParameter(LoggedInStateProvider::class) state: LoggedInState) = ElementPreview { +internal fun LoggedInViewPreview(@PreviewParameter(LoggedInStatePreviewParam::class) state: LoggedInState) = ElementPreview { LoggedInView( state = state, navigateToNotificationTroubleshoot = {}, diff --git a/appnav/src/main/kotlin/io/element/android/appnav/room/joined/LoadingRoomNodeView.kt b/appnav/src/main/kotlin/io/element/android/appnav/room/joined/LoadingRoomNodeView.kt index a596052fca..175b662e08 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/room/joined/LoadingRoomNodeView.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/room/joined/LoadingRoomNodeView.kt @@ -29,7 +29,7 @@ import io.element.android.libraries.designsystem.theme.components.Text import io.element.android.libraries.designsystem.theme.components.TopAppBar import io.element.android.libraries.designsystem.utils.DelayedVisibility import io.element.android.libraries.matrix.ui.room.LoadingRoomState -import io.element.android.libraries.matrix.ui.room.LoadingRoomStateProvider +import io.element.android.libraries.matrix.ui.room.LoadingRoomStatePreviewParam import io.element.android.libraries.ui.strings.CommonStrings @Composable @@ -84,7 +84,7 @@ private fun LoadingRoomTopBar( @PreviewsDayNight @Composable -internal fun LoadingRoomNodeViewPreview(@PreviewParameter(LoadingRoomStateProvider::class) state: LoadingRoomState) = ElementPreview { +internal fun LoadingRoomNodeViewPreview(@PreviewParameter(LoadingRoomStatePreviewParam::class) state: LoadingRoomState) = ElementPreview { LoadingRoomNodeView( state = state, onBackClick = {} diff --git a/appnav/src/main/kotlin/io/element/android/appnav/root/RootNavStateFlowFactory.kt b/appnav/src/main/kotlin/io/element/android/appnav/root/RootNavStateFlowFactory.kt index 9a91e9765b..8b02752a64 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/root/RootNavStateFlowFactory.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/root/RootNavStateFlowFactory.kt @@ -11,7 +11,7 @@ package io.element.android.appnav.root import com.bumble.appyx.core.state.MutableSavedStateMap import com.bumble.appyx.core.state.SavedStateMap import dev.zacsweers.metro.Inject -import io.element.android.appnav.di.MatrixSessionCache +import io.element.android.appnav.session.MatrixSessionCache import io.element.android.features.preferences.api.CacheService import io.element.android.libraries.matrix.ui.media.ImageLoaderHolder import io.element.android.libraries.preferences.api.store.SessionPreferencesStoreFactory diff --git a/appnav/src/main/kotlin/io/element/android/appnav/root/RootStateProvider.kt b/appnav/src/main/kotlin/io/element/android/appnav/root/RootStatePreviewParam.kt similarity index 95% rename from appnav/src/main/kotlin/io/element/android/appnav/root/RootStateProvider.kt rename to appnav/src/main/kotlin/io/element/android/appnav/root/RootStatePreviewParam.kt index 26db205498..8ae3d261e8 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/root/RootStateProvider.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/root/RootStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.features.rageshake.api.detection.aRageshakeDetectionSt import io.element.android.services.apperror.api.AppErrorState import io.element.android.services.apperror.api.aAppErrorState -open class RootStateProvider : PreviewParameterProvider { +open class RootStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRootState().copy( diff --git a/appnav/src/main/kotlin/io/element/android/appnav/root/RootView.kt b/appnav/src/main/kotlin/io/element/android/appnav/root/RootView.kt index 19aa820433..aa6bcf1a88 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/root/RootView.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/root/RootView.kt @@ -60,7 +60,7 @@ fun RootView( @PreviewsDayNight @Composable -internal fun RootViewPreview(@PreviewParameter(RootStateProvider::class) rootState: RootState) = ElementPreview { +internal fun RootViewPreview(@PreviewParameter(RootStatePreviewParam::class) rootState: RootState) = ElementPreview { RootView( state = rootState, onOpenBugReport = {}, diff --git a/appnav/src/main/kotlin/io/element/android/appnav/di/MatrixSessionCache.kt b/appnav/src/main/kotlin/io/element/android/appnav/session/MatrixSessionCache.kt similarity index 98% rename from appnav/src/main/kotlin/io/element/android/appnav/di/MatrixSessionCache.kt rename to appnav/src/main/kotlin/io/element/android/appnav/session/MatrixSessionCache.kt index 11337f2e0a..ffae5f2b17 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/di/MatrixSessionCache.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/session/MatrixSessionCache.kt @@ -6,7 +6,7 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.appnav.di +package io.element.android.appnav.session import androidx.annotation.VisibleForTesting import com.bumble.appyx.core.state.MutableSavedStateMap @@ -115,7 +115,7 @@ class MatrixSessionCache( private fun onNewMatrixClient(matrixClient: MatrixClient) { val syncOrchestrator = syncOrchestratorFactory.create( - syncService = matrixClient.syncService, + matrixClient = matrixClient, sessionCoroutineScope = matrixClient.sessionCoroutineScope, ) sessionIdsToMatrixSession[matrixClient.sessionId] = InMemoryMatrixSession( diff --git a/appnav/src/main/kotlin/io/element/android/appnav/di/SyncOrchestrator.kt b/appnav/src/main/kotlin/io/element/android/appnav/session/SyncOrchestrator.kt similarity index 91% rename from appnav/src/main/kotlin/io/element/android/appnav/di/SyncOrchestrator.kt rename to appnav/src/main/kotlin/io/element/android/appnav/session/SyncOrchestrator.kt index 1ce423a569..3a72c10ab7 100644 --- a/appnav/src/main/kotlin/io/element/android/appnav/di/SyncOrchestrator.kt +++ b/appnav/src/main/kotlin/io/element/android/appnav/session/SyncOrchestrator.kt @@ -6,7 +6,7 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.appnav.di +package io.element.android.appnav.session import androidx.annotation.VisibleForTesting import dev.zacsweers.metro.Assisted @@ -16,7 +16,7 @@ import io.element.android.features.networkmonitor.api.NetworkMonitor import io.element.android.features.networkmonitor.api.NetworkStatus import io.element.android.libraries.core.coroutine.CoroutineDispatchers import io.element.android.libraries.core.coroutine.childScope -import io.element.android.libraries.matrix.api.sync.SyncService +import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.api.sync.SyncState import io.element.android.services.analytics.api.AnalyticsService import io.element.android.services.analytics.api.recordTransaction @@ -37,7 +37,7 @@ import kotlin.time.Duration.Companion.seconds @AssistedInject class SyncOrchestrator( - @Assisted private val syncService: SyncService, + @Assisted private val matrixClient: MatrixClient, @Assisted sessionCoroutineScope: CoroutineScope, private val appForegroundStateService: AppForegroundStateService, private val networkMonitor: NetworkMonitor, @@ -47,13 +47,15 @@ class SyncOrchestrator( @AssistedFactory interface Factory { fun create( - syncService: SyncService, + matrixClient: MatrixClient, sessionCoroutineScope: CoroutineScope, ): SyncOrchestrator } private val tag = "SyncOrchestrator" + private val syncService = matrixClient.syncService + private val coroutineScope = sessionCoroutineScope.childScope(dispatchers.io, tag) private val started = AtomicBoolean(false) @@ -94,7 +96,7 @@ class SyncOrchestrator( appForegroundStateService.isInCall, appForegroundStateService.isSyncingNotificationEvent, appForegroundStateService.hasRingingCall, - appForegroundStateService.isSharingLiveLocation + appForegroundStateService.isSharingLiveLocation, ) val isAppActiveFlow = combine(isAppActiveFlows) { actives -> actives.any { it } } combine( @@ -103,6 +105,11 @@ class SyncOrchestrator( networkMonitor.connectivity, isAppActiveFlow, ) { syncState, networkState, isAppActive -> + if (matrixClient.isShuttingDown) { + Timber.tag(tag).d("Matrix client is shutting down, no need to start the sync service again") + return@combine SyncStateAction.NoOp + } + val isNetworkAvailable = networkState == NetworkStatus.Connected Timber.tag(tag).d("isAppActive=$isAppActive, isNetworkAvailable=$isNetworkAvailable") diff --git a/appnav/src/main/res/values-ar/translations.xml b/appnav/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..ca3a804097 --- /dev/null +++ b/appnav/src/main/res/values-ar/translations.xml @@ -0,0 +1,6 @@ + + + "تسجيل الخروج والترقية" + "لم يعد %1$s يدعم البروتوكول القديم. يرجى تسجيل الخروج ثم تسجيل الدخول مرة أخرى لمتابعة استخدام التطبيق." + "لم يعد خادمك المنزلي يدعم البروتوكول القديم. يرجى تسجيل الخروج ثم تسجيل الدخول مرة أخرى لمتابعة استخدام التطبيق." + diff --git a/appnav/src/main/res/values-fa/translations.xml b/appnav/src/main/res/values-fa/translations.xml index 16bb7fd3e2..dfff863365 100644 --- a/appnav/src/main/res/values-fa/translations.xml +++ b/appnav/src/main/res/values-fa/translations.xml @@ -2,4 +2,5 @@ "خروج و ارتقا" "‏%1$s دیگر از شیوه‌نامهٔ قدیمی پشتیبانی نمی‌کند. لطفاً برای ادامهٔ استفاده از کاره، خارج شده و دوباره وارد شوید." + "سرور خانگی شما دیگر از پروتکل قدیمی پشتیبانی نمی‌کند. لطفاً برای ادامه استفاده از برنامه، از سیستم خارج شده و دوباره وارد شوید." diff --git a/appnav/src/test/kotlin/io/element/android/appnav/RootFlowNodeTest.kt b/appnav/src/test/kotlin/io/element/android/appnav/RootFlowNodeTest.kt new file mode 100644 index 0000000000..fea30c8019 --- /dev/null +++ b/appnav/src/test/kotlin/io/element/android/appnav/RootFlowNodeTest.kt @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +@file:OptIn(ExperimentalCoroutinesApi::class) + +package io.element.android.appnav + +import android.content.Intent +import android.net.Uri +import androidx.arch.core.executor.testing.InstantTaskExecutorRule +import com.bumble.appyx.core.modality.AncestryInfo +import com.bumble.appyx.core.modality.BuildContext +import com.bumble.appyx.core.node.node +import com.bumble.appyx.navmodel.backstack.activeElement +import com.bumble.appyx.testing.junit4.util.MainDispatcherRule +import com.bumble.appyx.testing.unit.common.helper.parentNodeTestHelper +import com.bumble.appyx.utils.customisations.NodeCustomisationDirectoryImpl +import com.google.common.truth.Truth.assertThat +import io.element.android.appnav.intent.IntentResolver +import io.element.android.appnav.root.RootNavStateFlowFactory +import io.element.android.appnav.root.RootPresenter +import io.element.android.appnav.session.FakeSyncOrchestratorFactory +import io.element.android.appnav.session.MatrixSessionCache +import io.element.android.features.login.api.LoginEntryPoint +import io.element.android.features.login.api.LoginParams +import io.element.android.features.login.test.FakeLoginEntryPoint +import io.element.android.features.login.test.FakeLoginIntentResolver +import io.element.android.features.login.test.accesscontrol.FakeAccountProviderAccessControl +import io.element.android.features.preferences.test.FakeCacheService +import io.element.android.features.rageshake.test.FakeBugReportEntryPoint +import io.element.android.features.rageshake.test.logs.FakeAnnouncementService +import io.element.android.features.share.test.FakeShareIntentHandler +import io.element.android.features.signedout.test.FakeSignedOutEntryPoint +import io.element.android.libraries.accountselect.test.FakeAccountSelectEntryPoint +import io.element.android.libraries.architecture.AssistedNodeFactory +import io.element.android.libraries.featureflag.test.FakeFeatureFlagService +import io.element.android.libraries.matrix.test.FakeSdkMetadata +import io.element.android.libraries.matrix.test.auth.FakeMatrixAuthenticationService +import io.element.android.libraries.matrix.test.permalink.FakePermalinkParser +import io.element.android.libraries.matrix.ui.media.test.FakeImageLoaderHolder +import io.element.android.libraries.oauth.test.FakeOAuthActionFlow +import io.element.android.libraries.oauth.test.FakeOAuthIntentResolver +import io.element.android.libraries.preferences.test.FakeSessionPreferencesStoreFactory +import io.element.android.libraries.sessionstorage.api.SessionStore +import io.element.android.libraries.sessionstorage.test.InMemorySessionStore +import io.element.android.services.analytics.test.FakeAnalyticsService +import io.element.android.services.analytics.test.watchers.FakeAnalyticsColdStartWatcher +import io.element.android.services.apperror.test.FakeAppErrorStateService +import io.element.android.tests.testutils.node.FakeNodeFactoriesBindings +import io.element.android.tests.testutils.node.FakeParentNode +import io.element.android.tests.testutils.presenter.NotUsedPresenter +import io.element.android.tests.testutils.robolectric.RobolectricTest +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.Test + +private const val A_LOGIN_LINK = "https://mobile.element.io/element/?account_provider=example.com&login_hint=mxid:@alice:example.com" + +private val A_LOGIN_PARAMS = LoginParams( + accountProvider = "example.com", + loginHint = "mxid:@alice:example.com", +) + +private val A_LOGIN_ENTRY_POINT_PARAMS = LoginEntryPoint.Params( + accountProvider = A_LOGIN_PARAMS.accountProvider, + loginHint = A_LOGIN_PARAMS.loginHint, +) + +class RootFlowNodeTest : RobolectricTest() { + @get:Rule + val instantTaskExecutorRule = InstantTaskExecutorRule() + + @get:Rule + val mainDispatcherRule = MainDispatcherRule() + + @Test + fun `given no session, when a login link is handled before the nav state is observed, then the login params are kept`() = runTest { + var loginEntryPointParams: LoginEntryPoint.Params? = null + val rootFlowNode = createRootFlowNode( + loginEntryPoint = FakeLoginEntryPoint { buildContext, params -> + loginEntryPointParams = params + node(buildContext) {} + }, + ) + rootFlowNode.parentNodeTestHelper() + // The intent is handled first, this is what happens when the deep link cold starts the app. + rootFlowNode.handleIntent(aLoginIntent()) + assertThat(rootFlowNode.backstack.activeElement).isEqualTo(RootFlowNode.NavTarget.NotLoggedInFlow(A_LOGIN_PARAMS)) + // Then the first nav state emission lands, it must not override the login params. + runCurrent() + assertThat(rootFlowNode.backstack.activeElement).isEqualTo(RootFlowNode.NavTarget.NotLoggedInFlow(A_LOGIN_PARAMS)) + assertThat(loginEntryPointParams).isEqualTo(A_LOGIN_ENTRY_POINT_PARAMS) + } + + @Test + fun `given no session, when a login link is handled after the nav state is observed, then the login params are applied`() = runTest { + var loginEntryPointParams: LoginEntryPoint.Params? = null + val rootFlowNode = createRootFlowNode( + loginEntryPoint = FakeLoginEntryPoint { buildContext, params -> + loginEntryPointParams = params + node(buildContext) {} + }, + ) + rootFlowNode.parentNodeTestHelper() + // The nav state is observed first, this is what happens when the app is already running. + runCurrent() + assertThat(rootFlowNode.backstack.activeElement).isEqualTo(RootFlowNode.NavTarget.NotLoggedInFlow(null)) + rootFlowNode.handleIntent(aLoginIntent()) + runCurrent() + assertThat(rootFlowNode.backstack.activeElement).isEqualTo(RootFlowNode.NavTarget.NotLoggedInFlow(A_LOGIN_PARAMS)) + assertThat(loginEntryPointParams).isEqualTo(A_LOGIN_ENTRY_POINT_PARAMS) + } + + private fun aLoginIntent() = Intent(Intent.ACTION_VIEW, Uri.parse(A_LOGIN_LINK)) + + private fun TestScope.createRootFlowNode( + loginEntryPoint: LoginEntryPoint, + sessionStore: SessionStore = InMemorySessionStore(), + ): RootFlowNode { + val matrixSessionCache = MatrixSessionCache( + authenticationService = FakeMatrixAuthenticationService(), + syncOrchestratorFactory = FakeSyncOrchestratorFactory(), + analyticsService = FakeAnalyticsService(), + ) + val parentNode = FakeParentNode( + graph = FakeNodeFactoriesBindings( + mapOf( + NotLoggedInFlowNode::class to AssistedNodeFactory { buildContext, plugins -> + NotLoggedInFlowNode( + buildContext = buildContext, + plugins = plugins, + loginEntryPoint = loginEntryPoint, + imageLoaderHolder = FakeImageLoaderHolder(), + analyticsColdStartWatcher = FakeAnalyticsColdStartWatcher(), + ) + } + ) + ) + ) + return RootFlowNode( + buildContext = BuildContext( + ancestryInfo = AncestryInfo.Child(anchor = parentNode), + savedStateMap = null, + customisations = NodeCustomisationDirectoryImpl(), + ), + plugins = emptyList(), + sessionStore = sessionStore, + accountProviderAccessControl = FakeAccountProviderAccessControl { true }, + navStateFlowFactory = RootNavStateFlowFactory( + sessionStore = sessionStore, + cacheService = FakeCacheService(), + matrixSessionCache = matrixSessionCache, + imageLoaderHolder = FakeImageLoaderHolder(), + sessionPreferencesStoreFactory = FakeSessionPreferencesStoreFactory(), + ), + matrixSessionCache = matrixSessionCache, + presenter = RootPresenter( + crashDetectionPresenter = NotUsedPresenter(), + rageshakeDetectionPresenter = NotUsedPresenter(), + appErrorStateService = FakeAppErrorStateService(), + analyticsService = FakeAnalyticsService(), + sdkMetadata = FakeSdkMetadata("sha"), + ), + bugReportEntryPoint = FakeBugReportEntryPoint(), + signedOutEntryPoint = FakeSignedOutEntryPoint(), + accountSelectEntryPoint = FakeAccountSelectEntryPoint(), + intentResolver = IntentResolver( + deeplinkParser = { null }, + loginIntentResolver = FakeLoginIntentResolver { A_LOGIN_PARAMS }, + oAuthIntentResolver = FakeOAuthIntentResolver { null }, + permalinkParser = FakePermalinkParser(), + shareIntentHandler = FakeShareIntentHandler(), + ), + oAuthActionFlow = FakeOAuthActionFlow(), + featureFlagService = FakeFeatureFlagService(), + announcementService = FakeAnnouncementService(), + analyticsService = FakeAnalyticsService(), + analyticsColdStartWatcher = FakeAnalyticsColdStartWatcher(), + appCoroutineScope = backgroundScope, + ) + } +} diff --git a/appnav/src/test/kotlin/io/element/android/appnav/SyncOrchestratorTest.kt b/appnav/src/test/kotlin/io/element/android/appnav/SyncOrchestratorTest.kt index 7309ca6ac2..32d0ec8f56 100644 --- a/appnav/src/test/kotlin/io/element/android/appnav/SyncOrchestratorTest.kt +++ b/appnav/src/test/kotlin/io/element/android/appnav/SyncOrchestratorTest.kt @@ -8,10 +8,11 @@ package io.element.android.appnav -import io.element.android.appnav.di.SyncOrchestrator +import io.element.android.appnav.session.SyncOrchestrator import io.element.android.features.networkmonitor.api.NetworkStatus import io.element.android.features.networkmonitor.test.FakeNetworkMonitor import io.element.android.libraries.matrix.api.sync.SyncState +import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.libraries.matrix.test.sync.FakeSyncService import io.element.android.services.analytics.test.FakeAnalyticsService import io.element.android.services.appnavstate.test.FakeAppForegroundStateService @@ -40,7 +41,7 @@ class SyncOrchestratorTest { } val networkMonitor = FakeNetworkMonitor(initialStatus = NetworkStatus.Disconnected) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, ) @@ -60,7 +61,7 @@ class SyncOrchestratorTest { } val networkMonitor = FakeNetworkMonitor(initialStatus = NetworkStatus.Connected) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, ) @@ -85,7 +86,7 @@ class SyncOrchestratorTest { val networkMonitor = FakeNetworkMonitor(initialStatus = NetworkStatus.Connected) val appForegroundStateService = FakeAppForegroundStateService(initialForegroundValue = true) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, ) @@ -117,7 +118,7 @@ class SyncOrchestratorTest { val networkMonitor = FakeNetworkMonitor(initialStatus = NetworkStatus.Connected) val appForegroundStateService = FakeAppForegroundStateService(initialForegroundValue = true) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, ) @@ -165,7 +166,7 @@ class SyncOrchestratorTest { initialIsSyncingNotificationEventValue = false, ) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, ) @@ -208,7 +209,7 @@ class SyncOrchestratorTest { initialIsSyncingNotificationEventValue = false, ) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, ) @@ -252,7 +253,7 @@ class SyncOrchestratorTest { initialHasRingingCall = false, ) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, ) @@ -296,7 +297,7 @@ class SyncOrchestratorTest { initialIsInCallValue = true, ) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, ) @@ -339,7 +340,7 @@ class SyncOrchestratorTest { initialIsInCallValue = false, ) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, ) @@ -369,7 +370,7 @@ class SyncOrchestratorTest { } val networkMonitor = FakeNetworkMonitor(initialStatus = NetworkStatus.Disconnected) val syncOrchestrator = createSyncOrchestrator( - syncService = syncService, + matrixClient = FakeMatrixClient(syncService = syncService), networkMonitor = networkMonitor, ) @@ -381,12 +382,44 @@ class SyncOrchestratorTest { startSyncRecorder.assertions().isNeverCalled() } + @Test + fun `when the client is shutting down, the orchestrator does nothing`() = runTest { + val networkMonitor = FakeNetworkMonitor(initialStatus = NetworkStatus.Disconnected) + val appForegroundStateService = FakeAppForegroundStateService( + initialForegroundValue = false, + initialIsSyncingNotificationEventValue = false, + initialIsInCallValue = false, + ) + + val startSyncRecorder = lambdaRecorder> { Result.success(Unit) } + val syncService = FakeSyncService(initialSyncState = SyncState.Idle).apply { + startSyncLambda = startSyncRecorder + } + val syncOrchestrator = createSyncOrchestrator( + matrixClient = FakeMatrixClient(syncService = syncService, isShuttingDownResult = { true }), + networkMonitor = networkMonitor, + appForegroundStateService = appForegroundStateService, + ) + + // We start observing + syncOrchestrator.observeStates() + + // These should still not trigger a sync, sync the client is shutting down + networkMonitor.givenNetworkBlocked(false) + appForegroundStateService.updateIsInCallState(true) + appForegroundStateService.isInForeground.value = true + + advanceTimeBy(10.seconds) + + startSyncRecorder.assertions().isNeverCalled() + } + private fun TestScope.createSyncOrchestrator( - syncService: FakeSyncService = FakeSyncService(), + matrixClient: FakeMatrixClient = FakeMatrixClient(), networkMonitor: FakeNetworkMonitor = FakeNetworkMonitor(), appForegroundStateService: FakeAppForegroundStateService = FakeAppForegroundStateService(), ) = SyncOrchestrator( - syncService = syncService, + matrixClient = matrixClient, sessionCoroutineScope = backgroundScope, networkMonitor = networkMonitor, appForegroundStateService = appForegroundStateService, diff --git a/appnav/src/test/kotlin/io/element/android/appnav/intent/IntentResolverTest.kt b/appnav/src/test/kotlin/io/element/android/appnav/intent/IntentResolverTest.kt index 841f79678b..ddeae41a78 100644 --- a/appnav/src/test/kotlin/io/element/android/appnav/intent/IntentResolverTest.kt +++ b/appnav/src/test/kotlin/io/element/android/appnav/intent/IntentResolverTest.kt @@ -45,6 +45,24 @@ class IntentResolverTest : RobolectricTest() { assertThat(result).isNull() } + @Test + fun `resolve intent replayed from the history should return null`() { + val sut = createIntentResolver( + deeplinkParserResult = DeeplinkData.Room( + sessionId = A_SESSION_ID, + roomId = A_ROOM_ID, + threadId = null, + eventId = null, + ) + ) + val intent = Intent(RuntimeEnvironment.getApplication(), Activity::class.java).apply { + action = Intent.ACTION_VIEW + addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) + } + val result = sut.resolve(intent) + assertThat(result).isNull() + } + @Test fun `test resolve navigation intent root`() { val sut = createIntentResolver( diff --git a/appnav/src/test/kotlin/io/element/android/appnav/loggedin/LoggedInPresenterTest.kt b/appnav/src/test/kotlin/io/element/android/appnav/loggedin/LoggedInPresenterTest.kt index faa19d9e61..0e2d459d1e 100644 --- a/appnav/src/test/kotlin/io/element/android/appnav/loggedin/LoggedInPresenterTest.kt +++ b/appnav/src/test/kotlin/io/element/android/appnav/loggedin/LoggedInPresenterTest.kt @@ -48,6 +48,7 @@ import io.element.android.services.analytics.api.AnalyticsService import io.element.android.services.analytics.test.FakeAnalyticsService import io.element.android.tests.testutils.WarmUpRule import io.element.android.tests.testutils.consumeItemsUntilPredicate +import io.element.android.tests.testutils.lambda.assert import io.element.android.tests.testutils.lambda.lambdaError import io.element.android.tests.testutils.lambda.lambdaRecorder import io.element.android.tests.testutils.lambda.value @@ -346,6 +347,44 @@ class LoggedInPresenterTest { } } + @Test + fun `present - does not enable automatic call status when server does not support it`() = runTest { + val enableAutomaticCallStatusLambda = lambdaRecorder { } + val matrixClient = FakeMatrixClient( + accountManagementUrlResult = { Result.success(null) }, + enableAutomaticCallStatusLambda = enableAutomaticCallStatusLambda, + ).apply { + isUserStatusSupportedResult = Result.success(false) + } + createLoggedInPresenter( + matrixClient = matrixClient, + ).test { + cancelAndConsumeRemainingEvents() + assert(enableAutomaticCallStatusLambda) + .isCalledOnce() + .with(value(false)) + } + } + + @Test + fun `present - enables automatic call status when server supports it`() = runTest { + val enableAutomaticCallStatusLambda = lambdaRecorder { } + val matrixClient = FakeMatrixClient( + accountManagementUrlResult = { Result.success(null) }, + enableAutomaticCallStatusLambda = enableAutomaticCallStatusLambda, + ).apply { + isUserStatusSupportedResult = Result.success(true) + } + createLoggedInPresenter( + matrixClient = matrixClient, + ).test { + cancelAndConsumeRemainingEvents() + assert(enableAutomaticCallStatusLambda) + .isCalledOnce() + .with(value(true)) + } + } + private suspend fun ReceiveTurbine.awaitFirstItem(): T { skipItems(1) return awaitItem() diff --git a/appnav/src/test/kotlin/io/element/android/appnav/session/FakeSyncOrchestratorFactory.kt b/appnav/src/test/kotlin/io/element/android/appnav/session/FakeSyncOrchestratorFactory.kt new file mode 100644 index 0000000000..586c8f0804 --- /dev/null +++ b/appnav/src/test/kotlin/io/element/android/appnav/session/FakeSyncOrchestratorFactory.kt @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.appnav.session + +import io.element.android.libraries.matrix.api.MatrixClient +import io.element.android.tests.testutils.lambda.lambdaError +import kotlinx.coroutines.CoroutineScope + +class FakeSyncOrchestratorFactory : SyncOrchestrator.Factory { + override fun create( + matrixClient: MatrixClient, + sessionCoroutineScope: CoroutineScope, + ): SyncOrchestrator = lambdaError() +} diff --git a/appnav/src/test/kotlin/io/element/android/appnav/di/MatrixSessionCacheTest.kt b/appnav/src/test/kotlin/io/element/android/appnav/session/MatrixSessionCacheTest.kt similarity index 97% rename from appnav/src/test/kotlin/io/element/android/appnav/di/MatrixSessionCacheTest.kt rename to appnav/src/test/kotlin/io/element/android/appnav/session/MatrixSessionCacheTest.kt index 36fa471dd0..bf315ddb01 100644 --- a/appnav/src/test/kotlin/io/element/android/appnav/di/MatrixSessionCacheTest.kt +++ b/appnav/src/test/kotlin/io/element/android/appnav/session/MatrixSessionCacheTest.kt @@ -6,12 +6,12 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.appnav.di +package io.element.android.appnav.session import com.bumble.appyx.core.state.MutableSavedStateMapImpl import com.google.common.truth.Truth.assertThat import io.element.android.features.networkmonitor.test.FakeNetworkMonitor -import io.element.android.libraries.matrix.api.sync.SyncService +import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.test.A_SESSION_ID import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.libraries.matrix.test.auth.FakeMatrixAuthenticationService @@ -138,11 +138,11 @@ class MatrixSessionCacheTest { return object : SyncOrchestrator.Factory { override fun create( - syncService: SyncService, + matrixClient: MatrixClient, sessionCoroutineScope: CoroutineScope, ): SyncOrchestrator { return SyncOrchestrator( - syncService = syncService, + matrixClient = matrixClient, sessionCoroutineScope = sessionCoroutineScope, appForegroundStateService = FakeAppForegroundStateService(), networkMonitor = FakeNetworkMonitor(), diff --git a/build.gradle.kts b/build.gradle.kts index 0e0df9dbc6..6bbc568c66 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -98,7 +98,7 @@ allprojects { // This is disabled by default, but the CI will enforce this. // You can override by passing `-PallWarningsAsErrors=true` in the command line // Or add a line with "allWarningsAsErrors=true" in your ~/.gradle/gradle.properties file - allWarningsAsErrors = project.properties["allWarningsAsErrors"] == "true" + allWarningsAsErrors = findProperty("allWarningsAsErrors") == "true" // Uncomment to suppress Compose Kotlin compiler compatibility warning // freeCompilerArgs.addAll(listOf("-P", "plugin:androidx.compose.compiler.plugins.kotlin:suppressKotlinVersionCompatibilityCheck=true")) diff --git a/codegen/build.gradle.kts b/codegen/build.gradle.kts index 5c71c170bf..396ef665eb 100644 --- a/codegen/build.gradle.kts +++ b/codegen/build.gradle.kts @@ -1,3 +1,5 @@ +import org.sonarqube.gradle.SonarResolverTask + /* * Copyright (c) 2025 Element Creations Ltd. * Copyright 2022-2025 New Vector Ltd. @@ -18,3 +20,9 @@ dependencies { implementation(libs.ksp.plugin) implementation(libs.kotlinpoet.ksp) } + +// Ensure that the processResources task is executed before the SonarResolverTask to avoid issues with missing resources during SonarQube analysis. +// This *should not be necesssary* but is a workaround for a known issue with the SonarQube Gradle plugin. +tasks.withType().configureEach { + dependsOn("processResources") +} diff --git a/codegen/src/main/kotlin/io/element/android/codegen/ContributesNodeProcessor.kt b/codegen/src/main/kotlin/io/element/android/codegen/ContributesNodeProcessor.kt index 8b537a53fe..3e6c05ad01 100644 --- a/codegen/src/main/kotlin/io/element/android/codegen/ContributesNodeProcessor.kt +++ b/codegen/src/main/kotlin/io/element/android/codegen/ContributesNodeProcessor.kt @@ -61,32 +61,32 @@ class ContributesNodeProcessor( if (config.enableLogging) { logger.warn("Processing ${ksClass.qualifiedName?.asString()}") } - generateModule(ksClass) + generateBindingContainer(ksClass) generateFactory(ksClass) } return invalidSymbols } - private fun generateModule(ksClass: KSClassDeclaration) { + private fun generateBindingContainer(ksClass: KSClassDeclaration) { val annotation = ksClass.annotations.find { it.shortName.asString() == "ContributesNode" }!! val scope = annotation.arguments.find { it.name?.asString() == "scope" }!!.value as KSType - val modulePackage = ksClass.packageName.asString() - val moduleClassName = "${ksClass.simpleName.asString()}_Module" + val bindingContainerPackage = ksClass.packageName.asString() + val bindingContainerClassName = "${ksClass.simpleName.asString()}BindingContainer" val nodeClassName = ClassName.bestGuess(ksClass.qualifiedName!!.asString()) val content = FileSpec.builder( - packageName = modulePackage, - fileName = moduleClassName, + packageName = bindingContainerPackage, + fileName = bindingContainerClassName, ) .addType( - TypeSpec.interfaceBuilder(moduleClassName) + TypeSpec.interfaceBuilder(bindingContainerClassName) .addAnnotation(AnnotationSpec.builder(Origin::class).addMember(CLASS_PLACEHOLDER, nodeClassName).build()) .addAnnotation(BindingContainer::class) .addAnnotation(AnnotationSpec.builder(ContributesTo::class).addMember(CLASS_PLACEHOLDER, scope.toTypeName()).build()) .addFunction( - FunSpec.builder("bind${ksClass.simpleName.asString()}Factory") + FunSpec.builder("bind${ksClass.simpleName.asString()}AssistedFactory") .addModifiers(KModifier.ABSTRACT) - .addParameter("factory", ClassName(modulePackage, "${ksClass.simpleName.asString()}_AssistedFactory")) + .addParameter("factory", ClassName(bindingContainerPackage, "${ksClass.simpleName.asString()}AssistedFactory")) .returns(ClassName.bestGuess(assistedNodeFactoryFqName.asString()).parameterizedBy(STAR)) .addAnnotation(Binds::class) .addAnnotation(IntoMap::class) @@ -114,7 +114,7 @@ class ContributesNodeProcessor( @OptIn(KspExperimental::class) private fun generateFactory(ksClass: KSClassDeclaration) { val generatedPackage = ksClass.packageName.asString() - val assistedFactoryClassName = "${ksClass.simpleName.asString()}_AssistedFactory" + val assistedFactoryClassName = "${ksClass.simpleName.asString()}AssistedFactory" val constructor = ksClass.getConstructors().first { it.parameters.isNotEmpty() } val assistedParameters = constructor.parameters.filter { it.isAnnotationPresent(Assisted::class) } if (assistedParameters.size != 2) { diff --git a/docs/_developer_onboarding.md b/docs/_developer_onboarding.md index 74020ead98..e7515eb466 100644 --- a/docs/_developer_onboarding.md +++ b/docs/_developer_onboarding.md @@ -303,6 +303,8 @@ Follow these steps to install and configure the plugin and templates: - Click on OK 4. Configure generate-module-from-template plugin : - Navigate to AS/Settings/Tools/Module Template Settings + - If a `FeatureModule` template is already listed, select it and remove it, since the plugin keeps its own copy of the + imported template and will not pick up changes made to `FeatureModule.json` on its own - Click on + / Import From File - Pick the `tools/templates/FeatureModule.json` @@ -320,9 +322,11 @@ Example for a new feature called RoomDetails: 4. Verify that the structure looks ok and click on Finish 5. The modules api/impl should be created under `features/roomdetails` directory. 6. Sync project with Gradle so the modules are recognized (no need to add them to settings.gradle). -7. You can now add more Presentation classes (Events, State, StateProvider, View, Presenter) in the impl module with the `Template Presentation Classes`. - To use it, just right click on the package where you want to generate classes, and click on `Template Presentation Classes`. - Fill the text field with the base name of the classes, ie `RootRoomDetails` in the `root` package. +7. You can now add more Presentation classes (Events, State, StatePreviewParam, View, Presenter) in the impl module with the `Template Presentation Classes`. + To use it, just right click on the package where you want to generate classes, and click on `New` / `Template Presentation Classes`. + Fill the text field with the base name of the classes: the generated files are `Event.kt`, `State.kt`, + `StatePreviewParam.kt`, `Presenter.kt`, `Node.kt` and `View.kt`. For instance + `PreferencesRoot` in the `features/preferences/impl/root` package. Note that naming of files and classes is important, since those names are used to set up code coverage rules. For instance, presenters MUST have a @@ -356,9 +360,9 @@ We have 3 tests frameworks in place, and this should be sufficient to guarantee - Maestro to test the global usage of the application. See the related [documentation](../.maestro/README.md). - Combination of [Showkase](https://github.com/airbnb/Showkase) and [Paparazzi](https://github.com/cashapp/paparazzi), to test UI pixel perfect. To add test, just add `@Preview` for the composable you are adding. See the related [documentation](screenshot_testing.md) and see in the template the - file [TemplateView.kt](../features/template/src/main/kotlin/io/element/android/features/template/TemplateView.kt). We create PreviewProvider to provide + file [TemplateView.kt](../features/template/src/main/kotlin/io/element/android/features/template/TemplateView.kt). We create PreviewParam classes to provide different states. See for instance the - file [TemplateStateProvider.kt](../features/template/src/main/kotlin/io/element/android/features/template/TemplateStateProvider.kt) + file [TemplateStatePreviewParam.kt](../features/template/src/main/kotlin/io/element/android/features/template/TemplateStatePreviewParam.kt) - Tests on presenter with [Molecule](https://github.com/cashapp/molecule) and [Turbine](https://github.com/cashapp/turbine). See in the template the class [TemplatePresenterTests](../features/template/src/test/kotlin/io/element/android/features/template/TemplatePresenterTests.kt). **Note** For now we want to avoid using class mocking (with library such as *mockk*), because this should be not necessary. We prefer to create Fake diff --git a/docs/oauth.md b/docs/oauth.md index 1080c64b0e..8cce5abc91 100644 --- a/docs/oauth.md +++ b/docs/oauth.md @@ -6,8 +6,6 @@ Rust sdk branch: https://github.com/matrix-org/matrix-rust-sdk/tree/oidc-ffi Figma https://www.figma.com/file/o9p34zmiuEpZRyvZXJZAYL/FTUE?node-id=133-5426&t=yQXKeANatk6keoZF-0 -Server list: https://github.com/element-hq/oidc-playground - Metadata iOS: (from https://github.com/element-hq/element-x-ios/blob/5f9d07377cebc4f21d9668b1a25f6e3bb22f64a1/ElementX/Sources/Services/Authentication/AuthenticationServiceProxy.swift#L28) clientName: InfoPlistReader.main.bundleDisplayName, diff --git a/enterprise b/enterprise index 029db99513..e633a343b1 160000 --- a/enterprise +++ b/enterprise @@ -1 +1 @@ -Subproject commit 029db99513d569b715ad3bb24145b3c2ac9c14cc +Subproject commit e633a343b12088b1fe3fd6b27ec319c1f7f2931c diff --git a/fastlane/metadata/android/en-US/changelogs/202608010.txt b/fastlane/metadata/android/en-US/changelogs/202608010.txt new file mode 100644 index 0000000000..a4b397f1bb --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/202608010.txt @@ -0,0 +1,2 @@ +Main changes in this version: bug fixes and improvements. +Full changelog: https://github.com/element-hq/element-x-android/releases \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/202608020.txt b/fastlane/metadata/android/en-US/changelogs/202608020.txt new file mode 100644 index 0000000000..a4b397f1bb --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/202608020.txt @@ -0,0 +1,2 @@ +Main changes in this version: bug fixes and improvements. +Full changelog: https://github.com/element-hq/element-x-android/releases \ No newline at end of file diff --git a/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesStateProvider.kt b/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesStatePreviewParam.kt similarity index 89% rename from features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesStateProvider.kt rename to features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesStatePreviewParam.kt index 02e07a86a2..89d19ebac8 100644 --- a/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesStateProvider.kt +++ b/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.analytics.api.preferences import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class AnalyticsPreferencesStateProvider : PreviewParameterProvider { +open class AnalyticsPreferencesStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aAnalyticsPreferencesState().copy(isEnabled = true), diff --git a/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesView.kt b/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesView.kt index 1158b57673..0d141e5ed2 100644 --- a/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesView.kt +++ b/features/analytics/api/src/main/kotlin/io/element/android/features/analytics/api/preferences/AnalyticsPreferencesView.kt @@ -66,7 +66,7 @@ fun AnalyticsPreferencesView( @PreviewsDayNight @Composable -internal fun AnalyticsPreferencesViewPreview(@PreviewParameter(AnalyticsPreferencesStateProvider::class) state: AnalyticsPreferencesState) = +internal fun AnalyticsPreferencesViewPreview(@PreviewParameter(AnalyticsPreferencesStatePreviewParam::class) state: AnalyticsPreferencesState) = ElementPreview { AnalyticsPreferencesView( state = state, diff --git a/features/analytics/api/src/main/res/values-ar/translations.xml b/features/analytics/api/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..449a0a01cb --- /dev/null +++ b/features/analytics/api/src/main/res/values-ar/translations.xml @@ -0,0 +1,7 @@ + + + "مشاركة بيانات استخدام مجهولة لمساعدتنا على تتبع المشاكل." + "يمكنك قراءة كافة شروطنا %1$s." + "هنا" + "مشاركة البيانات الإحصائية" + diff --git a/features/analytics/api/src/main/res/values-pl/translations.xml b/features/analytics/api/src/main/res/values-pl/translations.xml index a3347582cc..37848b4c3f 100644 --- a/features/analytics/api/src/main/res/values-pl/translations.xml +++ b/features/analytics/api/src/main/res/values-pl/translations.xml @@ -1,6 +1,6 @@ - "Udostępniaj anonimowe dane użytkowania, aby pomóc nam identyfikować problemy." + "Udostępniaj anonimowe dane użytkowania, aby pomóc nam ulepszać aplikację." "Przeczytaj nasze warunki użytkowania %1$s." "tutaj" "Udostępniaj dane analityczne" diff --git a/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInStateProvider.kt b/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInStatePreviewParam.kt similarity index 88% rename from features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInStateProvider.kt rename to features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInStatePreviewParam.kt index 30a396c178..960abb7216 100644 --- a/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInStateProvider.kt +++ b/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.analytics.impl import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class AnalyticsOptInStateProvider : PreviewParameterProvider { +open class AnalyticsOptInStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aAnalyticsOptInState(), diff --git a/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInView.kt b/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInView.kt index c05edd825c..678d28c5c9 100644 --- a/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInView.kt +++ b/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/AnalyticsOptInView.kt @@ -171,7 +171,7 @@ private fun AnalyticsOptInFooter( @PreviewsDayNight @Composable -internal fun AnalyticsOptInViewPreview(@PreviewParameter(AnalyticsOptInStateProvider::class) state: AnalyticsOptInState) = ElementPreview { +internal fun AnalyticsOptInViewPreview(@PreviewParameter(AnalyticsOptInStatePreviewParam::class) state: AnalyticsOptInState) = ElementPreview { AnalyticsOptInView( state = state, onClickTerms = {}, diff --git a/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/di/AnalyticsModule.kt b/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/di/AnalyticsBindingContainer.kt similarity index 95% rename from features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/di/AnalyticsModule.kt rename to features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/di/AnalyticsBindingContainer.kt index 32a3d5826a..a4c2c68670 100644 --- a/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/di/AnalyticsModule.kt +++ b/features/analytics/impl/src/main/kotlin/io/element/android/features/analytics/impl/di/AnalyticsBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.architecture.Presenter @ContributesTo(AppScope::class) @BindingContainer -interface AnalyticsModule { +interface AnalyticsBindingContainer { @Binds fun bindAnalyticsPreferencesPresenter(presenter: AnalyticsPreferencesPresenter): Presenter } diff --git a/features/analytics/impl/src/main/res/values-ar/translations.xml b/features/analytics/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..8d1bf460d6 --- /dev/null +++ b/features/analytics/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,10 @@ + + + "لن نسجّل أو ننشئ ملفات شخصية لأي معلومات شخصية" + "مشاركة بيانات استخدام مجهولة لمساعدتنا على تتبع المشاكل." + "يمكنك قراءة كافة شروطنا %1$s." + "هنا" + "يمكنك إطفاء هذا الخيار في أي وقت" + "لن نشارك بياناتك مع أطراف ثالثة" + "ساعدنا على التحسن %1$s" + diff --git a/features/analytics/impl/src/main/res/values-pl/translations.xml b/features/analytics/impl/src/main/res/values-pl/translations.xml index 61da8408ad..c58d630ce9 100644 --- a/features/analytics/impl/src/main/res/values-pl/translations.xml +++ b/features/analytics/impl/src/main/res/values-pl/translations.xml @@ -1,7 +1,7 @@ "Nie będziemy rejestrować ani profilować żadnych danych osobistych" - "Udostępniaj anonimowe dane użytkowania, aby pomóc nam identyfikować problemy." + "Udostępniaj anonimowe dane użytkowania, aby pomóc nam ulepszać aplikację." "Przeczytaj nasze warunki użytkowania %1$s." "tutaj" "Możesz to wyłączyć w dowolnym momencie" diff --git a/features/announcement/api/src/main/kotlin/io/element/android/features/announcement/api/AnnouncementService.kt b/features/announcement/api/src/main/kotlin/io/element/android/features/announcement/api/AnnouncementService.kt index 42c66aa29d..23c748d6da 100644 --- a/features/announcement/api/src/main/kotlin/io/element/android/features/announcement/api/AnnouncementService.kt +++ b/features/announcement/api/src/main/kotlin/io/element/android/features/announcement/api/AnnouncementService.kt @@ -12,15 +12,34 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import kotlinx.coroutines.flow.Flow +/** + * Queues the full-screen announcements shown to the user once, such as the notice about a new feature. + * + * A dismissed announcement is remembered so it is not shown again. + */ interface AnnouncementService { + /** + * Queues an announcement, unless the user has already dismissed it. + * + * @param announcement the announcement to show. + */ suspend fun showAnnouncement(announcement: Announcement) + /** + * Records that the user dismissed an announcement, so it is not queued again. + * + * @param announcement the announcement that was dismissed. + */ suspend fun onAnnouncementDismissed(announcement: Announcement) + /** The announcements still waiting to be shown, in the order they should appear. */ fun announcementsToShowFlow(): Flow> /** * Use this composable to render the announcement UI in Fullscreen. + * Draws nothing while there is no announcement to show. + * + * @param modifier layout modifier for the container. */ @Composable fun Render( diff --git a/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/AnnouncementStateProvider.kt b/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/AnnouncementStatePreviewParam.kt similarity index 90% rename from features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/AnnouncementStateProvider.kt rename to features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/AnnouncementStatePreviewParam.kt index 2412fee167..df7afad32f 100644 --- a/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/AnnouncementStateProvider.kt +++ b/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/AnnouncementStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.announcement.impl import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.announcement.api.Announcement -open class AnnouncementStateProvider : PreviewParameterProvider { +open class AnnouncementStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAnnouncementState(), diff --git a/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/fullscreen/FullscreenAnnouncementView.kt b/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/fullscreen/FullscreenAnnouncementView.kt index 5f7778900b..cb962f8968 100644 --- a/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/fullscreen/FullscreenAnnouncementView.kt +++ b/features/announcement/impl/src/main/kotlin/io/element/android/features/announcement/impl/fullscreen/FullscreenAnnouncementView.kt @@ -33,7 +33,7 @@ import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.announcement.api.Announcement import io.element.android.features.announcement.impl.AnnouncementEvent import io.element.android.features.announcement.impl.AnnouncementState -import io.element.android.features.announcement.impl.AnnouncementStateProvider +import io.element.android.features.announcement.impl.AnnouncementStatePreviewParam import io.element.android.libraries.designsystem.atomic.molecules.ButtonColumnMolecule import io.element.android.libraries.designsystem.atomic.molecules.IconTitleSubtitleMolecule import io.element.android.libraries.designsystem.atomic.pages.HeaderFooterPage @@ -216,7 +216,7 @@ private fun Announcement.Fullscreen.notice(): String? = when (this) { @PreviewsDayNight @Composable -internal fun FullscreenAnnouncementViewPreview(@PreviewParameter(AnnouncementStateProvider::class) state: AnnouncementState) = ElementPreview { +internal fun FullscreenAnnouncementViewPreview(@PreviewParameter(AnnouncementStatePreviewParam::class) state: AnnouncementState) = ElementPreview { FullscreenAnnouncementView( state = state, ) diff --git a/features/cachecleaner/api/src/main/kotlin/io/element/android/features/cachecleaner/api/CacheCleaner.kt b/features/cachecleaner/api/src/main/kotlin/io/element/android/features/cachecleaner/api/CacheCleaner.kt index b5a5396b16..48b464cb21 100644 --- a/features/cachecleaner/api/src/main/kotlin/io/element/android/features/cachecleaner/api/CacheCleaner.kt +++ b/features/cachecleaner/api/src/main/kotlin/io/element/android/features/cachecleaner/api/CacheCleaner.kt @@ -8,6 +8,9 @@ package io.element.android.features.cachecleaner.api +/** + * Removes the temporary files holding decrypted content, so plaintext media does not linger on disk. + */ interface CacheCleaner { /** * Clear the cache subdirs holding temporarily decrypted content (such as media and voice messages). diff --git a/features/call/api/src/main/kotlin/io/element/android/features/call/api/CurrentCallService.kt b/features/call/api/src/main/kotlin/io/element/android/features/call/api/CurrentCallService.kt index 25720596ba..20ff7ef4d8 100644 --- a/features/call/api/src/main/kotlin/io/element/android/features/call/api/CurrentCallService.kt +++ b/features/call/api/src/main/kotlin/io/element/android/features/call/api/CurrentCallService.kt @@ -10,6 +10,9 @@ package io.element.android.features.call.api import kotlinx.coroutines.flow.StateFlow +/** + * Tracks the call the user is currently in on this device, so unrelated parts of the app can react to it. + */ interface CurrentCallService { /** * The current call state flow, which will be updated when the active call changes. diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPictureEvent.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPictureEvent.kt index 1af13e148e..2053ff5102 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPictureEvent.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPictureEvent.kt @@ -11,7 +11,9 @@ package io.element.android.features.call.impl.pip import io.element.android.features.call.impl.utils.PipController sealed interface PictureInPictureEvent { + data object OnCallStarted : PictureInPictureEvent data class SetPipController(val pipController: PipController) : PictureInPictureEvent data object EnterPictureInPicture : PictureInPictureEvent data class OnPictureInPictureModeChanged(val isInPip: Boolean) : PictureInPictureEvent + data class SetPipOrientation(val orientation: Int?) : PictureInPictureEvent } diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPicturePresenter.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPicturePresenter.kt index 2dc16d7f26..274a80cc26 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPicturePresenter.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PictureInPicturePresenter.kt @@ -38,6 +38,9 @@ class PictureInPicturePresenter( fun handleEvent(event: PictureInPictureEvent) { when (event) { + is PictureInPictureEvent.OnCallStarted -> { + pipController?.setupPipCallbacks() + } is PictureInPictureEvent.SetPipController -> { pipController = event.pipController } @@ -55,6 +58,12 @@ class PictureInPicturePresenter( pipController?.exitPip() } } + is PictureInPictureEvent.SetPipOrientation -> { + Timber.tag(loggerTag.value).d("onOrientationChange: ${event.orientation}") + if (isPipSupported) { + pipView?.setPipOrientation(event.orientation) + } + } } } diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PipView.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PipView.kt index 90f74a37fd..54b8d77601 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PipView.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/pip/PipView.kt @@ -8,8 +8,15 @@ package io.element.android.features.call.impl.pip +import android.os.Build +import androidx.annotation.RequiresApi + interface PipView { + @RequiresApi(Build.VERSION_CODES.O) + fun setPipOrientation(orientation: Int?) + @RequiresApi(Build.VERSION_CODES.O) fun setPipParams() + @RequiresApi(Build.VERSION_CODES.O) fun enterPipMode(): Boolean fun hangUp() } diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallNotificationDataProvider.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallNotificationDataPreviewParam.kt similarity index 94% rename from features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallNotificationDataProvider.kt rename to features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallNotificationDataPreviewParam.kt index 9e551b3e1b..8ca3893f2b 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallNotificationDataProvider.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallNotificationDataPreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.matrix.api.core.UserId -open class CallNotificationDataProvider : PreviewParameterProvider { +open class CallNotificationDataPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aCallNotificationData( diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenStateProvider.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenStatePreviewParam.kt similarity index 93% rename from features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenStateProvider.kt rename to features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenStatePreviewParam.kt index 155c5d3380..cc21197a51 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenStateProvider.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.call.impl.ui import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncData -open class CallScreenStateProvider : PreviewParameterProvider { +open class CallScreenStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aCallScreenState(), diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenView.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenView.kt index 2537eb739c..33c3024f83 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenView.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/CallScreenView.kt @@ -118,6 +118,7 @@ internal fun CallScreenView( if (webViewAudioManager?.isInCallMode?.get() == false) { Timber.d("URL $url is loaded, starting in-call audio mode") webViewAudioManager?.onCallStarted() + pipState.eventSink(PictureInPictureEvent.OnCallStarted) } else { Timber.d("Can't start in-call audio mode since the app is already in it.") } @@ -130,7 +131,12 @@ internal fun CallScreenView( onInvalidAudioDeviceAdded = { invalidAudioDeviceReason = it }, ) state.eventSink(CallScreenEvent.SetupMessageChannels(interceptor)) - val pipController = WebViewPipController(webView) + val pipController = WebViewPipController( + webView = webView, + updatePipOrientation = { orientation -> + pipState.eventSink(PictureInPictureEvent.SetPipOrientation(orientation)) + } + ) pipState.eventSink(PictureInPictureEvent.SetPipController(pipController)) }, onDestroyWebView = { @@ -260,7 +266,7 @@ private fun WebView.dispatchEscKeyEvent() { @PreviewsDayNight @Composable internal fun CallScreenViewPreview( - @PreviewParameter(CallScreenStateProvider::class) state: CallScreenState, + @PreviewParameter(CallScreenStatePreviewParam::class) state: CallScreenState, ) = ElementPreview { CallScreenView( state = state, diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/ElementCallActivity.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/ElementCallActivity.kt index 9a093ff5a6..4a6b8f1c05 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/ElementCallActivity.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/ElementCallActivity.kt @@ -11,9 +11,9 @@ package io.element.android.features.call.impl.ui import android.Manifest import android.app.PictureInPictureParams import android.content.Intent +import android.content.res.Configuration import android.os.Build import android.os.Bundle -import android.util.Rational import android.view.WindowManager import android.webkit.PermissionRequest import androidx.activity.compose.setContent @@ -49,6 +49,7 @@ import io.element.android.features.call.impl.pip.PipView import io.element.android.features.call.impl.services.CallForegroundService import io.element.android.features.enterprise.api.EnterpriseService import io.element.android.libraries.androidutils.browser.ConsoleMessageLogger +import io.element.android.libraries.androidutils.media.setAspectRatioFromOrientation import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.architecture.bindings import io.element.android.libraries.audio.api.AudioFocus @@ -86,6 +87,8 @@ class ElementCallActivity : private var eventSink: ((CallScreenEvent) -> Unit)? = null + private var currentPipOrientation: Int? = null + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -199,6 +202,9 @@ class ElementCallActivity : } DisposableEffect(Unit) { val onPictureInPictureModeChangedListener = Consumer { _: PictureInPictureModeChangedInfo -> + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + setPipParams() + } pipEventSink(PictureInPictureEvent.OnPictureInPictureModeChanged(isInPictureInPictureMode)) if (!isInPictureInPictureMode && !lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) { Timber.tag(loggerTag.value).d("Exiting PiP mode: Hangup the call") @@ -296,11 +302,18 @@ class ElementCallActivity : } } + @RequiresApi(Build.VERSION_CODES.O) + override fun setPipOrientation(orientation: Int?) { + currentPipOrientation = orientation + setPictureInPictureParams(getPictureInPictureParams()) + } + @RequiresApi(Build.VERSION_CODES.O) private fun getPictureInPictureParams(): PictureInPictureParams { + // Portrait for calls seems more appropriate as a fallback value + val orientation = currentPipOrientation ?: Configuration.ORIENTATION_PORTRAIT return PictureInPictureParams.Builder() - // Portrait for calls seems more appropriate - .setAspectRatio(Rational(3, 5)) + .setAspectRatioFromOrientation(orientation) .apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { setAutoEnterEnabled(true) diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/IncomingCallScreen.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/IncomingCallScreen.kt index 72edd59ed5..1489d9d0e7 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/IncomingCallScreen.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/ui/IncomingCallScreen.kt @@ -161,7 +161,7 @@ private fun ActionButton( @PreviewsDayNight @Composable internal fun IncomingCallScreenPreview( - @PreviewParameter(CallNotificationDataProvider::class) state: CallNotificationData, + @PreviewParameter(CallNotificationDataPreviewParam::class) state: CallNotificationData, ) = ElementPreview { IncomingCallScreen( notificationData = state, diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/PipController.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/PipController.kt index b259816f9d..f7788ad520 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/PipController.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/PipController.kt @@ -9,6 +9,7 @@ package io.element.android.features.call.impl.utils interface PipController { + fun setupPipCallbacks() suspend fun canEnterPip(): Boolean fun enterPip() fun exitPip() diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewAudioManager.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewAudioManager.kt index e68e57118b..3290269971 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewAudioManager.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewAudioManager.kt @@ -250,7 +250,7 @@ class WebViewAudioManager( hasRegisteredCallbacks = true } - } + }, ) Timber.d("Setting androidNativeBridge javascript interface in webview") webView.addJavascriptInterface(webViewAudioDeviceSelectedCallback, "androidNativeBridge") diff --git a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewPipController.kt b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewPipController.kt index 12f8dfd00f..88648e84fa 100644 --- a/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewPipController.kt +++ b/features/call/impl/src/main/kotlin/io/element/android/features/call/impl/utils/WebViewPipController.kt @@ -8,7 +8,10 @@ package io.element.android.features.call.impl.utils +import android.content.res.Configuration +import android.webkit.JavascriptInterface import android.webkit.WebView +import timber.log.Timber import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine @@ -18,7 +21,18 @@ import kotlin.coroutines.suspendCoroutine */ class WebViewPipController( private val webView: WebView, + updatePipOrientation: (orientation: Int?) -> Unit, ) : PipController { + init { + // Register the JavaScript interface ahead of time to ensure it's available when the WebView content is loaded and tries to call it + webView.addJavascriptInterface(PipBridge(updatePipOrientation), "androidPipBridge") + } + + override fun setupPipCallbacks() { + Timber.d("Adding callback in controls.onPipMediaOrientationUpdate") + webView.evaluateJavascript("controls.onPipMediaOrientationUpdate = (orientation) => { androidPipBridge.setPipOrientation(orientation); };", null) + } + override suspend fun canEnterPip(): Boolean { return suspendCoroutine { continuation -> webView.evaluateJavascript("controls.canEnterPip()") { result -> @@ -36,3 +50,19 @@ class WebViewPipController( webView.evaluateJavascript("controls.disablePip()", null) } } + +private class PipBridge( + private val onOrientationChange: (orientation: Int?) -> Unit, +) { + @JavascriptInterface + fun setPipOrientation(orientation: String?) { + Timber.d("Picture-in-picture orientation changed in webview, orientation: $orientation") + // This callback is used to update the picture-in-picture orientation in the WebView when it changes + val orientation = when (orientation) { + "portrait" -> Configuration.ORIENTATION_PORTRAIT + "landscape" -> Configuration.ORIENTATION_LANDSCAPE + else -> return + } + onOrientationChange(orientation) + } +} diff --git a/features/call/impl/src/main/res/values-ar/translations.xml b/features/call/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..612dd16a28 --- /dev/null +++ b/features/call/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,8 @@ + + + "مكالمة جارية" + "اضغط للعودة إلى المكالمة" + "☎️ الاتصال يتمّ" + "لا يدعم Element Call استخدام أجهزة الصوت عبر Bluetooth في إصدار Android هذا. يرجى اختيار جهاز صوت آخر." + "مكالمة Element Call واردة" + diff --git a/features/call/impl/src/main/res/values-fa/translations.xml b/features/call/impl/src/main/res/values-fa/translations.xml index c58ebfd5c6..622be3d428 100644 --- a/features/call/impl/src/main/res/values-fa/translations.xml +++ b/features/call/impl/src/main/res/values-fa/translations.xml @@ -3,5 +3,6 @@ "تماس خروجی" "زدن برای بازگشت به تماس" "تماس در جریان ☎️" + "برنامه Element Call در این نسخه اندروید از دستگاه‌های صوتی بلوتوث پشتیبانی نمی‌کند. لطفاً دستگاه صوتی دیگری را انتخاب کنید." "تماس المنتی ورودی" diff --git a/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipController.kt b/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipController.kt index 5153f79c31..f2eca681e9 100644 --- a/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipController.kt +++ b/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipController.kt @@ -12,10 +12,13 @@ import io.element.android.features.call.impl.utils.PipController import io.element.android.tests.testutils.lambda.lambdaError class FakePipController( + private val setupPipCallbacksResult: () -> Unit = { lambdaError() }, private val canEnterPipResult: () -> Boolean = { lambdaError() }, private val enterPipResult: () -> Unit = { lambdaError() }, private val exitPipResult: () -> Unit = { lambdaError() }, ) : PipController { + override fun setupPipCallbacks() = setupPipCallbacksResult() + override suspend fun canEnterPip(): Boolean = canEnterPipResult() override fun enterPip() = enterPipResult() diff --git a/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipView.kt b/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipView.kt index 55e94312bf..adfcde2c38 100644 --- a/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipView.kt +++ b/features/call/impl/src/test/kotlin/io/element/android/features/call/impl/pip/FakePipView.kt @@ -13,9 +13,11 @@ import io.element.android.tests.testutils.lambda.lambdaError class FakePipView( private val setPipParamsResult: () -> Unit = { lambdaError() }, private val enterPipModeResult: () -> Boolean = { lambdaError() }, - private val handUpResult: () -> Unit = { lambdaError() } + private val handUpResult: () -> Unit = { lambdaError() }, + private val onOrientationChangeResult: (orientation: Int?) -> Unit = { lambdaError() }, ) : PipView { override fun setPipParams() = setPipParamsResult() override fun enterPipMode(): Boolean = enterPipModeResult() override fun hangUp() = handUpResult() + override fun setPipOrientation(orientation: Int?) = onOrientationChangeResult(orientation) } diff --git a/features/contentscanner/api/src/main/kotlin/io/element/android/features/contentscanner/api/ContentScannerService.kt b/features/contentscanner/api/src/main/kotlin/io/element/android/features/contentscanner/api/ContentScannerService.kt index 68f7af28f1..3649768eb7 100644 --- a/features/contentscanner/api/src/main/kotlin/io/element/android/features/contentscanner/api/ContentScannerService.kt +++ b/features/contentscanner/api/src/main/kotlin/io/element/android/features/contentscanner/api/ContentScannerService.kt @@ -18,5 +18,11 @@ import io.element.android.libraries.matrix.ui.media.contentvalidation.ContentVal * This will only process media when a [ContentScanner] is provided when building the client in Pro. */ fun interface ContentScannerService { + /** + * Starts scanning the given media, reporting the verdict of each one through [contentValidationState] rather than by returning. + * + * @param mediaSources the media to scan. + * @param contentValidationState where the outcome of each scan is published for the UI to observe. + */ fun scan(mediaSources: List, contentValidationState: ContentValidationState) } diff --git a/features/contentscanner/impl/src/main/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerModule.kt b/features/contentscanner/impl/src/main/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerBindingContainer.kt similarity index 97% rename from features/contentscanner/impl/src/main/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerModule.kt rename to features/contentscanner/impl/src/main/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerBindingContainer.kt index 9446a603b2..8c25d8bf6a 100644 --- a/features/contentscanner/impl/src/main/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerModule.kt +++ b/features/contentscanner/impl/src/main/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerBindingContainer.kt @@ -21,7 +21,7 @@ import kotlinx.coroutines.CoroutineScope @BindingContainer @ContributesTo(RoomScope::class) -object ContentScannerModule { +object ContentScannerBindingContainer { @Provides @SingleIn(RoomScope::class) fun providesContentScannerService( diff --git a/features/contentscanner/impl/src/test/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerModuleTest.kt b/features/contentscanner/impl/src/test/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerBindingContainerTest.kt similarity index 77% rename from features/contentscanner/impl/src/test/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerModuleTest.kt rename to features/contentscanner/impl/src/test/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerBindingContainerTest.kt index 8c3834d696..858a21df6c 100644 --- a/features/contentscanner/impl/src/test/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerModuleTest.kt +++ b/features/contentscanner/impl/src/test/kotlin/io/element/android/features/contentscanner/impl/di/ContentScannerBindingContainerTest.kt @@ -15,16 +15,16 @@ import io.element.android.tests.testutils.testCoroutineDispatchers import kotlinx.coroutines.test.runTest import org.junit.Test -class ContentScannerModuleTest { +class ContentScannerBindingContainerTest { @Test - fun `ContentScannerModule provides NoopContentScannerService when ContentScanner is null`() = runTest { + fun `ContentScannerBindingContainer provides NoopContentScannerService when ContentScanner is null`() = runTest { // Given val contentScanner: ContentScanner? = null val sessionCoroutineScope = backgroundScope val coroutineDispatchers = testCoroutineDispatchers() // When - val contentScannerService = ContentScannerModule.providesContentScannerService( + val contentScannerService = ContentScannerBindingContainer.providesContentScannerService( contentScanner = contentScanner, coroutineScope = sessionCoroutineScope, coroutineDispatchers = coroutineDispatchers, @@ -35,14 +35,14 @@ class ContentScannerModuleTest { } @Test - fun `ContentScannerModule provides DefaultContentScannerService when ContentScanner is not null`() = runTest { + fun `ContentScannerBindingContainer provides DefaultContentScannerService when ContentScanner is not null`() = runTest { // Given val contentScanner: ContentScanner? = FakeContentScanner() val sessionCoroutineScope = backgroundScope val coroutineDispatchers = testCoroutineDispatchers() // When - val contentScannerService = ContentScannerModule.providesContentScannerService( + val contentScannerService = ContentScannerBindingContainer.providesContentScannerService( contentScanner = contentScanner, coroutineScope = sessionCoroutineScope, coroutineDispatchers = coroutineDispatchers, diff --git a/features/createroom/api/src/main/kotlin/io/element/android/features/createroom/api/CreateRoomEntryPoint.kt b/features/createroom/api/src/main/kotlin/io/element/android/features/createroom/api/CreateRoomEntryPoint.kt index 271fdb2332..3128b8073a 100644 --- a/features/createroom/api/src/main/kotlin/io/element/android/features/createroom/api/CreateRoomEntryPoint.kt +++ b/features/createroom/api/src/main/kotlin/io/element/android/features/createroom/api/CreateRoomEntryPoint.kt @@ -15,9 +15,21 @@ import io.element.android.libraries.architecture.FeatureEntryPoint import io.element.android.libraries.matrix.api.core.RoomId interface CreateRoomEntryPoint : FeatureEntryPoint { + /** + * Configures the create-room flow before it is started, since it serves rooms and spaces from the same screens. + */ interface Builder { + /** + * @param isSpace true to create a space rather than a room. + */ fun setIsSpace(isSpace: Boolean): Builder + + /** + * @param parentSpaceId the space the new room should be added to once created. + */ fun setParentSpace(parentSpaceId: RoomId): Builder + + /** Builds the node with the options configured so far. */ fun build(): Node } diff --git a/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/addpeople/AddPeopleView.kt b/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/addpeople/AddPeopleView.kt index e03d36363d..f9075691aa 100644 --- a/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/addpeople/AddPeopleView.kt +++ b/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/addpeople/AddPeopleView.kt @@ -23,7 +23,7 @@ import androidx.compose.ui.unit.dp import io.element.android.features.createroom.impl.R import io.element.android.features.invitepeople.api.InvitePeopleEvents import io.element.android.features.invitepeople.api.InvitePeopleState -import io.element.android.features.invitepeople.api.InvitePeopleStateProvider +import io.element.android.features.invitepeople.api.InvitePeopleStatePreviewParam import io.element.android.libraries.designsystem.atomic.pages.HeaderFooterPage import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight @@ -86,7 +86,7 @@ private fun AddPeopleTopBar( @PreviewsDayNight @Composable -internal fun AddPeopleViewPreview(@PreviewParameter(InvitePeopleStateProvider::class) state: InvitePeopleState) = ElementPreview { +internal fun AddPeopleViewPreview(@PreviewParameter(InvitePeopleStatePreviewParam::class) state: InvitePeopleState) = ElementPreview { AddPeopleView( state = state, invitePeopleView = {}, diff --git a/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomStateProvider.kt b/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomStatePreviewParam.kt similarity index 98% rename from features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomStateProvider.kt rename to features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomStatePreviewParam.kt index 9c2ad76a9b..151c7d13d0 100644 --- a/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomStateProvider.kt +++ b/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomStatePreviewParam.kt @@ -21,7 +21,7 @@ import io.element.android.libraries.permissions.api.aPermissionsState import io.element.android.libraries.previewutils.room.aSpaceRoom import kotlinx.collections.immutable.toImmutableList -open class ConfigureRoomStateProvider : PreviewParameterProvider { +open class ConfigureRoomStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aConfigureRoomState(), diff --git a/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomView.kt b/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomView.kt index c929060e13..e39df69f97 100644 --- a/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomView.kt +++ b/features/createroom/impl/src/main/kotlin/io/element/android/features/createroom/impl/configureroom/ConfigureRoomView.kt @@ -349,12 +349,12 @@ private fun RoomJoinRuleOptions( @PreviewWithLargeHeight @Composable -internal fun ConfigureRoomViewLightPreview(@PreviewParameter(ConfigureRoomStateProvider::class) state: ConfigureRoomState) = +internal fun ConfigureRoomViewLightPreview(@PreviewParameter(ConfigureRoomStatePreviewParam::class) state: ConfigureRoomState) = ElementPreviewLight { ContentToPreview(state) } @PreviewWithLargeHeight @Composable -internal fun ConfigureRoomViewDarkPreview(@PreviewParameter(ConfigureRoomStateProvider::class) state: ConfigureRoomState) = +internal fun ConfigureRoomViewDarkPreview(@PreviewParameter(ConfigureRoomStatePreviewParam::class) state: ConfigureRoomState) = ElementPreviewDark { ContentToPreview(state) } @ExcludeFromCoverage diff --git a/features/createroom/impl/src/main/res/values-ar/translations.xml b/features/createroom/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..7cb356739a --- /dev/null +++ b/features/createroom/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,36 @@ + + + "إنشاء غرفة جديدة" + "دعوة أشخاص" + "حصل خطأ أثناء إنشاء الغرفة" + "تعذّر إنشاء المساحة بسبب خطأ غير معروف. حاول مرة أخرى لاحقًا." + "إضافة اسم…" + "غرفة جديدة" + "مساحة جديدة" + "لا يدخل إلا المدعوّون." + "خاصة" + "بإمكان الجميع العثور على هذه الغرفة. +يمكنك تغيير هذا من إعدادات الغرفة متى شئت." + "يمكن لأي شخص الانضمام." + "عامة" + "يمكن لأي شخص طلب الانضمام، لكن يجب أن يقبل الطلب مسؤول أو مشرف." + "السماح بطلبات الانضمام" + "يمكن لأي شخص في %1$s الانضمام، لكن يجب على الآخرين طلب الوصول." + "طلب الانضمام" + "يمكن للمدعوين فقط الانضمام." + "خاصة" + "يمكن لأي شخص الانضمام." + "عامة" + "يمكن لأي شخص في %1$s الانضمام." + "قياسي" + "من يمكنه الوصول" + "تحتاج إلى عنوان حتى تظهر الغرفة في الدليل العام." + "العنوان" + "ظهور الغرفة" + "(لا توجد مساحة)" + "عدم الإضافة إلى مساحة" + "لم يتم اختيار أي مساحة" + "إضافة إلى مساحة" + "الموضوع (اختياري)" + "إضافة وصف…" + diff --git a/features/createroom/impl/src/main/res/values-es/translations.xml b/features/createroom/impl/src/main/res/values-es/translations.xml index 740e0b70cc..e3ceccbb83 100644 --- a/features/createroom/impl/src/main/res/values-es/translations.xml +++ b/features/createroom/impl/src/main/res/values-es/translations.xml @@ -3,14 +3,34 @@ "Nueva sala" "Invitar personas" "Se ha producido un error al crear la sala" + "No se pudo crear el espacio debido a un error desconocido. Inténtalo de nuevo más tarde." + "Añadir nombre…" + "Nueva sala" + "Nuevo espacio" "Solo las personas invitadas pueden acceder." + "Privado" "Cualquiera puede encontrar esta sala. Puedes cambiar esto en cualquier momento en los ajustes de la sala." + "Cualquiera puede unirse." + "Público" "Cualquiera puede solicitar unirse, pero un administrador o un moderador tendrá que aceptar la solicitud" "Permitir solicitar unirse" + "Cualquiera en %1$s puede unirse, pero el resto debe solicitar acceso." + "Solicitar unirse" + "Solo las personas invitadas pueden unirse." + "Privado" "Cualquiera puede unirse." + "Público" + "Cualquiera de %1$s puede unirse." + "Estándar" + "Quién tiene acceso" "Necesitarás una dirección de sala para que sea visible en el directorio de salas públicas." "Dirección" "Visibilidad de la sala" + "(ningún espacio)" + "No añadir a un espacio" + "No se ha seleccionado ningún espacio" + "Añadir a un espacio" "Tema (opcional)" + "Añadir descripción…" diff --git a/features/createroom/impl/src/main/res/values-fa/translations.xml b/features/createroom/impl/src/main/res/values-fa/translations.xml index 821d55af67..c3ec327d5b 100644 --- a/features/createroom/impl/src/main/res/values-fa/translations.xml +++ b/features/createroom/impl/src/main/res/values-fa/translations.xml @@ -3,12 +3,34 @@ "اتاق جدید" "دعوت افراد" "هنگام ایجاد اتاق خطایی رخ داد" + "به دلیل خطای ناشناخته‌ای، فضا ایجاد نشد. بعداً دوباره امتحان کنید." + "افزودن نام…" + "اتاق جدید" + "فضای جدید" "تنها افراد دعوت شده می‌توانند بپیوندند." + "خصوصی" "هرکسی می‌تواند اتاق را بیابد. می‌توانید بعداً در تظیمات اتاق عوضش کنید." - "درخواست دعوت" - "هرکسی می‌تواند به این اتاق بپیوندد" - "نشانی اتاق" + "هر کسی می‌تواند عضو شود." + "عمومی" + "هر کسی می‌تواند درخواست عضویت بدهد، اما یک مدیر یا ناظر باید درخواست را بپذیرد." + "اجازه درخواست عضویت" + "هر کسی در %1$s می‌تواند عضو شود، اما بقیه باید درخواست دسترسی بدهند." + "درخواست عضویت" + "تنها افراد دعوت شده می‌توانند بپیوندند." + "خصوصی" + "هر کسی می‌تواند عضو شود." + "عمومی" + "هر کسی که در %1$s باشد می‌تواند عضو شود." + "استاندارد" + "چه کسی دسترسی دارد" + "برای اینکه بتوانید آن را در فهرست عمومی مشاهده کنید، به یک آدرس نیاز دارید." + "آدرس" "نمایانی اتاق" + "(بدون فضا)" + "به یک فضا اضافه نکنید" + "فضایی انتخاب نشده است" + "به فضا اضافه کنید" "موضوع (اختیاری)" + "اضافه کردن توضیحات…" diff --git a/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationStateProvider.kt b/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationStatePreviewParam.kt similarity index 94% rename from features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationStateProvider.kt rename to features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationStatePreviewParam.kt index 5c832a4d75..bd86af9572 100644 --- a/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationStateProvider.kt +++ b/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.logout.impl import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class AccountDeactivationStateProvider : PreviewParameterProvider { +open class AccountDeactivationStatePreviewParam : PreviewParameterProvider { private val filledForm = aDeactivateFormState(eraseData = true, password = "password") override val values: Sequence get() = sequenceOf( diff --git a/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationView.kt b/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationView.kt index 738046b3a3..eb6b401667 100644 --- a/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationView.kt +++ b/features/deactivation/impl/src/main/kotlin/io/element/android/features/logout/impl/AccountDeactivationView.kt @@ -299,16 +299,16 @@ private fun Content( } /** - * Ensure that the string does not contain any new line characters, which can happen when pasting values. + * Ensure that the string does not contain any line separator, which can happen when pasting values. */ private fun String.sanitize(): String { - return replace("\n", "") + return filterNot { it == '\n' || it == '\r' } } @PreviewsDayNight @Composable internal fun AccountDeactivationViewPreview( - @PreviewParameter(AccountDeactivationStateProvider::class) state: AccountDeactivationState, + @PreviewParameter(AccountDeactivationStatePreviewParam::class) state: AccountDeactivationState, ) = ElementPreview { AccountDeactivationView( state, diff --git a/features/deactivation/impl/src/main/res/values-ar/translations.xml b/features/deactivation/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..d0fa5afe94 --- /dev/null +++ b/features/deactivation/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,14 @@ + + + "يرجى تأكيد رغبتك في حذف حسابك. لا يمكن التراجع عن هذا الإجراء." + "حذف جميع رسائلي" + "تحذير: قد يرى المستخدمون في المستقبل محادثات غير مكتملة." + "حذف حسابك %1$s، وسيؤدي إلى:" + "إجراء لا رجعة فيه" + "%1$s (لن تتمكن من تسجيل الدخول مرة أخرى، ولا يمكن إعادة استخدام معرّفك)." + "تعطيل حسابك نهائيًا" + "إزالتك من جميع غرف الدردشة." + "حذف معلومات حسابك من خادم الهوية لدينا." + "ستظل رسائلك مرئية للمستخدمين المسجلين، لكنها لن تكون متاحة للمستخدمين الجدد أو غير المسجلين إذا اخترت حذفها." + "حذف الحساب" + diff --git a/features/deactivation/impl/src/main/res/values-es/translations.xml b/features/deactivation/impl/src/main/res/values-es/translations.xml index 17ae73d6c8..dc3e090e06 100644 --- a/features/deactivation/impl/src/main/res/values-es/translations.xml +++ b/features/deactivation/impl/src/main/res/values-es/translations.xml @@ -1,13 +1,14 @@ - "Confirma que quieres desactivar tu cuenta. Esta acción no se puede deshacer." + "Confirma que quieres eliminar tu cuenta. Esta acción no se puede deshacer." "Borrar todos mis mensajes" "Advertencia: Futuros usuarios pueden ver conversaciones incompletas." - "Desactivar tu cuenta es %1$s:" + "Eliminar tu cuenta es %1$s:" "irreversible" "%1$s tu cuenta (no podrás volver a iniciar sesión y tu ID no se podrá volver a utilizar)." "Inhabilitará permanentemente" "Te eliminará de todas las salas de chat." "Eliminará la información de tu cuenta de nuestro servidor de identidad." "Tus mensajes seguirán siendo visibles para los usuarios registrados, pero no estarán disponibles para los usuarios nuevos o no registrados si decides eliminarlos." + "Eliminar cuenta" diff --git a/features/deactivation/impl/src/main/res/values-fa/translations.xml b/features/deactivation/impl/src/main/res/values-fa/translations.xml index 5c4eb00d62..38828d5e60 100644 --- a/features/deactivation/impl/src/main/res/values-fa/translations.xml +++ b/features/deactivation/impl/src/main/res/values-fa/translations.xml @@ -1,9 +1,14 @@ + "لطفاً تأیید کنید که می‌خواهید حساب کاربری خود را حذف کنید. این اقدام قابل بازگشت نیست." "حذف همهٔ پیام‌هایم" + "هشدار: کاربران آینده ممکن است مکالمات ناقص را ببینند." + "حذف حساب کاربری شما %1$s است، این کار باعث می‌شود:" "بازگشت‌ناپذیر" + "حساب کاربری خود را %1$s کنید (شما نمی‌توانید دوباره وارد سیستم شوید و شناسه شما قابل استفاده مجدد نیست)." "از کار انداختن دایمی" "برداشتنتان از همهٔ اتاق‌های گپ." "حذف اطّلاعات حسابتان از کارساز هویت." - "غیرفعّال‌سازی حساب" + "پیام‌های شما همچنان برای کاربران ثبت‌نام‌شده قابل مشاهده خواهند بود، اما اگر تصمیم به حذف آنها بگیرید، برای کاربران جدید یا ثبت‌نام‌نشده در دسترس نخواهند بود." + "حذف حساب کاربری" diff --git a/features/deactivation/impl/src/main/res/values-zh-rTW/translations.xml b/features/deactivation/impl/src/main/res/values-zh-rTW/translations.xml index a099a67f7f..159d8f4a41 100644 --- a/features/deactivation/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/deactivation/impl/src/main/res/values-zh-rTW/translations.xml @@ -1,14 +1,14 @@ - "請確認您想要停用您的帳號。此動作無法還原。" + "請確認您想要刪除您的帳號。此動作無法還原。" "刪除我所有的訊息" "警告:未來的使用者可能會看到不完整的對話。" - "停用您的帳號為 %1$s,它將:" + "刪除您的帳號為 %1$s,它將:" "不可逆" "%1$s 您的帳號(您將無法重新登入,也無法重用您的 ID)。" "永久停用" "將您從所有聊天室移除。" "從我們的身份伺服器將您的帳號資訊刪除。" "註冊使用者仍可看到您的訊息,但如果您選擇刪除,新使用者與未註冊的使用者將看不到它們。" - "停用帳號" + "刪除帳號" diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/ClientBuilderEnterpriseHook.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/ClientBuilderEnterpriseHook.kt new file mode 100644 index 0000000000..bfb9fb538a --- /dev/null +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/ClientBuilderEnterpriseHook.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.api + +import io.element.android.libraries.matrix.api.MatrixClientBuilder +import io.element.android.libraries.matrix.api.core.SessionId + +/** + * A hook that can be used to customize the [MatrixClientBuilder] for enterprise features. + */ +fun interface ClientBuilderEnterpriseHook { + suspend operator fun invoke(clientBuilder: MatrixClientBuilder, sessionId: SessionId): MatrixClientBuilder +} diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/ClientEnterpriseHook.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/ClientEnterpriseHook.kt new file mode 100644 index 0000000000..e6d5c9aac1 --- /dev/null +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/ClientEnterpriseHook.kt @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.api + +import io.element.android.libraries.matrix.api.MatrixClient + +/** + * A hook that can be used to customize the [MatrixClient] for enterprise features. + */ +fun interface ClientEnterpriseHook { + suspend operator fun invoke(client: MatrixClient) +} diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/EnterpriseService.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/EnterpriseService.kt index 7b595966d4..2cb4a356be 100644 --- a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/EnterpriseService.kt +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/EnterpriseService.kt @@ -10,17 +10,52 @@ package io.element.android.features.enterprise.api import androidx.compose.ui.graphics.Color import io.element.android.compound.colors.SemanticColorsLightDark +import io.element.android.libraries.matrix.api.ClientUrlContentFetcher import io.element.android.libraries.matrix.api.core.SessionId -import io.element.android.libraries.wellknown.api.ElementWellKnown import kotlinx.coroutines.flow.Flow +/** + * Exposes the restrictions and customisations an enterprise deployment can impose: allowed homeservers, branding, push gateways and more. + * + * On a standard build this reports permissive defaults, so callers do not need to branch on the build type themselves. + */ interface EnterpriseService { - val isEnterpriseBuild: Boolean + /** + * Whether the given session belongs to an enterprise deployment, which can be true even on a standard build. + * + * @param sessionId the session to check. + */ suspend fun isEnterpriseUser(sessionId: SessionId): Boolean - suspend fun tweakMasUrl(url: String, homeserver: String): String - fun defaultHomeserverList(): List + + /** + * Rewrites the authentication server URL when the deployment requires a different one from the one advertised. + * + * @param url the URL to rewrite. + * @param urlContentFetcher used to read the deployment configuration; a client that is not authenticated yet also works. + */ + suspend fun tweakMasUrl(url: String, urlContentFetcher: ClientUrlContentFetcher): String + + /** + * Returns the list of homeservers the user is allowed to sign in to. + * + * If the list is empty or contains the special value [ANY_ACCOUNT_PROVIDER], the user is allowed to sign in to any homeserver. + */ + fun homeserverAllowList(): List + + /** + * Whether the user is allowed to sign in to a given homeserver, according to [homeserverAllowList]. + * + * @param homeserverUrl the server the user is trying to use. + */ suspend fun isAllowedToConnectToHomeserver(homeserverUrl: String): Boolean + /** + * Whether the given homeserver enforces the use of Element Pro or a derived app. + * + * @param serverName the homeserver to check. + */ + suspend fun isElementProEnforced(serverName: String): Boolean + /** * Override the brand color. * @param sessionId the session to override the brand color for, or null to set the brand color to use when there is no session. @@ -28,32 +63,48 @@ interface EnterpriseService { */ suspend fun overrideBrandColor(sessionId: SessionId?, brandColor: String?) + /** + * The brand color to apply, or `null` when the default theme color should be used. + * + * @param sessionId the session to read the color of, or `null` for the color used when no session is active. + */ fun brandColorsFlow(sessionId: SessionId?): Flow + /** + * The full light and dark color palettes derived from the brand color. + * + * @param sessionId the session to read the colors of, or `null` for the colors used when no session is active. + */ fun semanticColorsFlow(sessionId: SessionId?): Flow + /** The push gateway to register with when using Firebase, or `null` to use the app default. */ fun firebasePushGateway(): String? + + /** The push gateway to register with when using UnifiedPush, or `null` to use the app default. */ fun unifiedPushDefaultPushGateway(): String? + /** + * Where bug reports should be submitted, which an enterprise deployment can redirect or disable entirely. + * + * @param sessionId the session to read the setting of, or `null` for the setting used when no session is active. + */ fun bugReportUrlFlow(sessionId: SessionId?): Flow /** * Gets Notification Channel to use for the noisy notifications of the provided session. + * Returns `null` when the session has no dedicated channel and the app-wide one should be used. + * + * @param sessionId the session whose channel is requested. */ fun getNoisyNotificationChannelId(sessionId: SessionId): String? - /** - * Gets the overridden Element Well-Known data if it has been set, or null if not set. - */ - fun overriddenElementWellKnown(): ElementWellKnown? - companion object { const val ANY_ACCOUNT_PROVIDER = "*" } } fun EnterpriseService.canConnectToAnyHomeserver(): Boolean { - return defaultHomeserverList().let { + return homeserverAllowList().let { it.isEmpty() || it.contains(EnterpriseService.ANY_ACCOUNT_PROVIDER) } } diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/IsEnterpriseBuild.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/IsEnterpriseBuild.kt new file mode 100644 index 0000000000..83591ea7bd --- /dev/null +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/IsEnterpriseBuild.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.api + +/** + * A use case to check if this build of the app is an enterprise build. + */ +fun interface IsEnterpriseBuild { + /** + * Returns `true` if this build of the app is an enterprise build, `false` otherwise. + */ + operator fun invoke(): Boolean +} diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/SessionEnterpriseService.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/SessionEnterpriseService.kt index ee005a0b6b..94f455f2ff 100644 --- a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/SessionEnterpriseService.kt +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/SessionEnterpriseService.kt @@ -8,11 +8,25 @@ package io.element.android.features.enterprise.api +/** + * The session-scoped counterpart of [EnterpriseService], answering the same kind of questions for the session it belongs to. + * + * [init] must have run before the other members return meaningful answers. + */ interface SessionEnterpriseService { + /** Loads the deployment configuration of this session; to be called once when the session starts. */ + suspend fun init() + + /** Whether Element Call may be used on this session, which a deployment can turn off. */ suspend fun isElementCallAvailable(): Boolean + + /** + * Rewrites the authentication server URL for this session; see [EnterpriseService.tweakMasUrl]. + * + * @param url the URL to rewrite. + */ suspend fun tweakMasUrl(url: String): String + /** Whether the homeserver forbids creating encrypted rooms, in which case the app must not offer the option. */ suspend fun isEncryptionDisabledByHomeserver(): Boolean - - suspend fun init() } diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/CustomMapTilerConfigProvider.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/CustomMapTilerConfigProvider.kt new file mode 100644 index 0000000000..9bfd3c940a --- /dev/null +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/CustomMapTilerConfigProvider.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.api.remoteconfig + +/** + * A provider of a runtime-fetched MapTiler configuration, which can be used to override the default MapTiler configuration. + */ +fun interface CustomMapTilerConfigProvider { + suspend fun get(): Result +} diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/MapTilerConfig.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/MapTilerConfig.kt new file mode 100644 index 0000000000..3e8b8b14e1 --- /dev/null +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/MapTilerConfig.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.api.remoteconfig + +import androidx.compose.runtime.Immutable + +/** + * A `MapTiler` configuration received from the server. This configuration is used to display maps in the app. + */ +@Immutable +data class MapTilerConfig( + /** The API key to use with MapTiler. This is always not null, but can be empty/blank. */ + val apiKey: String, + /** The style ID to use for light mode. This is optional and can be null. */ + val lightStyleId: String?, + /** The style ID to use for light mode. This is optional and can be null. */ + val darkStyleId: String?, + /** The base URL to use for MapTiler. This is optional and can be null. */ + val baseUrl: String?, +) diff --git a/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/RemoteEnterpriseConfigResult.kt b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/RemoteEnterpriseConfigResult.kt new file mode 100644 index 0000000000..0cdcdebe0b --- /dev/null +++ b/features/enterprise/api/src/main/kotlin/io/element/android/features/enterprise/api/remoteconfig/RemoteEnterpriseConfigResult.kt @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.api.remoteconfig + +sealed interface RemoteEnterpriseConfigResult { + /** + * Well-known data has been successfully retrieved. + */ + data class Success(val data: T) : RemoteEnterpriseConfigResult + + /** + * Well-known data has been retrieved from the local cache but is outdated and a manual refresh has been launched. + */ + data class Outdated(val data: T) : RemoteEnterpriseConfigResult + + /** + * Well-known data is not found (file does not exist server side, we got a 404). + */ + data object NotFound : RemoteEnterpriseConfigResult + + /** + * Any other error. + */ + data class Error(val exception: Exception) : RemoteEnterpriseConfigResult + + fun dataOrNull(): T? = when (this) { + is Success -> data + is Outdated -> data + is Error -> null + is NotFound -> null + } + + fun upToDateDataOrNull(): T? = when (this) { + is Success -> data + is Outdated -> null + is Error -> null + is NotFound -> null + } +} diff --git a/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultClientBuilderEnterpriseHook.kt b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultClientBuilderEnterpriseHook.kt new file mode 100644 index 0000000000..ee22e4399d --- /dev/null +++ b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultClientBuilderEnterpriseHook.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.impl + +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesBinding +import io.element.android.features.enterprise.api.ClientBuilderEnterpriseHook +import io.element.android.libraries.matrix.api.MatrixClientBuilder +import io.element.android.libraries.matrix.api.core.SessionId + +/** + * Default implementation of [ClientBuilderEnterpriseHook] that does nothing for FOSS. + */ +@ContributesBinding(AppScope::class) +class DefaultClientBuilderEnterpriseHook : ClientBuilderEnterpriseHook { + override suspend fun invoke(clientBuilder: MatrixClientBuilder, sessionId: SessionId): MatrixClientBuilder { + // No modification + return clientBuilder + } +} diff --git a/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultClientEnterpriseHook.kt b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultClientEnterpriseHook.kt new file mode 100644 index 0000000000..b0c0152d94 --- /dev/null +++ b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultClientEnterpriseHook.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.impl + +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesBinding +import io.element.android.features.enterprise.api.ClientEnterpriseHook +import io.element.android.libraries.matrix.api.MatrixClient + +/** + * Default implementation of [ClientEnterpriseHook] that does nothing for FOSS. + */ +@ContributesBinding(AppScope::class) +class DefaultClientEnterpriseHook : ClientEnterpriseHook { + override suspend fun invoke(client: MatrixClient) { + // No-op + } +} diff --git a/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseService.kt b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseService.kt index bc2a3f1bf1..bb10550369 100644 --- a/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseService.kt +++ b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseService.kt @@ -14,19 +14,18 @@ import dev.zacsweers.metro.ContributesBinding import io.element.android.compound.colors.SemanticColorsLightDark import io.element.android.features.enterprise.api.BugReportUrl import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.libraries.matrix.api.ClientUrlContentFetcher import io.element.android.libraries.matrix.api.core.SessionId -import io.element.android.libraries.wellknown.api.ElementWellKnown import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf @ContributesBinding(AppScope::class) class DefaultEnterpriseService : EnterpriseService { - override val isEnterpriseBuild = false - override suspend fun isEnterpriseUser(sessionId: SessionId) = false - override suspend fun tweakMasUrl(url: String, homeserver: String) = url - override fun defaultHomeserverList(): List = emptyList() + override suspend fun tweakMasUrl(url: String, urlContentFetcher: ClientUrlContentFetcher) = url + override fun homeserverAllowList(): List = emptyList() override suspend fun isAllowedToConnectToHomeserver(homeserverUrl: String) = true + override suspend fun isElementProEnforced(serverName: String): Boolean = false override suspend fun overrideBrandColor(sessionId: SessionId?, brandColor: String?) = Unit @@ -46,6 +45,4 @@ class DefaultEnterpriseService : EnterpriseService { } override fun getNoisyNotificationChannelId(sessionId: SessionId): String? = null - - override fun overriddenElementWellKnown(): ElementWellKnown? = null } diff --git a/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultIsEnterpriseBuild.kt b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultIsEnterpriseBuild.kt new file mode 100644 index 0000000000..73da4d5d03 --- /dev/null +++ b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/DefaultIsEnterpriseBuild.kt @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.impl + +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesBinding +import io.element.android.features.enterprise.api.IsEnterpriseBuild + +@ContributesBinding(AppScope::class) +class DefaultIsEnterpriseBuild : IsEnterpriseBuild { + override fun invoke(): Boolean = false +} diff --git a/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/remoteconfig/DefaultCustomMapTilerConfigProvider.kt b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/remoteconfig/DefaultCustomMapTilerConfigProvider.kt new file mode 100644 index 0000000000..2b136d3739 --- /dev/null +++ b/features/enterprise/impl-foss/src/main/kotlin/io/element/android/features/enterprise/impl/remoteconfig/DefaultCustomMapTilerConfigProvider.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.impl.remoteconfig + +import dev.zacsweers.metro.ContributesBinding +import io.element.android.features.enterprise.api.remoteconfig.CustomMapTilerConfigProvider +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig +import io.element.android.libraries.di.SessionScope + +@ContributesBinding(SessionScope::class) +class DefaultCustomMapTilerConfigProvider : CustomMapTilerConfigProvider { + override suspend fun get(): Result = Result.success(null) +} diff --git a/features/enterprise/impl-foss/src/test/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseServiceTest.kt b/features/enterprise/impl-foss/src/test/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseServiceTest.kt index 2bee3f8b4d..474990c6d9 100644 --- a/features/enterprise/impl-foss/src/test/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseServiceTest.kt +++ b/features/enterprise/impl-foss/src/test/kotlin/io/element/android/features/enterprise/impl/DefaultEnterpriseServiceTest.kt @@ -19,15 +19,9 @@ import org.junit.Test class DefaultEnterpriseServiceTest { @Test - fun `isEnterpriseBuild is false`() { + fun homeserverWhitelist() { val defaultEnterpriseService = DefaultEnterpriseService() - assertThat(defaultEnterpriseService.isEnterpriseBuild).isFalse() - } - - @Test - fun `defaultHomeserverList should return empty list`() { - val defaultEnterpriseService = DefaultEnterpriseService() - assertThat(defaultEnterpriseService.defaultHomeserverList()).isEmpty() + assertThat(defaultEnterpriseService.homeserverAllowList()).isEmpty() } @Test diff --git a/features/enterprise/test/src/main/kotlin/io/element/android/features/enterprise/test/FakeEnterpriseService.kt b/features/enterprise/test/src/main/kotlin/io/element/android/features/enterprise/test/FakeEnterpriseService.kt index f6379bef30..a8efcb5873 100644 --- a/features/enterprise/test/src/main/kotlin/io/element/android/features/enterprise/test/FakeEnterpriseService.kt +++ b/features/enterprise/test/src/main/kotlin/io/element/android/features/enterprise/test/FakeEnterpriseService.kt @@ -12,8 +12,8 @@ import androidx.compose.ui.graphics.Color import io.element.android.compound.colors.SemanticColorsLightDark import io.element.android.features.enterprise.api.BugReportUrl import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.libraries.matrix.api.ClientUrlContentFetcher import io.element.android.libraries.matrix.api.core.SessionId -import io.element.android.libraries.wellknown.api.ElementWellKnown import io.element.android.tests.testutils.lambda.lambdaError import io.element.android.tests.testutils.simulateLongTask import kotlinx.coroutines.flow.Flow @@ -21,7 +21,6 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow class FakeEnterpriseService( - override val isEnterpriseBuild: Boolean = false, private val isEnterpriseUserResult: (SessionId) -> Boolean = { lambdaError() }, private val defaultHomeserverListResult: () -> List = { emptyList() }, private val isAllowedToConnectToHomeserverResult: (String) -> Boolean = { lambdaError() }, @@ -31,8 +30,8 @@ class FakeEnterpriseService( private val firebasePushGatewayResult: () -> String? = { lambdaError() }, private val unifiedPushDefaultPushGatewayResult: () -> String? = { lambdaError() }, private val getNoisyNotificationChannelIdResult: (SessionId?) -> String? = { lambdaError() }, - private val tweakMasUrlResult: (String, String) -> String = { _, _ -> lambdaError() }, - private val overrideWellKnownResult: () -> ElementWellKnown? = { lambdaError() }, + private val tweakMasUrlResult: (String, ClientUrlContentFetcher) -> String = { _, _ -> lambdaError() }, + private val isElementProEnforcedResult: (String) -> Boolean = { lambdaError() }, ) : EnterpriseService { private val brandColorState = MutableStateFlow(initialBrandColor) private val semanticColorsState = MutableStateFlow(initialSemanticColors) @@ -41,11 +40,11 @@ class FakeEnterpriseService( isEnterpriseUserResult(sessionId) } - override suspend fun tweakMasUrl(url: String, homeserver: String): String = simulateLongTask { - tweakMasUrlResult(url, homeserver) + override suspend fun tweakMasUrl(url: String, urlContentFetcher: ClientUrlContentFetcher): String = simulateLongTask { + tweakMasUrlResult(url, urlContentFetcher) } - override fun defaultHomeserverList(): List { + override fun homeserverAllowList(): List { return defaultHomeserverListResult() } @@ -53,6 +52,10 @@ class FakeEnterpriseService( isAllowedToConnectToHomeserverResult(homeserverUrl) } + override suspend fun isElementProEnforced(serverName: String): Boolean = simulateLongTask { + isElementProEnforcedResult(serverName) + } + override suspend fun overrideBrandColor(sessionId: SessionId?, brandColor: String?) = simulateLongTask { overrideBrandColorResult(sessionId, brandColor) } @@ -81,8 +84,4 @@ class FakeEnterpriseService( override fun getNoisyNotificationChannelId(sessionId: SessionId): String? { return getNoisyNotificationChannelIdResult(sessionId) } - - override fun overriddenElementWellKnown(): ElementWellKnown? { - return overrideWellKnownResult() - } } diff --git a/features/enterprise/test/src/main/kotlin/io/element/android/features/enterprise/test/remoteconfig/Fixtures.kt b/features/enterprise/test/src/main/kotlin/io/element/android/features/enterprise/test/remoteconfig/Fixtures.kt new file mode 100644 index 0000000000..fd429eada5 --- /dev/null +++ b/features/enterprise/test/src/main/kotlin/io/element/android/features/enterprise/test/remoteconfig/Fixtures.kt @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.enterprise.test.remoteconfig + +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig + +fun aMapTilerConfig( + apiKey: String = "test_api_key", + baseUrl: String? = null, + lightStyleId: String? = null, + darkStyleId: String? = null, +) = MapTilerConfig( + apiKey = apiKey, + baseUrl = baseUrl, + lightStyleId = lightStyleId, + darkStyleId = darkStyleId, +) diff --git a/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesStateProvider.kt b/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesStatePreviewParam.kt similarity index 92% rename from features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesStateProvider.kt rename to features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesStatePreviewParam.kt index bbb5b380ae..8ff621c2a6 100644 --- a/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesStateProvider.kt +++ b/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.core.RoomId -open class ForwardMessagesStateProvider : PreviewParameterProvider { +open class ForwardMessagesStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aForwardMessagesState(), diff --git a/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesView.kt b/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesView.kt index 8065054b2d..f350c5b516 100644 --- a/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesView.kt +++ b/features/forward/impl/src/main/kotlin/io/element/android/features/forward/impl/ForwardMessagesView.kt @@ -38,7 +38,7 @@ fun ForwardMessagesView( @PreviewsDayNight @Composable -internal fun ForwardMessagesViewPreview(@PreviewParameter(ForwardMessagesStateProvider::class) state: ForwardMessagesState) = ElementPreview { +internal fun ForwardMessagesViewPreview(@PreviewParameter(ForwardMessagesStatePreviewParam::class) state: ForwardMessagesState) = ElementPreview { ForwardMessagesView( state = state, onForwardSuccess = {} diff --git a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/di/FtueModule.kt b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/di/FtueBindingContainer.kt similarity index 82% rename from features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/di/FtueModule.kt rename to features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/di/FtueBindingContainer.kt index 52f7a43bde..3ba42f687f 100644 --- a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/di/FtueModule.kt +++ b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/di/FtueBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.di.SessionScope @ContributesTo(SessionScope::class) @BindingContainer -interface FtueModule { +interface FtueBindingContainer { @Binds - fun bindChooseSelfVerificationMethodPresenter(presenter: ChooseSelfVerificationModePresenter): Presenter + fun bindChooseSelfVerificationModePresenter(presenter: ChooseSelfVerificationModePresenter): Presenter } diff --git a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInStateProvider.kt b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInStatePreviewParam.kt similarity index 88% rename from features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInStateProvider.kt rename to features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInStatePreviewParam.kt index 1b2e5d2d58..07569a238e 100644 --- a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInStateProvider.kt +++ b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.ftue.impl.notifications import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.permissions.api.aPermissionsState -open class NotificationsOptInStateProvider : PreviewParameterProvider { +open class NotificationsOptInStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aNotificationsOptInState(), diff --git a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInView.kt b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInView.kt index 6955d8e501..e2eabe8f2b 100644 --- a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInView.kt +++ b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/notifications/NotificationsOptInView.kt @@ -178,7 +178,7 @@ private fun NotificationRow( @PreviewsDayNight @Composable internal fun NotificationsOptInViewPreview( - @PreviewParameter(NotificationsOptInStateProvider::class) state: NotificationsOptInState + @PreviewParameter(NotificationsOptInStatePreviewParam::class) state: NotificationsOptInState ) { ElementPreview { NotificationsOptInView( diff --git a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeStateProvider.kt b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeStatePreviewParam.kt similarity index 97% rename from features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeStateProvider.kt rename to features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeStatePreviewParam.kt index b35a9624b9..1af6786289 100644 --- a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeStateProvider.kt +++ b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.logout.api.direct.aDirectLogoutState import io.element.android.libraries.architecture.AsyncData -class ChooseSelfVerificationModeStateProvider : +class ChooseSelfVerificationModeStatePreviewParam : PreviewParameterProvider { override val values = sequenceOf( aChooseSelfVerificationModeState( diff --git a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeView.kt b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeView.kt index 1bfa10daf2..96d6b82d47 100644 --- a/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeView.kt +++ b/features/ftue/impl/src/main/kotlin/io/element/android/features/ftue/impl/sessionverification/choosemode/ChooseSelfVerificationModeView.kt @@ -149,7 +149,7 @@ private fun ChooseSelfVerificationModeButtons( @PreviewsDayNight @Composable internal fun ChooseSelfVerificationModeViewPreview( - @PreviewParameter(ChooseSelfVerificationModeStateProvider::class) state: ChooseSelfVerificationModeState + @PreviewParameter(ChooseSelfVerificationModeStatePreviewParam::class) state: ChooseSelfVerificationModeState ) = ElementPreview { ChooseSelfVerificationModeView( state = state, diff --git a/features/ftue/impl/src/main/res/values-ar/translations.xml b/features/ftue/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..afd974d4bb --- /dev/null +++ b/features/ftue/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,15 @@ + + + "لا يمكنك التأكيد؟" + "إنشاء مفتاح استرداد جديد" + "اختر طريقة التحقق لإعداد المراسلة الآمنة." + "تأكيد هويتك الرقمية" + "استخدام جهاز آخر" + "استخدام مفتاح الاسترداد" + "يمكنك الآن قراءة الرسائل أو إرسالها بأمان، ويمكن لأي شخص تدردش معه أن يثق بهذا الجهاز أيضًا." + "تم التحقق من الجهاز" + "استخدام جهاز آخر" + "في انتظار الجهاز الآخر…" + "يمكنك تغيير إعداداتك لاحقاً." + "السماح بالإشعارات وعدم تفويت أي رسالة" + diff --git a/features/ftue/impl/src/main/res/values-es/translations.xml b/features/ftue/impl/src/main/res/values-es/translations.xml index 8f49a77e0d..9b232f8dab 100644 --- a/features/ftue/impl/src/main/res/values-es/translations.xml +++ b/features/ftue/impl/src/main/res/values-es/translations.xml @@ -2,8 +2,8 @@ "¿No puedes confirmar?" "Crear una nueva clave de recuperación" - "Verifica este dispositivo para configurar la mensajería segura." - "Confirma que eres tú" + "Elige cómo verificar para configurar la mensajería segura." + "Confirma tu identidad digital" "Usar otro dispositivo" "Usar clave de recuperación" "Ahora puedes leer o enviar mensajes de forma segura y cualquier persona con la que chatees también puede confiar en este dispositivo." diff --git a/features/home/api/src/main/kotlin/io/element/android/features/home/api/HomeEntryPoint.kt b/features/home/api/src/main/kotlin/io/element/android/features/home/api/HomeEntryPoint.kt index 1a90245611..1c6a0a906e 100644 --- a/features/home/api/src/main/kotlin/io/element/android/features/home/api/HomeEntryPoint.kt +++ b/features/home/api/src/main/kotlin/io/element/android/features/home/api/HomeEntryPoint.kt @@ -12,6 +12,7 @@ import com.bumble.appyx.core.modality.BuildContext import com.bumble.appyx.core.node.Node import com.bumble.appyx.core.plugin.Plugin import io.element.android.libraries.architecture.FeatureEntryPoint +import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.room.JoinedRoom @@ -23,7 +24,7 @@ interface HomeEntryPoint : FeatureEntryPoint { ): Node interface Callback : Plugin { - fun navigateToRoom(roomId: RoomId, joinedRoom: JoinedRoom?) + fun navigateToRoom(roomId: RoomId, eventId: EventId?, joinedRoom: JoinedRoom?) fun navigateToCreateRoom() fun navigateToCreateSpace() fun navigateToSettings() diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeFlowNode.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeFlowNode.kt index 00f285e3f4..20f27f67bd 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeFlowNode.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeFlowNode.kt @@ -56,6 +56,7 @@ import io.element.android.libraries.designsystem.utils.DelayedVisibility import io.element.android.libraries.di.SessionScope import io.element.android.libraries.di.annotations.SessionCoroutineScope import io.element.android.libraries.matrix.api.MatrixClient +import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.services.analytics.api.AnalyticsService import kotlinx.coroutines.CoroutineScope @@ -183,6 +184,7 @@ class HomeFlowNode( fun navigateToRoom( roomId: RoomId, + eventId: EventId?, ) { if (!loadingJoinedRoomJob.value.isUninitialized()) { Timber.w("Already loading a room, ignoring navigateToRoom for $roomId") @@ -195,7 +197,7 @@ class HomeFlowNode( }.fold( onSuccess = { joinedRoom -> if (isActive) { - callback.navigateToRoom(roomId, joinedRoom) + callback.navigateToRoom(roomId = roomId, eventId = eventId, joinedRoom = joinedRoom) loadingJoinedRoomJob.value = AsyncData.Success(coroutineContext.job) // Wait a bit before resetting the state to avoid allowing to open several rooms delay(200.milliseconds) @@ -205,7 +207,7 @@ class HomeFlowNode( onFailure = { // If the operation wasn't cancelled, navigate without the room, using the room id if (it !is CancellationException) { - callback.navigateToRoom(roomId, null) + callback.navigateToRoom(roomId = roomId, eventId = null, joinedRoom = null) } loadingJoinedRoomJob.value = AsyncData.Failure(error = it, prevData = coroutineContext.job) // Wait a bit before resetting the state to avoid allowing to open several rooms @@ -233,7 +235,7 @@ class HomeFlowNode( acceptDeclineInviteView = { acceptDeclineInviteView.Render( state = state.roomListState.acceptDeclineInviteState, - onAcceptInviteSuccess = ::navigateToRoom, + onAcceptInviteSuccess = { navigateToRoom(roomId = it, eventId = null) }, onDeclineInviteSuccess = { }, modifier = Modifier ) @@ -269,6 +271,11 @@ class HomeFlowNode( parentNode = this, buildContext = buildContext, inviteData = navTarget.inviteData, + callback = object : DeclineInviteAndBlockEntryPoint.Callback { + override fun onDeclineSuccess() { + backstack.pop() + } + }, ) } is NavTarget.SelectNewOwnersWhenLeavingRoom -> { diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeStateProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeStatePreviewParam.kt similarity index 96% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeStateProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeStatePreviewParam.kt index ea9ff7a234..14ab6dc7f6 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeStateProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.home.impl import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.home.impl.roomlist.RoomListState -import io.element.android.features.home.impl.roomlist.RoomListStateProvider +import io.element.android.features.home.impl.roomlist.RoomListStatePreviewParam import io.element.android.features.home.impl.roomlist.aRoomListState import io.element.android.features.home.impl.roomlist.aRoomsContentState import io.element.android.features.home.impl.roomlist.generateRoomListRoomSummaryList @@ -24,7 +24,7 @@ import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.ui.strings.CommonStrings import kotlinx.collections.immutable.toImmutableList -open class HomeStateProvider : PreviewParameterProvider { +open class HomeStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aHomeState(), @@ -43,7 +43,7 @@ open class HomeStateProvider : PreviewParameterProvider { aHomeState( currentHomeNavigationBarItem = HomeNavigationBarItem.Spaces, ), - ) + RoomListStateProvider().values.map { + ) + RoomListStatePreviewParam().values.map { aHomeState(roomListState = it) } + aHomeState( currentHomeNavigationBarItem = HomeNavigationBarItem.Spaces, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeView.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeView.kt index f5a2400f2f..024d013871 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeView.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/HomeView.kt @@ -55,6 +55,8 @@ import io.element.android.features.home.impl.roomlist.RoomListContextMenu import io.element.android.features.home.impl.roomlist.RoomListDeclineInviteMenu import io.element.android.features.home.impl.roomlist.RoomListEvent import io.element.android.features.home.impl.roomlist.RoomListState +import io.element.android.features.home.impl.search.GlobalSearchEvent +import io.element.android.features.home.impl.search.GlobalSearchView import io.element.android.features.home.impl.search.RoomListSearchView import io.element.android.features.home.impl.spacefilters.SpaceFiltersEvent import io.element.android.features.home.impl.spacefilters.SpaceFiltersState @@ -73,6 +75,7 @@ import io.element.android.libraries.designsystem.utils.lazyColumnContentPadding import io.element.android.libraries.designsystem.utils.scaffoldScrollableContentInsets import io.element.android.libraries.designsystem.utils.snackbar.SnackbarHost import io.element.android.libraries.designsystem.utils.snackbar.rememberSnackbarHostState +import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.ui.strings.CommonStrings import kotlinx.coroutines.launch @@ -80,7 +83,7 @@ import kotlinx.coroutines.launch @Composable fun HomeView( homeState: HomeState, - onRoomClick: (RoomId) -> Unit, + onRoomClick: (RoomId, EventId?) -> Unit, onSettingsClick: () -> Unit, onSetUpRecoveryClick: () -> Unit, onConfirmRecoveryKeyClick: () -> Unit, @@ -122,22 +125,34 @@ fun HomeView( state = homeState, onSetUpRecoveryClick = onSetUpRecoveryClick, onConfirmRecoveryKeyClick = onConfirmRecoveryKeyClick, - onRoomClick = { if (firstThrottler.canHandle()) onRoomClick(it) }, + onRoomClick = { roomId -> if (firstThrottler.canHandle()) onRoomClick(roomId, null) }, onOpenSettings = { if (firstThrottler.canHandle()) onSettingsClick() }, onStartChatClick = { if (firstThrottler.canHandle()) onStartChatClick() }, onCreateSpaceClick = { if (firstThrottler.canHandle()) onCreateSpaceClick() }, onMenuActionClick = onMenuActionClick, ) - // This overlaid view will only be visible when state.displaySearchResults is true - RoomListSearchView( - state = state.searchState, - eventSink = state.eventSink, - hideInvitesAvatars = state.hideInvitesAvatars, - onRoomClick = { if (firstThrottler.canHandle()) onRoomClick(it) }, - modifier = Modifier - .fillMaxSize() - .background(ElementTheme.colors.bgCanvasDefault) - ) + + if (state.globalSearchState.isEnabled) { + GlobalSearchView( + state = state.globalSearchState, + onSelectSearchResult = { roomId, eventId -> if (firstThrottler.canHandle()) onRoomClick(roomId, eventId) }, + modifier = Modifier + .fillMaxSize() + .background(ElementTheme.colors.bgCanvasDefault), + ) + } else { + // This overlaid view will only be visible when state.displaySearchResults is true + RoomListSearchView( + state = state.searchState, + eventSink = state.eventSink, + hideInvitesAvatars = state.hideInvitesAvatars, + onRoomClick = { roomId -> if (firstThrottler.canHandle()) onRoomClick(roomId, null) }, + modifier = Modifier + .fillMaxSize() + .background(ElementTheme.colors.bgCanvasDefault) + ) + } + acceptDeclineInviteView() } } @@ -186,8 +201,18 @@ private fun HomeScaffold( selectedNavigationItem = state.currentHomeNavigationBarItem, currentUserAndNeighbors = state.currentUserAndNeighbors, showAvatarIndicator = state.showAvatarIndicator, - areSearchResultsDisplayed = roomListState.searchState.isSearchActive, - onToggleSearch = { roomListState.eventSink(RoomListEvent.ToggleSearchResults) }, + areSearchResultsDisplayed = if (roomListState.globalSearchState.isEnabled) { + roomListState.globalSearchState.isSearchActive + } else { + roomListState.searchState.isSearchActive + }, + onToggleSearch = { + if (roomListState.globalSearchState.isEnabled) { + roomListState.globalSearchState.eventSink(GlobalSearchEvent.ToggleSearchVisibility) + } else { + roomListState.eventSink(RoomListEvent.ToggleSearchResults) + } + }, onMenuActionClick = onMenuActionClick, onOpenSettings = onOpenSettings, onAccountSwitch = { @@ -346,10 +371,10 @@ internal fun RoomListRoomSummary.contentType() = displayType.ordinal @PreviewsDayNight @Composable -internal fun HomeViewPreview(@PreviewParameter(HomeStateProvider::class) state: HomeState) = ElementPreview { +internal fun HomeViewPreview(@PreviewParameter(HomeStatePreviewParam::class) state: HomeState) = ElementPreview { HomeView( homeState = state, - onRoomClick = {}, + onRoomClick = { _, _ -> }, onSettingsClick = {}, onSetUpRecoveryClick = {}, onConfirmRecoveryKeyClick = {}, @@ -369,7 +394,7 @@ internal fun HomeViewPreview(@PreviewParameter(HomeStateProvider::class) state: internal fun HomeViewA11yPreview() = ElementPreview { HomeView( homeState = aHomeState(), - onRoomClick = {}, + onRoomClick = { _, _ -> }, onSettingsClick = {}, onSetUpRecoveryClick = {}, onConfirmRecoveryKeyClick = {}, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/HomeTopBar.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/HomeTopBar.kt index 8163d29d92..63d28dca21 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/HomeTopBar.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/HomeTopBar.kt @@ -8,6 +8,8 @@ package io.element.android.features.home.impl.components +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.RowScope @@ -15,9 +17,11 @@ import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.pager.VerticalPager import androidx.compose.foundation.pager.rememberPagerState @@ -25,8 +29,11 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.material3.rememberTopAppBarState +import androidx.compose.material3.ripple import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue @@ -37,10 +44,20 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.CompositingStrategy +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import io.element.android.appconfig.RoomListConfig import io.element.android.compound.theme.ElementTheme @@ -71,10 +88,13 @@ import io.element.android.libraries.designsystem.theme.components.IconButton import io.element.android.libraries.designsystem.theme.components.Text import io.element.android.libraries.designsystem.theme.components.TopAppBar import io.element.android.libraries.matrix.api.core.SessionId +import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.MatrixUser +import io.element.android.libraries.matrix.api.user.UserStatus import io.element.android.libraries.matrix.ui.components.aMatrixUser import io.element.android.libraries.matrix.ui.components.aMatrixUserList import io.element.android.libraries.matrix.ui.model.getAvatarData +import io.element.android.libraries.matrix.ui.model.toEmojiText import io.element.android.libraries.testtags.TestTags import io.element.android.libraries.testtags.testTag import io.element.android.libraries.ui.strings.CommonStrings @@ -151,7 +171,7 @@ fun HomeTopBar( }, // We want a 16dp left padding for the navigationIcon : // 4dp from default TopAppBarHorizontalPadding - // 8dp from AccountIcon default padding (because of IconButton) + // 8dp from AccountIcon default padding (48dp touch target around 32dp avatar) // 4dp extra padding using left insets windowInsets = WindowInsets(left = 4.dp), ) @@ -316,19 +336,36 @@ private fun AccountIcon( modifier: Modifier = Modifier, ) { val testTag = if (isCurrentAccount) Modifier.testTag(TestTags.homeScreenSettings) else Modifier - IconButton( - modifier = modifier.then(testTag), - onClick = onClick, + val interactionSource = remember { MutableInteractionSource() } + Box( + modifier = modifier + .then(testTag) + .minimumInteractiveComponentSize() + .clickable( + interactionSource = interactionSource, + onClick = onClick, + indication = ripple(bounded = false), + ), + contentAlignment = Alignment.Center, ) { - Box { val avatarData by remember(matrixUser) { derivedStateOf { matrixUser.getAvatarData(size = AvatarSize.CurrentUserTopBar) } } + val statusEmoji = matrixUser.displayedStatus?.toEmojiText() + val avatarModifier = if (statusEmoji != null) { + Modifier.eraseStatusEmojiBackground( + parentSize = AvatarSize.CurrentUserTopBar.dp, + layoutDirection = LocalLayoutDirection.current, + ) + } else { + Modifier + } Avatar( avatarData = avatarData, avatarType = AvatarType.User, + modifier = avatarModifier, contentDescription = if (isCurrentAccount) { if (showAvatarIndicator) { stringResource(CommonStrings.a11y_settings_with_required_action) @@ -339,11 +376,69 @@ private fun AccountIcon( null }, ) + if (statusEmoji != null) { + StatusEmojiBadge( + emoji = statusEmoji, + modifier = Modifier.align(Alignment.BottomEnd), + ) + } if (showAvatarIndicator) { RedIndicatorAtom( modifier = Modifier.align(Alignment.TopEnd) ) } + } +} + +private val statusEmojiBadgeSize = 20.dp +private val statusEmojiBadgeRadius = statusEmojiBadgeSize / 2 +private val statusEmojiBadgeOffset = 8.dp + +private fun Modifier.eraseStatusEmojiBackground( + parentSize: Dp, + layoutDirection: LayoutDirection, +): Modifier = this + .graphicsLayer { + compositingStrategy = CompositingStrategy.Offscreen + } + .drawWithContent { + drawContent() + drawCircle( + color = Color.Black, + center = Offset( + x = if (layoutDirection == LayoutDirection.Ltr) { + (parentSize - statusEmojiBadgeRadius + statusEmojiBadgeOffset).toPx() + } else { + (statusEmojiBadgeRadius - statusEmojiBadgeOffset).toPx() + }, + y = size.height - statusEmojiBadgeRadius.toPx(), + ), + radius = statusEmojiBadgeRadius.toPx(), + blendMode = BlendMode.Clear, + ) + } + +@Composable +private fun StatusEmojiBadge( + emoji: String, + modifier: Modifier = Modifier, +) { + val density = LocalDensity.current + // Ensure the emoji size is not affected by the user's font scale settings + val fixedFontScaleDensity = remember(density.density) { + Density(density = density.density, fontScale = 1f) + } + Box( + modifier = modifier + .offset(x = statusEmojiBadgeOffset) + .size(statusEmojiBadgeSize), + contentAlignment = Alignment.Center, + ) { + CompositionLocalProvider(LocalDensity provides fixedFontScaleDensity) { + Text( + text = emoji, + style = ElementTheme.typography.fontBodyMdRegular, + ) } } } @@ -432,6 +527,33 @@ internal fun HomeTopBarWithIndicatorPreview() = ElementPreview { ) } +@OptIn(ExperimentalMaterial3Api::class) +@PreviewsDayNight +@Composable +internal fun HomeTopBarWithStatusPreview() = ElementPreview { + HomeTopBar( + selectedNavigationItem = HomeNavigationBarItem.Chats, + currentUserAndNeighbors = persistentListOf( + aMatrixUser( + id = "@id:domain", + displayName = USER_NAME_ALICE, + displayedStatus = DisplayedStatus.UserSet(UserStatus(emoji = "🌴", text = "Away")), + ) + ), + showAvatarIndicator = false, + areSearchResultsDisplayed = false, + scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState()), + onOpenSettings = {}, + onAccountSwitch = {}, + onToggleSearch = {}, + canReportBug = true, + displayFilters = true, + filtersState = aRoomListFiltersState(), + spaceFiltersState = anUnselectedSpaceFiltersState(), + onMenuActionClick = {}, + ) +} + @OptIn(ExperimentalMaterial3Api::class) @PreviewsDayNight @Composable diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomListContentView.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomListContentView.kt index 266b6f5a59..e06fe7c46d 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomListContentView.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomListContentView.kt @@ -42,7 +42,7 @@ import io.element.android.features.home.impl.filters.selection.FilterSelectionSt import io.element.android.features.home.impl.model.RoomListRoomSummary import io.element.android.features.home.impl.model.RoomSummaryDisplayType import io.element.android.features.home.impl.roomlist.RoomListContentState -import io.element.android.features.home.impl.roomlist.RoomListContentStateProvider +import io.element.android.features.home.impl.roomlist.RoomListContentStatePreviewParam import io.element.android.features.home.impl.roomlist.RoomListEvent import io.element.android.features.home.impl.roomlist.SecurityBannerState import io.element.android.features.home.impl.spacefilters.SpaceFiltersState @@ -336,7 +336,7 @@ private fun EmptyScaffold( @PreviewsDayNight @Composable -internal fun RoomListContentViewPreview(@PreviewParameter(RoomListContentStateProvider::class) state: RoomListContentState) = ElementPreview { +internal fun RoomListContentViewPreview(@PreviewParameter(RoomListContentStatePreviewParam::class) state: RoomListContentState) = ElementPreview { RoomListContentView( contentState = state, filtersState = aRoomListFiltersState( diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomSummaryRow.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomSummaryRow.kt index 2a21518e83..883d8aff76 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomSummaryRow.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/components/RoomSummaryRow.kt @@ -43,7 +43,7 @@ import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.home.impl.R import io.element.android.features.home.impl.model.LatestEvent import io.element.android.features.home.impl.model.RoomListRoomSummary -import io.element.android.features.home.impl.model.RoomListRoomSummaryProvider +import io.element.android.features.home.impl.model.RoomListRoomSummaryPreviewParam import io.element.android.features.home.impl.model.RoomSummaryDisplayType import io.element.android.features.home.impl.roomlist.RoomListEvent import io.element.android.libraries.core.extensions.orEmpty @@ -449,7 +449,7 @@ private fun MentionIndicatorAtom() { @PreviewsDayNight @Composable -internal fun RoomSummaryRowPreview(@PreviewParameter(RoomListRoomSummaryProvider::class) data: RoomListRoomSummary) = ElementPreview { +internal fun RoomSummaryRowPreview(@PreviewParameter(RoomListRoomSummaryPreviewParam::class) data: RoomListRoomSummary) = ElementPreview { RoomSummaryRow( room = data, hideInviteAvatars = false, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/HomeSpacesModule.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/HomeSpacesBindingContainer.kt similarity index 95% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/HomeSpacesModule.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/HomeSpacesBindingContainer.kt index 5e2212375d..989a558718 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/HomeSpacesModule.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/HomeSpacesBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.di.SessionScope @BindingContainer @ContributesTo(SessionScope::class) -interface HomeSpacesModule { +interface HomeSpacesBindingContainer { @Binds fun bindHomeSpacesPresenter(presenter: HomeSpacesPresenter): Presenter } diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/RoomListModule.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/RoomListBindingContainer.kt similarity index 73% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/RoomListModule.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/RoomListBindingContainer.kt index 1eeba4fff7..b275559206 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/RoomListModule.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/di/RoomListBindingContainer.kt @@ -15,6 +15,8 @@ import io.element.android.features.home.impl.filters.RoomListFiltersPresenter import io.element.android.features.home.impl.filters.RoomListFiltersState import io.element.android.features.home.impl.roomlist.RoomListPresenter import io.element.android.features.home.impl.roomlist.RoomListState +import io.element.android.features.home.impl.search.GlobalSearchPresenter +import io.element.android.features.home.impl.search.GlobalSearchState import io.element.android.features.home.impl.search.RoomListSearchPresenter import io.element.android.features.home.impl.search.RoomListSearchState import io.element.android.features.home.impl.spacefilters.SpaceFiltersPresenter @@ -24,16 +26,19 @@ import io.element.android.libraries.di.SessionScope @ContributesTo(SessionScope::class) @BindingContainer -interface RoomListModule { +interface RoomListBindingContainer { @Binds fun bindRoomListPresenter(presenter: RoomListPresenter): Presenter @Binds - fun bindSearchPresenter(presenter: RoomListSearchPresenter): Presenter + fun bindRoomListSearchPresenter(presenter: RoomListSearchPresenter): Presenter @Binds - fun bindFiltersPresenter(presenter: RoomListFiltersPresenter): Presenter + fun bindRoomListFiltersPresenter(presenter: RoomListFiltersPresenter): Presenter @Binds fun bindSpaceFiltersPresenter(presenter: SpaceFiltersPresenter): Presenter + + @Binds + fun bindGlobalSearchPresenter(presenter: GlobalSearchPresenter): Presenter } diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersStateProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersStatePreviewParam.kt similarity index 92% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersStateProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersStatePreviewParam.kt index 7e095512fe..8118a65e1d 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersStateProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.home.impl.filters.selection.FilterSelectionState import kotlinx.collections.immutable.toImmutableList -class RoomListFiltersStateProvider : PreviewParameterProvider { +class RoomListFiltersStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomListFiltersState(), diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersView.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersView.kt index 9931a98c4e..c671eecf45 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersView.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersView.kt @@ -212,7 +212,7 @@ private fun RoomListFilterView( @PreviewsDayNight @Composable -internal fun RoomListFiltersViewPreview(@PreviewParameter(RoomListFiltersStateProvider::class) state: RoomListFiltersState) = ElementPreview { +internal fun RoomListFiltersViewPreview(@PreviewParameter(RoomListFiltersStatePreviewParam::class) state: RoomListFiltersState) = ElementPreview { RoomListFiltersView( modifier = Modifier.padding(vertical = 4.dp), state = state, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/selection/DefaultFilterSelectionStrategy.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/selection/DefaultFilterSelectionStrategy.kt index 847dbc2c39..9b5951ae3d 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/selection/DefaultFilterSelectionStrategy.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/filters/selection/DefaultFilterSelectionStrategy.kt @@ -22,6 +22,7 @@ class DefaultFilterSelectionStrategy : FilterSelectionStrategy { override val filterSelectionStates = MutableStateFlow(buildFilters()) override fun select(filter: RoomListFilter) { + if (selectedFilters.any { it in filter.incompatibleFilters }) return selectedFilters.add(filter) filterSelectionStates.value = buildFilters() } diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/model/RoomListRoomSummaryProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/model/RoomListRoomSummaryPreviewParam.kt similarity index 99% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/model/RoomListRoomSummaryProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/model/RoomListRoomSummaryPreviewParam.kt index 2e75858e3e..c04c3e446b 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/model/RoomListRoomSummaryProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/model/RoomListRoomSummaryPreviewParam.kt @@ -24,7 +24,7 @@ import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.ui.model.InviteSender import kotlinx.collections.immutable.toImmutableList -open class RoomListRoomSummaryProvider : PreviewParameterProvider { +open class RoomListRoomSummaryPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( listOf( diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContentStateProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContentStatePreviewParam.kt similarity index 96% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContentStateProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContentStatePreviewParam.kt index 0ac2b7bf62..4ca87992f9 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContentStateProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContentStatePreviewParam.kt @@ -19,7 +19,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableSet -open class RoomListContentStateProvider : PreviewParameterProvider { +open class RoomListContentStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomsContentState(), diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContextMenu.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContextMenu.kt index bfa6962e8b..6a334a94c2 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContextMenu.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListContextMenu.kt @@ -199,7 +199,7 @@ private fun RoomListModalBottomSheetContent( @PreviewsDayNight @Composable internal fun RoomListContextMenuPreview( - @PreviewParameter(RoomListStateContextMenuShownProvider::class) contextMenu: RoomListState.ContextMenu.Shown + @PreviewParameter(RoomListStateContextMenuShownPreviewParam::class) contextMenu: RoomListState.ContextMenu.Shown ) = ElementPreview(fillMaxSize = true) { RoomListContextMenu( contextMenu = contextMenu, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListDeclineInviteMenu.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListDeclineInviteMenu.kt index 0a7a29ebc2..022696cbb1 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListDeclineInviteMenu.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListDeclineInviteMenu.kt @@ -126,7 +126,7 @@ private fun RoomListDeclineInviteMenuContent( @PreviewsDayNight @Composable internal fun RoomListDeclineInviteMenuPreview( - @PreviewParameter(RoomListStateDeclineInviteMenuShownProvider::class) menu: RoomListState.DeclineInviteMenu.Shown, + @PreviewParameter(RoomListStateDeclineInviteMenuShownPreviewParam::class) menu: RoomListState.DeclineInviteMenu.Shown, ) = ElementPreview { RoomListDeclineInviteMenu( menu = menu, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenter.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenter.kt index fe09bd7cd1..1c21177988 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenter.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenter.kt @@ -30,6 +30,7 @@ import io.element.android.features.announcement.api.AnnouncementService import io.element.android.features.home.impl.datasource.RoomListDataSource import io.element.android.features.home.impl.filters.RoomListFiltersState import io.element.android.features.home.impl.filters.into +import io.element.android.features.home.impl.search.GlobalSearchState import io.element.android.features.home.impl.search.RoomListSearchEvent import io.element.android.features.home.impl.search.RoomListSearchState import io.element.android.features.home.impl.spacefilters.SpaceFiltersState @@ -85,6 +86,7 @@ class RoomListPresenter( private val announcementService: AnnouncementService, private val coldStartWatcher: AnalyticsColdStartWatcher, private val spaceFiltersPresenter: Presenter, + private val globalSearchPresenter: Presenter, private val featureFlagService: FeatureFlagService, ) : Presenter { private val encryptionService = client.encryptionService @@ -97,6 +99,7 @@ class RoomListPresenter( val searchState = searchPresenter.present() val spaceFiltersState = spaceFiltersPresenter.present() val acceptDeclineInviteState = acceptDeclineInvitePresenter.present() + val globalSearchState = globalSearchPresenter.present() LaunchedEffect(Unit) { roomListDataSource.launchIn(this) @@ -177,6 +180,7 @@ class RoomListPresenter( leaveRoomState = leaveRoomState, filtersState = filtersState, searchState = searchState, + globalSearchState = globalSearchState, spaceFiltersState = spaceFiltersState, contentState = contentState, acceptDeclineInviteState = acceptDeclineInviteState, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListState.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListState.kt index e184a5a57f..4164c56e9d 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListState.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListState.kt @@ -11,6 +11,7 @@ package io.element.android.features.home.impl.roomlist import androidx.compose.runtime.Immutable import io.element.android.features.home.impl.filters.RoomListFiltersState import io.element.android.features.home.impl.model.RoomListRoomSummary +import io.element.android.features.home.impl.search.GlobalSearchState import io.element.android.features.home.impl.search.RoomListSearchState import io.element.android.features.home.impl.spacefilters.SpaceFiltersState import io.element.android.features.invite.api.acceptdecline.AcceptDeclineInviteState @@ -27,6 +28,7 @@ data class RoomListState( val leaveRoomState: LeaveRoomState, val filtersState: RoomListFiltersState, val searchState: RoomListSearchState, + val globalSearchState: GlobalSearchState, val spaceFiltersState: SpaceFiltersState, val contentState: RoomListContentState, val acceptDeclineInviteState: AcceptDeclineInviteState, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateContextMenuShownProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateContextMenuShownPreviewParam.kt similarity index 90% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateContextMenuShownProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateContextMenuShownPreviewParam.kt index eca1b63d7d..f4bd0eac2e 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateContextMenuShownProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateContextMenuShownPreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.home.impl.roomlist import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.matrix.api.core.RoomId -open class RoomListStateContextMenuShownProvider : PreviewParameterProvider { +open class RoomListStateContextMenuShownPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aContextMenuShown(hasNewContent = true), diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateDeclineInviteMenuShownProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateDeclineInviteMenuShownPreviewParam.kt similarity index 90% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateDeclineInviteMenuShownProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateDeclineInviteMenuShownPreviewParam.kt index 73d4785e96..c19da0595a 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateDeclineInviteMenuShownProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateDeclineInviteMenuShownPreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.datasource.LoremIpsum import io.element.android.features.home.impl.model.RoomListRoomSummary import io.element.android.features.home.impl.model.aRoomListRoomSummary -open class RoomListStateDeclineInviteMenuShownProvider : PreviewParameterProvider { +open class RoomListStateDeclineInviteMenuShownPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDeclineInviteMenuShown(), diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStatePreviewParam.kt similarity index 91% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStatePreviewParam.kt index 97600e0247..04f612870f 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStateProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/roomlist/RoomListStatePreviewParam.kt @@ -16,7 +16,9 @@ import io.element.android.features.home.impl.model.RoomListRoomSummary import io.element.android.features.home.impl.model.RoomSummaryDisplayType import io.element.android.features.home.impl.model.aRoomListRoomSummary import io.element.android.features.home.impl.model.anInviteSender +import io.element.android.features.home.impl.search.GlobalSearchState import io.element.android.features.home.impl.search.RoomListSearchState +import io.element.android.features.home.impl.search.aGlobalSearchState import io.element.android.features.home.impl.search.aRoomListSearchState import io.element.android.features.home.impl.spacefilters.SpaceFiltersState import io.element.android.features.home.impl.spacefilters.anUnselectedSpaceFiltersState @@ -31,7 +33,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -open class RoomListStateProvider : PreviewParameterProvider { +open class RoomListStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomListState(), @@ -41,7 +43,10 @@ open class RoomListStateProvider : PreviewParameterProvider { aRoomListState(contentState = aRoomsContentState(securityBannerState = SecurityBannerState.RecoveryKeyConfirmation)), aRoomListState(contentState = anEmptyContentState()), aRoomListState(contentState = aSkeletonContentState()), - aRoomListState(searchState = aRoomListSearchState(isSearchActive = true, query = "Test")), + aRoomListState( + searchState = aRoomListSearchState(isSearchActive = true, query = "Test"), + globalSearchState = aGlobalSearchState(isEnabled = false), + ), aRoomListState(contentState = aRoomsContentState(securityBannerState = SecurityBannerState.SetUpRecovery)), aRoomListState(contentState = aRoomsContentState(batteryOptimizationState = aBatteryOptimizationState(shouldDisplayBanner = true))), aRoomListState(contentState = anEmptyContentState(securityBannerState = SecurityBannerState.RecoveryKeyConfirmation)), @@ -53,6 +58,7 @@ internal fun aRoomListState( declineInviteMenu: RoomListState.DeclineInviteMenu = RoomListState.DeclineInviteMenu.Hidden, leaveRoomState: LeaveRoomState = aLeaveRoomState(), searchState: RoomListSearchState = aRoomListSearchState(), + globalSearchState: GlobalSearchState = aGlobalSearchState(), filtersState: RoomListFiltersState = aRoomListFiltersState(), spaceFiltersState: SpaceFiltersState = anUnselectedSpaceFiltersState(), contentState: RoomListContentState = aRoomsContentState(), @@ -66,6 +72,7 @@ internal fun aRoomListState( leaveRoomState = leaveRoomState, filtersState = filtersState, searchState = searchState, + globalSearchState = globalSearchState, spaceFiltersState = spaceFiltersState, contentState = contentState, acceptDeclineInviteState = acceptDeclineInviteState, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchEvent.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchEvent.kt new file mode 100644 index 0000000000..76d9147e94 --- /dev/null +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchEvent.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.home.impl.search + +import androidx.compose.runtime.Immutable + +@Immutable +sealed interface GlobalSearchEvent { + object ClearQuery : GlobalSearchEvent + object ToggleSearchVisibility : GlobalSearchEvent + data class UpdateVisibleRange(val range: IntRange) : GlobalSearchEvent + data class UpdateTarget(val target: GlobalSearchTarget) : GlobalSearchEvent +} diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchPresenter.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchPresenter.kt new file mode 100644 index 0000000000..6e153344c9 --- /dev/null +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchPresenter.kt @@ -0,0 +1,301 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.home.impl.search + +import androidx.compose.foundation.text.input.clearText +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import dev.zacsweers.metro.Inject +import io.element.android.libraries.androidutils.filesize.FileSizeFormatter +import io.element.android.libraries.architecture.AsyncData +import io.element.android.libraries.architecture.Presenter +import io.element.android.libraries.core.coroutine.CoroutineDispatchers +import io.element.android.libraries.dateformatter.api.DateFormatter +import io.element.android.libraries.dateformatter.api.DateFormatterMode +import io.element.android.libraries.eventformatter.api.RoomLatestEventFormatter +import io.element.android.libraries.featureflag.api.FeatureFlagService +import io.element.android.libraries.featureflag.api.FeatureFlags +import io.element.android.libraries.matrix.api.MatrixClient +import io.element.android.libraries.matrix.api.permalink.PermalinkParser +import io.element.android.libraries.matrix.api.room.RoomInfo +import io.element.android.libraries.matrix.api.roomlist.LatestEventValue +import io.element.android.libraries.matrix.api.search.MessageSearch +import io.element.android.libraries.matrix.api.search.MessageSearchPaginationState +import io.element.android.libraries.matrix.api.search.MessageSearchResult +import io.element.android.libraries.matrix.api.search.MessageSearchService +import io.element.android.libraries.matrix.api.timeline.item.event.AudioMessageType +import io.element.android.libraries.matrix.api.timeline.item.event.FileMessageType +import io.element.android.libraries.matrix.api.timeline.item.event.ImageMessageType +import io.element.android.libraries.matrix.api.timeline.item.event.MessageContent +import io.element.android.libraries.matrix.api.timeline.item.event.MessageTypeWithAttachment +import io.element.android.libraries.matrix.api.timeline.item.event.StickerMessageType +import io.element.android.libraries.matrix.api.timeline.item.event.VideoMessageType +import io.element.android.libraries.matrix.api.timeline.item.event.VoiceMessageType +import io.element.android.libraries.matrix.api.timeline.item.event.isMediaContent +import io.element.android.libraries.matrix.ui.components.AttachmentThumbnailType +import io.element.android.libraries.matrix.ui.messages.toPlainText +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.toImmutableList +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import timber.log.Timber +import kotlin.jvm.optionals.getOrElse +import kotlin.time.Duration.Companion.milliseconds + +@Inject +class GlobalSearchPresenter( + private val roomListSearchDataSourceFactory: RoomListSearchDataSource.Factory, + private val messageSearchService: MessageSearchService, + private val featureFlagService: FeatureFlagService, + private val latestEventFormatter: RoomLatestEventFormatter, + private val dateFormatter: DateFormatter, + private val fileSizeFormatter: FileSizeFormatter, + private val permalinkParser: PermalinkParser, + private val coroutineDispatchers: CoroutineDispatchers, + private val matrixClient: MatrixClient, +) : Presenter { + @Composable + override fun present(): GlobalSearchState { + val coroutineScope = rememberCoroutineScope() + val isEnabled by produceState(false) { + featureFlagService.isFeatureEnabledFlow(FeatureFlags.MessageSearch).collectLatest { value = it } + } + val roomListSearchDataSource = remember { roomListSearchDataSourceFactory.create(coroutineScope = coroutineScope) } + val queryState = rememberTextFieldState() + var isSearchActive by remember { mutableStateOf(false) } + var searchResults: AsyncData by remember { mutableStateOf(AsyncData.Uninitialized) } + var currentTarget: GlobalSearchTarget by remember { mutableStateOf(GlobalSearchTarget.ROOMS) } + val currentMessageSearch: MessageSearch = remember { messageSearchService.createMessageSearch(scope = coroutineScope) } + + LaunchedEffect(queryState.text) { + // Add a delay to avoid performing too many searches in a short period of time, which can be expensive + delay(200.milliseconds) + + searchResults = if (queryState.text.isNotEmpty()) { + AsyncData.Loading(prevData = searchResults.dataOrNull()) + } else { + AsyncData.Uninitialized + } + + launch { roomListSearchDataSource.setSearchQuery(queryState.text.toString()) } + launch { + currentMessageSearch.setQuery(queryState.text.toString()) + .onFailure { Timber.e(it, "Could not set query for message search") } + } + } + + LaunchedEffect(currentTarget) { + if (queryState.text.isNotEmpty()) { + searchResults = AsyncData.Loading() + } + + when (currentTarget) { + GlobalSearchTarget.ROOMS -> { + roomListSearchDataSource.roomSummaries.collectLatest { results -> + Timber.d("Room list search found ${results.size} items") + // The room list data source always returns some values, even if the query is empty, + // so we only want to update the search results if the query is not empty + searchResults = if (queryState.text.isNotEmpty()) { + AsyncData.Success(GlobalSearchResults.RoomListResults(results = results)) + } else { + AsyncData.Uninitialized + } + } + } + GlobalSearchTarget.MESSAGES -> { + Timber.d("Message search found ${currentMessageSearch.results.value.size} items") + combine( + currentMessageSearch.results, + currentMessageSearch.paginationState, + ) { results, paginationState -> + Pair(results, paginationState) + }.collectLatest { (results, paginationState) -> + Timber.d("Message search found ${results.size} items, pagination state: $paginationState") + + // Try processing the results in parallel to speed up the processing time, since we have to wait until we get the room info for each + // result, which can be slow if we have a lot of results. The original order is kept by using `awaitAll()`. + val mappedResults = results.map { result -> + async(coroutineDispatchers.computation) { + val roomInfo = matrixClient.getRoomInfoFlow(result.roomId).first().getOrElse { return@async null } + val formattedTimestamp = dateFormatter.format( + timestamp = result.timestamp, + mode = DateFormatterMode.TimeOrDate, + useRelative = true + ) + + if (!result.content.isMediaContent()) { + mapMessageContent(result, roomInfo, formattedTimestamp) + } else { + mapMediaContent(result, roomInfo, formattedTimestamp) + } + } + } + .awaitAll() + .mapNotNull { it } + + searchResults = when { + queryState.text.isEmpty() -> AsyncData.Uninitialized + mappedResults.isNotEmpty() -> { + AsyncData.Success(GlobalSearchResults.MessageSearchResults(results = mappedResults.toImmutableList())) + } + paginationState is MessageSearchPaginationState.Idle && paginationState.endReached -> { + AsyncData.Success(GlobalSearchResults.MessageSearchResults(results = persistentListOf())) + } + paginationState is MessageSearchPaginationState.Loading -> { + AsyncData.Loading(prevData = searchResults.dataOrNull()) + } + else -> { + AsyncData.Uninitialized + } + } + } + } + } + } + + fun handleEvent(event: GlobalSearchEvent) { + when (event) { + GlobalSearchEvent.ClearQuery -> { + queryState.clearText() + } + GlobalSearchEvent.ToggleSearchVisibility -> { + isSearchActive = !isSearchActive + queryState.clearText() + } + is GlobalSearchEvent.UpdateVisibleRange -> { + when (currentTarget) { + GlobalSearchTarget.ROOMS -> coroutineScope.launch { + // TODO Maybe this is not needed? We're not displaying the latest event or timestamp info so maybe we dont need to subscribe + // to the room info for each room in the search results. + roomListSearchDataSource.updateVisibleRange(event.range) + } + GlobalSearchTarget.MESSAGES -> coroutineScope.launch { + val currentCount = (searchResults.dataOrNull() as? GlobalSearchResults.MessageSearchResults)?.results?.size ?: 0 + val currentPaginationState = currentMessageSearch.paginationState.value + val canPaginate = currentPaginationState is MessageSearchPaginationState.Idle && !currentPaginationState.endReached + if (event.range.last >= currentCount - 10 && canPaginate) { + currentMessageSearch.paginate() + } + } + } + } + is GlobalSearchEvent.UpdateTarget -> currentTarget = event.target + } + } + + return GlobalSearchState( + isEnabled = isEnabled, + isSearchActive = isSearchActive, + queryState = queryState, + currentTarget = currentTarget, + results = searchResults, + eventSink = ::handleEvent, + ) + } + + private fun mapMessageContent( + result: MessageSearchResult, + roomInfo: RoomInfo, + formattedTimestamp: String, + ): MessageSearchResultItem.Message? { + val body = latestEventFormatter.format( + latestEvent = LatestEventValue.Remote( + timestamp = result.timestamp, + content = result.content, + senderId = result.senderId, + senderProfile = result.senderProfile, + isOwn = matrixClient.isMe(result.senderId), + ), + isDmRoom = false, + ) + return MessageSearchResultItem.Message( + messageSearchResult = result, + body = body?.toString() ?: "", + formattedTimestamp = formattedTimestamp, + roomInfo = roomInfo, + ) + } + + private fun mapMediaContent( + result: MessageSearchResult, + roomInfo: RoomInfo, + formattedTimestamp: String, + ): MessageSearchResultItem.Media? { + val messageType = when (val content = result.content) { + is MessageContent if content.type is MessageTypeWithAttachment -> content.type as MessageTypeWithAttachment + else -> return null + } + + val caption = messageType.toPlainText(permalinkParser, default = messageType.caption ?: messageType.filename) + + val thumbnailType = when (messageType) { + is ImageMessageType -> AttachmentThumbnailType.Image + is VideoMessageType -> AttachmentThumbnailType.Video + is AudioMessageType -> AttachmentThumbnailType.Audio + is VoiceMessageType -> AttachmentThumbnailType.Voice + is FileMessageType -> AttachmentThumbnailType.File + is StickerMessageType -> AttachmentThumbnailType.Image + } + val thumbnailSource = when (messageType) { + is ImageMessageType -> messageType.info?.thumbnailSource ?: messageType.source + is VideoMessageType -> messageType.info?.thumbnailSource + is AudioMessageType -> null + is VoiceMessageType -> null + is FileMessageType -> null + is StickerMessageType -> messageType.info?.thumbnailSource ?: messageType.source + } + val blurhash = when (messageType) { + is ImageMessageType -> messageType.info?.blurhash + is VideoMessageType -> messageType.info?.blurhash + is AudioMessageType -> null + is VoiceMessageType -> null + is FileMessageType -> null + is StickerMessageType -> messageType.info?.blurhash + } + + val extension = messageType.filename.split(".").takeIf { it.size > 1 }?.lastOrNull()?.uppercase() + val formattedSize = when (messageType) { + is ImageMessageType -> messageType.info?.size + is VideoMessageType -> messageType.info?.size + is AudioMessageType -> messageType.info?.size + is VoiceMessageType -> messageType.info?.size + is FileMessageType -> messageType.info?.size + is StickerMessageType -> messageType.info?.size + } + ?.let(fileSizeFormatter::format) + + val mediaContent = MediaSearchResultContent( + filename = messageType.filename, + extension = extension, + caption = caption, + formattedSize = formattedSize, + thumbnailSource = thumbnailSource, + thumbnailType = thumbnailType, + blurhash = blurhash + ) + + return MessageSearchResultItem.Media( + messageSearchResult = result, + mediaContent = mediaContent, + formattedTimestamp = formattedTimestamp, + roomInfo = roomInfo, + ) + } +} diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchState.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchState.kt new file mode 100644 index 0000000000..d623fd5594 --- /dev/null +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchState.kt @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.home.impl.search + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.Immutable +import io.element.android.features.home.impl.model.RoomListRoomSummary +import io.element.android.libraries.architecture.AsyncData +import io.element.android.libraries.matrix.api.core.EventId +import io.element.android.libraries.matrix.api.core.RoomId +import io.element.android.libraries.matrix.api.core.UserId +import io.element.android.libraries.matrix.api.media.MediaSource +import io.element.android.libraries.matrix.api.room.RoomInfo +import io.element.android.libraries.matrix.api.search.MessageSearchResult +import io.element.android.libraries.matrix.api.timeline.item.event.getDisambiguatedDisplayName +import io.element.android.libraries.matrix.ui.components.AttachmentThumbnailType +import kotlinx.collections.immutable.ImmutableList + +@Immutable +data class GlobalSearchState( + val isEnabled: Boolean, + val isSearchActive: Boolean, + val queryState: TextFieldState, + val currentTarget: GlobalSearchTarget, + val results: AsyncData, + val eventSink: (GlobalSearchEvent) -> Unit +) + +@Immutable +enum class GlobalSearchTarget { + ROOMS, + MESSAGES, +} + +@Immutable +sealed interface GlobalSearchResults { + data class RoomListResults(val results: ImmutableList) : GlobalSearchResults + data class MessageSearchResults(val results: ImmutableList) : GlobalSearchResults + + fun isEmpty(): Boolean = when (this) { + is RoomListResults -> results.isEmpty() + is MessageSearchResults -> results.isEmpty() + } +} + +sealed interface MessageSearchResultItem { + val roomId: RoomId + val eventId: EventId + val senderId: UserId + val senderName: String + val roomInfo: RoomInfo + val formattedTimestamp: String + + data class Message( + val messageSearchResult: MessageSearchResult, + val body: String, + override val roomInfo: RoomInfo, + override val formattedTimestamp: String, + ) : MessageSearchResultItem { + override val roomId: RoomId = messageSearchResult.roomId + override val eventId: EventId = messageSearchResult.eventId + override val senderId: UserId = messageSearchResult.senderId + override val senderName: String = messageSearchResult.senderProfile.getDisambiguatedDisplayName(senderId) + } + + data class Media( + val messageSearchResult: MessageSearchResult, + val mediaContent: MediaSearchResultContent, + override val roomInfo: RoomInfo, + override val formattedTimestamp: String, + ) : MessageSearchResultItem { + override val roomId: RoomId = messageSearchResult.roomId + override val eventId: EventId = messageSearchResult.eventId + override val senderId: UserId = messageSearchResult.senderId + override val senderName: String = messageSearchResult.senderProfile.getDisambiguatedDisplayName(senderId) + } +} + +data class MediaSearchResultContent( + val filename: String, + val extension: String?, + val caption: String?, + val formattedSize: String?, + val thumbnailSource: MediaSource?, + val thumbnailType: AttachmentThumbnailType, + val blurhash: String?, +) diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchStatePreviewParam.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchStatePreviewParam.kt new file mode 100644 index 0000000000..73487c5069 --- /dev/null +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchStatePreviewParam.kt @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.home.impl.search + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.ui.tooling.preview.PreviewParameterProvider +import io.element.android.features.home.impl.roomlist.aRoomListRoomSummaryList +import io.element.android.libraries.architecture.AsyncData +import io.element.android.libraries.matrix.api.core.EventId +import io.element.android.libraries.matrix.api.core.RoomAlias +import io.element.android.libraries.matrix.api.core.RoomId +import io.element.android.libraries.matrix.api.core.UserId +import io.element.android.libraries.matrix.api.media.MediaSource +import io.element.android.libraries.matrix.api.room.CallIntentConsensus +import io.element.android.libraries.matrix.api.room.CurrentUserMembership +import io.element.android.libraries.matrix.api.room.RoomInfo +import io.element.android.libraries.matrix.api.room.RoomMember +import io.element.android.libraries.matrix.api.room.RoomNotificationMode +import io.element.android.libraries.matrix.api.room.history.RoomHistoryVisibility +import io.element.android.libraries.matrix.api.room.join.JoinRule +import io.element.android.libraries.matrix.api.room.powerlevels.RoomPowerLevels +import io.element.android.libraries.matrix.api.room.powerlevels.RoomPowerLevelsValues +import io.element.android.libraries.matrix.api.room.tombstone.SuccessorRoom +import io.element.android.libraries.matrix.api.search.MessageSearchResult +import io.element.android.libraries.matrix.api.timeline.item.EventThreadInfo +import io.element.android.libraries.matrix.api.timeline.item.event.InReplyTo +import io.element.android.libraries.matrix.api.timeline.item.event.MessageContent +import io.element.android.libraries.matrix.api.timeline.item.event.MessageType +import io.element.android.libraries.matrix.api.timeline.item.event.ProfileDetails +import io.element.android.libraries.matrix.api.timeline.item.event.TextMessageType +import io.element.android.libraries.matrix.api.user.MatrixUser +import io.element.android.libraries.matrix.ui.components.AttachmentThumbnailType +import io.element.android.libraries.matrix.ui.messages.reply.aProfileDetailsReady +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentMapOf +import kotlinx.collections.immutable.toImmutableList +import kotlinx.collections.immutable.toPersistentList + +class GlobalSearchStatePreviewParam : PreviewParameterProvider { + override val values: Sequence + get() = sequenceOf( + // Not enabled, no preview + aGlobalSearchState(isEnabled = false), + aGlobalSearchState(isSearchActive = true, queryState = TextFieldState("Query")), + aGlobalSearchState( + isSearchActive = true, + currentTarget = GlobalSearchTarget.ROOMS, + queryState = TextFieldState("Query"), + results = AsyncData.Loading(), + ), + aGlobalSearchState( + isSearchActive = true, + currentTarget = GlobalSearchTarget.ROOMS, + queryState = TextFieldState("Query"), + results = AsyncData.Success( + GlobalSearchResults.RoomListResults( + results = aRoomListRoomSummaryList().mapIndexed { index, summary -> + summary.copy(name = "Room with Query #${index + 1}") + }.toPersistentList() + ) + ), + ), + aGlobalSearchState( + isSearchActive = true, + currentTarget = GlobalSearchTarget.MESSAGES, + queryState = TextFieldState("Query"), + results = AsyncData.Success(GlobalSearchResults.MessageSearchResults(persistentListOf( + MessageSearchResultItem.Message( + messageSearchResult = aMessageSearchResult(eventId = EventId("\$eventId1:server.org")), + body = "A message with Query", + roomInfo = aRoomInfo(), + formattedTimestamp = "12:00", + ), + MessageSearchResultItem.Media( + messageSearchResult = aMessageSearchResult(eventId = EventId("\$eventId2:server.org")), + mediaContent = MediaSearchResultContent( + filename = "file.png", + extension = "PNG", + caption = "A caption containing Query", + formattedSize = "1 MB", + thumbnailSource = MediaSource("https://example.com/thumbnail.png"), + thumbnailType = AttachmentThumbnailType.Image, + blurhash = null, + ), + roomInfo = aRoomInfo(), + formattedTimestamp = "12:00", + ), + ))), + ), + aGlobalSearchState( + isSearchActive = true, + currentTarget = GlobalSearchTarget.MESSAGES, + queryState = TextFieldState("Query"), + results = AsyncData.Success(GlobalSearchResults.MessageSearchResults(persistentListOf())), + ), + ) +} + +fun aRoomInfo( + id: RoomId = RoomId("!roomId:server.org"), + name: String? = "A room", + rawName: String? = "A room raw name", + topic: String? = "A room topic", + avatarUrl: String? = "https://example.com/avatar.png", + isPublic: Boolean = true, + isDirect: Boolean = false, + isEncrypted: Boolean = false, + joinRule: JoinRule? = JoinRule.Public, + isSpace: Boolean = false, + successorRoom: SuccessorRoom? = null, + isFavorite: Boolean = false, + canonicalAlias: RoomAlias? = null, + alternativeAliases: List = emptyList(), + currentUserMembership: CurrentUserMembership = CurrentUserMembership.JOINED, + inviter: RoomMember? = null, + activeMembersCount: Long = 2, + invitedMembersCount: Long = 1, + joinedMembersCount: Long = 1, + highlightCount: Long = 0, + notificationCount: Long = 0, + userDefinedNotificationMode: RoomNotificationMode? = null, + hasRoomCall: Boolean = false, + roomPowerLevels: RoomPowerLevels? = RoomPowerLevels( + values = RoomPowerLevelsValues( + ban = 0, + invite = 0, + kick = 0, + eventsDefault = 0, + stateDefault = 0, + redactEvents = 0, + roomName = 0, + roomAvatar = 0, + roomTopic = 0, + spaceChild = 0, + beacon = 0, + beaconInfo = 0 + ), + users = persistentMapOf(), + ), + activeRoomCallParticipants: List = emptyList(), + heroes: List = emptyList(), + pinnedEventIds: List = emptyList(), + roomCreators: List = emptyList(), + isMarkedUnread: Boolean = false, + numUnreadMessages: Long = 0, + numUnreadNotifications: Long = 0, + numUnreadMentions: Long = 0, + historyVisibility: RoomHistoryVisibility = RoomHistoryVisibility.Joined, + roomVersion: String? = "11", + privilegedCreatorRole: Boolean = false, + isLowPriority: Boolean = false, + activeCallIntentConsensus: CallIntentConsensus = CallIntentConsensus.None, + isDm: Boolean = false, + fullyReadEventId: EventId? = null, +) = RoomInfo( + id = id, + name = name, + rawName = rawName, + topic = topic, + avatarUrl = avatarUrl, + isPublic = isPublic, + isDirect = isDirect, + isEncrypted = isEncrypted, + joinRule = joinRule, + isSpace = isSpace, + successorRoom = successorRoom, + isFavorite = isFavorite, + canonicalAlias = canonicalAlias, + alternativeAliases = alternativeAliases.toImmutableList(), + currentUserMembership = currentUserMembership, + inviter = inviter, + activeMembersCount = activeMembersCount, + invitedMembersCount = invitedMembersCount, + joinedMembersCount = joinedMembersCount, + highlightCount = highlightCount, + notificationCount = notificationCount, + userDefinedNotificationMode = userDefinedNotificationMode, + hasRoomCall = hasRoomCall, + roomPowerLevels = roomPowerLevels, + activeRoomCallParticipants = activeRoomCallParticipants.toImmutableList(), + heroes = heroes.toImmutableList(), + pinnedEventIds = pinnedEventIds.toImmutableList(), + creators = roomCreators.toImmutableList(), + isMarkedUnread = isMarkedUnread, + numUnreadMessages = numUnreadMessages, + numUnreadNotifications = numUnreadNotifications, + numUnreadMentions = numUnreadMentions, + historyVisibility = historyVisibility, + roomVersion = roomVersion, + privilegedCreatorRole = privilegedCreatorRole, + isLowPriority = isLowPriority, + activeCallIntentConsensus = activeCallIntentConsensus, + isDm = isDm, + fullyReadEventId = fullyReadEventId, +) + +fun aMessageContent( + body: String = "body", + inReplyTo: InReplyTo? = null, + isEdited: Boolean = false, + threadInfo: EventThreadInfo? = null, + messageType: MessageType = TextMessageType( + body = body, + formatted = null + ) +) = MessageContent( + body = body, + inReplyTo = inReplyTo, + isEdited = isEdited, + threadInfo = threadInfo, + type = messageType +) + +internal fun aMessageSearchResult( + roomId: RoomId = RoomId("!roomId:server.org"), + eventId: EventId = EventId("\$eventId:server.org"), + senderId: UserId = UserId("@user:server.org"), + senderProfile: ProfileDetails = aProfileDetailsReady(), + content: MessageContent = aMessageContent(), + timestamp: Long = 0L, +) = MessageSearchResult( + roomId = roomId, + eventId = eventId, + senderId = senderId, + senderProfile = senderProfile, + content = content, + timestamp = timestamp, +) + +internal fun aGlobalSearchState( + isEnabled: Boolean = true, + isSearchActive: Boolean = false, + queryState: TextFieldState = TextFieldState(), + currentTarget: GlobalSearchTarget = GlobalSearchTarget.ROOMS, + results: AsyncData = AsyncData.Uninitialized, + eventSink: (GlobalSearchEvent) -> Unit = {}, +) = GlobalSearchState( + isEnabled = isEnabled, + isSearchActive = isSearchActive, + queryState = queryState, + currentTarget = currentTarget, + results = results, + eventSink = eventSink +) diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchView.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchView.kt new file mode 100644 index 0000000000..d5a0460f06 --- /dev/null +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/GlobalSearchView.kt @@ -0,0 +1,564 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.home.impl.search + +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.PreviewParameter +import androidx.compose.ui.unit.dp +import io.element.android.compound.theme.ElementTheme +import io.element.android.compound.tokens.generated.CompoundIcons +import io.element.android.features.home.impl.R +import io.element.android.features.home.impl.model.RoomListRoomSummary +import io.element.android.libraries.designsystem.atomic.molecules.IconTitleSubtitleMolecule +import io.element.android.libraries.designsystem.components.BigIcon +import io.element.android.libraries.designsystem.components.avatar.Avatar +import io.element.android.libraries.designsystem.components.avatar.AvatarData +import io.element.android.libraries.designsystem.components.avatar.AvatarSize +import io.element.android.libraries.designsystem.components.avatar.AvatarType +import io.element.android.libraries.designsystem.components.button.BackButton +import io.element.android.libraries.designsystem.modifiers.niceClickable +import io.element.android.libraries.designsystem.preview.ElementPreview +import io.element.android.libraries.designsystem.preview.PreviewsDayNight +import io.element.android.libraries.designsystem.text.roundToPx +import io.element.android.libraries.designsystem.theme.components.FilledTextField +import io.element.android.libraries.designsystem.theme.components.Icon +import io.element.android.libraries.designsystem.theme.components.IconButton +import io.element.android.libraries.designsystem.theme.components.LinearProgressIndicator +import io.element.android.libraries.designsystem.theme.components.Scaffold +import io.element.android.libraries.designsystem.theme.components.SegmentedButton +import io.element.android.libraries.designsystem.theme.components.Text +import io.element.android.libraries.designsystem.theme.components.TopAppBar +import io.element.android.libraries.designsystem.utils.OnVisibleRangeChangeEffect +import io.element.android.libraries.designsystem.utils.lazyColumnContentPadding +import io.element.android.libraries.designsystem.utils.scaffoldScrollableContentInsets +import io.element.android.libraries.matrix.api.core.EventId +import io.element.android.libraries.matrix.api.core.RoomId +import io.element.android.libraries.matrix.ui.components.AttachmentThumbnail +import io.element.android.libraries.matrix.ui.components.AttachmentThumbnailInfo +import io.element.android.libraries.matrix.ui.model.getAvatarData +import io.element.android.libraries.ui.strings.CommonStrings +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.toImmutableList + +@Composable +fun GlobalSearchView( + state: GlobalSearchState, + onSelectSearchResult: (RoomId, EventId?) -> Unit, + modifier: Modifier = Modifier, +) { + BackHandler(enabled = state.isSearchActive) { + state.eventSink(GlobalSearchEvent.ToggleSearchVisibility) + } + + AnimatedVisibility( + visible = state.isSearchActive, + enter = fadeIn(), + exit = fadeOut(), + ) { + Column(modifier = modifier) { + GlobalSearchContent( + state = state, + onBackButtonClick = { + state.eventSink(GlobalSearchEvent.ToggleSearchVisibility) + }, + onSelectSearchResult = onSelectSearchResult, + ) + } + } +} + +@Composable +private fun GlobalSearchContent( + state: GlobalSearchState, + onBackButtonClick: () -> Unit, + onSelectSearchResult: (RoomId, EventId?) -> Unit, +) { + val borderColor = MaterialTheme.colorScheme.tertiary + val strokeWidth = 1.dp + + val drawBottomLineModifier = Modifier.drawBehind { + drawLine( + color = borderColor, + start = Offset(0f, size.height), + end = Offset(size.width, size.height), + strokeWidth = strokeWidth.value + ) + } + + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { BackButton(onClick = onBackButtonClick) }, + title = { + // The stateSaver will keep the selection state when returning to this UI + val focusRequester = remember { FocusRequester() } + val searchLabel = stringResource(CommonStrings.action_search) + FilledTextField( + modifier = Modifier + .fillMaxWidth() + .focusRequester(focusRequester) + .semantics { contentDescription = searchLabel }, + state = state.queryState, + lineLimits = TextFieldLineLimits.SingleLine, + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + disabledContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + disabledIndicatorColor = Color.Transparent, + errorIndicatorColor = Color.Transparent, + ), + trailingIcon = if (state.queryState.text.isNotEmpty()) { + @Composable { + IconButton(onClick = { state.eventSink(GlobalSearchEvent.ClearQuery) }) { + Icon( + imageVector = CompoundIcons.Close(), + contentDescription = stringResource(CommonStrings.a11y_clear_search_field) + ) + } + } + } else { + null + }, + ) + + LaunchedEffect(Unit) { + if (!focusRequester.restoreFocusedChild()) { + focusRequester.requestFocus() + } + focusRequester.saveFocusedChild() + } + } + ) + }, + contentWindowInsets = scaffoldScrollableContentInsets, + ) { padding -> + Column( + modifier = Modifier.padding(padding), + ) { + SingleChoiceSegmentedButtonRow( + modifier = drawBottomLineModifier + .fillMaxWidth() + .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 8.dp) + ) { + SegmentedButton( + index = 0, + count = 2, + selected = state.currentTarget == GlobalSearchTarget.ROOMS, + onClick = { state.eventSink(GlobalSearchEvent.UpdateTarget(GlobalSearchTarget.ROOMS)) }, + text = stringResource(R.string.search_section_chats), + ) + + SegmentedButton( + index = 1, + count = 2, + selected = state.currentTarget == GlobalSearchTarget.MESSAGES, + onClick = { state.eventSink(GlobalSearchEvent.UpdateTarget(GlobalSearchTarget.MESSAGES)) }, + text = stringResource(R.string.search_section_messages), + ) + } + + val lazyListState = rememberLazyListState() + OnVisibleRangeChangeEffect(lazyListState) { visibleRange -> + state.eventSink(GlobalSearchEvent.UpdateVisibleRange(visibleRange)) + } + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = lazyColumnContentPadding, + state = lazyListState, + ) { + val results = state.results.dataOrNull() + when { + state.results.isUninitialized() -> startSearching() + state.results.isLoading() -> loading() + results?.isEmpty() == true -> emptySearchResults(query = state.queryState.text.toString()) + results is GlobalSearchResults.RoomListResults -> roomListResults( + results = results.results, + onRoomClick = { roomId -> onSelectSearchResult(roomId, null) }, + ) + results is GlobalSearchResults.MessageSearchResults -> messageSearchResults( + results = results.results, + onSearchResultSelected = onSelectSearchResult, + ) + } + } + } + } +} + +private fun LazyListScope.startSearching() { + item { + IconTitleSubtitleMolecule( + modifier = Modifier + .fillMaxWidth() + .padding(40.dp), + title = stringResource(R.string.start_searching_title), + subTitle = stringResource(R.string.start_searching_subtitle), + iconStyle = BigIcon.Style.Default(CompoundIcons.Search()), + ) + } +} + +private fun LazyListScope.loading() { + item { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + } +} + +private fun LazyListScope.emptySearchResults(query: String) { + item { + IconTitleSubtitleMolecule( + modifier = Modifier + .fillMaxWidth() + .padding(40.dp), + title = stringResource(R.string.search_no_results_title), + subTitle = stringResource(R.string.search_no_results_subtitle, query), + iconStyle = BigIcon.Style.Default(CompoundIcons.Search()), + ) + } +} + +private fun LazyListScope.roomListResults( + results: ImmutableList, + onRoomClick: (RoomId) -> Unit, +) { + itemsIndexed( + items = results, + key = { _, roomSummary -> roomSummary.roomId }, + ) { index, result -> + Row( + modifier = Modifier + .niceClickable(onClick = { onRoomClick(result.roomId) }) + .fillMaxWidth() + .addSeparatorLine(color = ElementTheme.colors.separatorSecondary, isLastItem = index == results.lastIndex) + .padding(horizontal = 16.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Avatar( + avatarData = result.avatarData.copy(size = AvatarSize.SearchRoomListItem), + avatarType = AvatarType.Room( + heroes = result.heroes.map { it.copy(size = AvatarSize.SearchRoomListItem) }.toImmutableList(), + isTombstoned = result.isTombstoned, + ), + ) + + Column( + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + text = result.name ?: result.roomId.value, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodyLgRegular, + ) + + if (result.isDm) { + val userId = result.heroes.firstOrNull()?.id + userId?.let { + Text( + text = it, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodyMdRegular, + color = ElementTheme.colors.textSecondary, + ) + } + } else { + result.canonicalAlias?.let { + Text( + text = it.value, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodyMdRegular, + color = ElementTheme.colors.textSecondary, + ) + } + } + } + } + } +} + +private fun LazyListScope.messageSearchResults( + results: ImmutableList, + onSearchResultSelected: (RoomId, EventId?) -> Unit, +) { + if (results.isNotEmpty()) { + item { + Text( + modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp), + text = stringResource(R.string.search_from_your_messages_header), + style = ElementTheme.typography.fontBodyMdMedium, + color = ElementTheme.colors.textSecondary, + ) + } + } + itemsIndexed( + items = results, + contentType = { _, messageSearchResult -> messageSearchResult::class.java }, + key = { _, messageSearchResult -> messageSearchResult.eventId }, + ) { index, result -> + val clickableModifier = Modifier.niceClickable(onClick = { onSearchResultSelected(result.roomId, result.eventId) }) + when (result) { + is MessageSearchResultItem.Message -> TextMessageSearchResultItemView( + modifier = clickableModifier.addSeparatorLine(color = ElementTheme.colors.separatorSecondary, isLastItem = index == results.lastIndex), + avatarData = result.roomInfo.getAvatarData(AvatarSize.RoomListItem), + avatarType = AvatarType.Room( + heroes = result.roomInfo.heroes.map { it.getAvatarData(AvatarSize.RoomListItem) }.toImmutableList(), + isTombstoned = result.roomInfo.successorRoom != null + ), + roomName = result.roomInfo.name ?: result.roomInfo.id.value, + body = result.body, + formattedTimestamp = result.formattedTimestamp, + ) + is MessageSearchResultItem.Media -> { + MediaMessageSearchResultItemView( + modifier = clickableModifier.addSeparatorLine(color = ElementTheme.colors.separatorSecondary, isLastItem = index == results.lastIndex), + avatarData = result.roomInfo.getAvatarData(AvatarSize.RoomListItem), + avatarType = AvatarType.Room( + heroes = result.roomInfo.heroes.map { it.getAvatarData(AvatarSize.RoomListItem) }.toImmutableList(), + isTombstoned = result.roomInfo.successorRoom != null + ), + roomName = result.roomInfo.name ?: result.roomInfo.id.value, + content = result.mediaContent, + formattedTimestamp = result.formattedTimestamp, + ) + } + } + } +} + +@Composable +private fun TextMessageSearchResultItemView( + avatarData: AvatarData, + avatarType: AvatarType, + roomName: String, + body: String, + formattedTimestamp: String, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Avatar( + avatarData = avatarData, + avatarType = avatarType, + ) + + Spacer(modifier = Modifier.width(16.dp)) + + Column( + modifier = Modifier + .fillMaxWidth() + .padding(top = 12.dp, bottom = 10.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Text( + modifier = Modifier.weight(1f), + text = roomName, + maxLines = 1, + style = ElementTheme.typography.fontBodyLgMedium, + ) + Text( + text = formattedTimestamp, + maxLines = 1, + style = ElementTheme.typography.fontBodySmRegular, + color = ElementTheme.colors.textSecondary, + ) + } + Text( + text = body, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodyMdRegular, + color = ElementTheme.colors.textSecondary, + ) + } + } +} + +@Composable +private fun MediaMessageSearchResultItemView( + avatarData: AvatarData, + avatarType: AvatarType, + roomName: String, + content: MediaSearchResultContent, + formattedTimestamp: String, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Avatar( + avatarData = avatarData, + avatarType = avatarType, + ) + + Spacer(modifier = Modifier.width(16.dp)) + + Column( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Text( + modifier = Modifier.weight(1f), + text = roomName, + maxLines = 1, + style = ElementTheme.typography.fontBodyLgMedium, + ) + Text( + text = formattedTimestamp, + maxLines = 1, + style = ElementTheme.typography.fontBodySmRegular, + color = ElementTheme.colors.textSecondary, + ) + } + + content.caption?.let { + Text( + text = it, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodyMdRegular, + color = ElementTheme.colors.textSecondary, + ) + } + Row( + modifier = Modifier + .fillMaxWidth(1f) + .background(ElementTheme.colors.bgSubtleSecondary, shape = RoundedCornerShape(12.dp)) + .padding(horizontal = 12.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + AttachmentThumbnail( + modifier = Modifier + .size(36.dp) + .clip(RoundedCornerShape(4.dp)), + info = AttachmentThumbnailInfo( + type = content.thumbnailType, + thumbnailSource = content.thumbnailSource, + textContent = null, + blurHash = content.blurhash, + ), + thumbnailSize = 36.dp.roundToPx().toLong(), + backgroundColor = ElementTheme.colors.bgCanvasDefault, + ) + + Column { + Text( + text = content.filename, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodyLgRegular, + ) + + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + content.extension?.let { + Text( + text = it, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodySmRegular, + color = ElementTheme.colors.textSecondary, + ) + } + content.formattedSize?.let { + Text( + text = "($it)", + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = ElementTheme.typography.fontBodySmRegular, + color = ElementTheme.colors.textSecondary, + ) + } + } + } + } + } + } +} + +private fun Modifier.addSeparatorLine(color: Color, isLastItem: Boolean): Modifier { + if (isLastItem) return this + + return this.drawBehind { + val strokeWidthPx = 1.dp.toPx() + drawLine( + color = color, + start = Offset(0f, size.height - strokeWidthPx), + end = Offset(size.width, size.height - strokeWidthPx), + strokeWidth = strokeWidthPx, + ) + } +} + +@PreviewsDayNight +@Composable +internal fun GlobalSearchViewPreview( + @PreviewParameter(GlobalSearchStatePreviewParam::class) state: GlobalSearchState, +) { + ElementPreview { + GlobalSearchView( + state = state, + onSelectSearchResult = { _, _ -> }, + ) + } +} diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchDataSource.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchDataSource.kt index 03fcb5520f..df7ed0dd37 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchDataSource.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchDataSource.kt @@ -46,6 +46,8 @@ class RoomListSearchDataSource( coroutineScope = coroutineScope ) + val loadingState = roomList.loadingState + val roomSummaries: Flow> = roomList.summaries .map { roomSummaries -> roomSummaries diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchStateProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchStatePreviewParam.kt similarity index 93% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchStateProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchStatePreviewParam.kt index e6ec92f68b..2b857354a3 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchStateProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.features.home.impl.roomlist.aRoomListRoomSummaryList import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -class RoomListSearchStateProvider : PreviewParameterProvider { +class RoomListSearchStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomListSearchState(), diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchView.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchView.kt index 0535ded5c5..ff354cf717 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchView.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/search/RoomListSearchView.kt @@ -196,7 +196,7 @@ private fun RoomListSearchContent( @PreviewsDayNight @Composable -internal fun RoomListSearchContentPreview(@PreviewParameter(RoomListSearchStateProvider::class) state: RoomListSearchState) = ElementPreview { +internal fun RoomListSearchContentPreview(@PreviewParameter(RoomListSearchStatePreviewParam::class) state: RoomListSearchState) = ElementPreview { RoomListSearchContent( state = state, hideInvitesAvatars = false, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersStateProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersStatePreviewParam.kt similarity index 97% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersStateProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersStatePreviewParam.kt index 264d122836..335b801908 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersStateProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.matrix.api.spaces.SpaceServiceFilter import io.element.android.libraries.previewutils.room.aSpaceRoom import kotlinx.collections.immutable.toImmutableList -class SpaceFiltersStateProvider : PreviewParameterProvider { +class SpaceFiltersStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSelectingSpaceFiltersState(), diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersView.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersView.kt index 280f41b909..e4573f344e 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersView.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spacefilters/SpaceFiltersView.kt @@ -189,6 +189,6 @@ private fun SpaceFilterItem( @PreviewsDayNight @Composable -internal fun SpaceFiltersViewPreview(@PreviewParameter(SpaceFiltersStateProvider::class) state: SpaceFiltersState) = ElementPreview(fillMaxSize = true) { +internal fun SpaceFiltersViewPreview(@PreviewParameter(SpaceFiltersStatePreviewParam::class) state: SpaceFiltersState) = ElementPreview(fillMaxSize = true) { SpaceFiltersView(state = state) } diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesStateProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesStatePreviewParam.kt similarity index 93% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesStateProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesStatePreviewParam.kt index 17f2cbad31..57b219d302 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesStateProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesStatePreviewParam.kt @@ -15,11 +15,11 @@ import io.element.android.libraries.previewutils.room.aSpaceRoom import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableSet -open class HomeSpacesStateProvider : PreviewParameterProvider { +open class HomeSpacesStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aHomeSpacesState( - spaceRooms = SpaceRoomProvider().values.toList(), + spaceRooms = SpaceRoomPreviewParam().values.toList(), seenSpaceInvites = setOf( RoomId("!spaceId3:example.com"), ), diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesView.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesView.kt index 9125912bf0..914d08d7f6 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesView.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/HomeSpacesView.kt @@ -171,7 +171,7 @@ private fun EmptySpaceHomeView( @PreviewsDayNight @Composable internal fun HomeSpacesViewPreview( - @PreviewParameter(HomeSpacesStateProvider::class) state: HomeSpacesState, + @PreviewParameter(HomeSpacesStatePreviewParam::class) state: HomeSpacesState, ) = ElementPreview { HomeSpacesView( state = state, diff --git a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/SpaceRoomProvider.kt b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/SpaceRoomPreviewParam.kt similarity index 95% rename from features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/SpaceRoomProvider.kt rename to features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/SpaceRoomPreviewParam.kt index 4a77e45372..25744157aa 100644 --- a/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/SpaceRoomProvider.kt +++ b/features/home/impl/src/main/kotlin/io/element/android/features/home/impl/spaces/SpaceRoomPreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.matrix.api.room.CurrentUserMembership import io.element.android.libraries.matrix.api.spaces.SpaceRoom import io.element.android.libraries.previewutils.room.aSpaceRoom -class SpaceRoomProvider : PreviewParameterProvider { +class SpaceRoomPreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( aSpaceRoom(), aSpaceRoom( diff --git a/features/home/impl/src/main/res/values-ar/translations.xml b/features/home/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..59f4d6c821 --- /dev/null +++ b/features/home/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,56 @@ + + + "عطّل تحسين البطارية لهذا التطبيق للتأكد من استلام جميع الإشعارات." + "تعطيل التحسين" + "هل لا تصلك الإشعارات؟" + "تم تحديث صوت إشعاراتك، ليصبح أوضح وأسرع وأقل إزعاجًا." + "حدّثنا الأصوات لديك" + "يتم نسخ دردشاتك احتياطيًا تلقائيًا بتشفير من طرف إلى طرف. لاستعادة هذه النسخة الاحتياطية والاحتفاظ بهويتك الرقمية إذا فقدت الوصول إلى جميع أجهزتك، ستحتاج إلى مفتاح الاسترداد." + "الحصول على مفتاح الاسترداد" + "احتفِظ بنسخة احتياطية من دردشاتك" + "أكّد مفتاح الاسترداد الخاص بك للحفاظ على الوصول إلى تخزين المفاتيح وسجل الرسائل." + "أدخل مفتاح الاسترداد" + "هل نسيت مفتاح الاسترداد؟" + "تخزين المفاتيح لديك غير متزامن" + "للتأكد من عدم تفويت أي مكالمة مهمة، يُرجى تغيير إعداداتك للسماح بإشعارات ملء الشاشة عندما يكون هاتفك مقفلاً." + "حسّن تجربة مكالماتك" + "المحادثات" + "المساحات" + "أمتأكد من رغبتك برفض دعوة للانضمام إلى %1$s؟" + "رفض الدعوة" + "أمتأكد من رغبتك برفض المحادثة الخاصة مع %1$s؟" + "رفض المحادثة" + "لا دعوات" + "دعاك %1$s (%2$s)" + "هذه العملية تُجرى لمرة واحدة، شكراً على انتظارك." + "إعداد حسابك" + "إنشاء محادثة جديد أو غرفة" + "مسح عوامل التصفية" + "ابدأ الآن بمراسلة من تشاء." + "لا محادثات بعد." + "المفضلة" + "يمكنك إضافة محادثة إلى المفضلة من إعدادات المحادثة. +يمكنك الآن إلغاء تحديد عوامل التصفية لرؤية محادثاتك الأخرى" + "ليست لديك أي محادثات مفضلة بعد" + "الدعوات" + "ليس لديك أي دعوات قيد الانتظار." + "منخفضة الأولوية" + "ليست لديك أي دردشات منخفضة الأولوية بعد" + "يمكنك إلغاء تحديد عوامل التصفية لرؤية محادثاتك الأخرى" + "ليست لديك محادثات لهذا الاختيار" + "الأشخاص" + "ليست لديك أي رسائل مباشرة بعد" + "الغرف" + "لست في أي غرفة بعد" + "غير المقروءة" + "تهانينا! +ليست لديك أي رسائل غير مقروءة!" + "تم إرسال طلب الانضمام" + "المحادثات" + "وضع علامة كمقروء" + "وضع علامة كغير مقروء" + "تمت ترقية هذه الغرفة" + "مساحاتك" + "يبدو أنك تستخدم جهازاً جديداً. تحقق باستخدام جهاز آخر ليصبح لك وصول إلى رسائلك المشفرة." + "أثبت هويتك" + diff --git a/features/home/impl/src/main/res/values-es/translations.xml b/features/home/impl/src/main/res/values-es/translations.xml index ed6cfdc990..e841d6ebf8 100644 --- a/features/home/impl/src/main/res/values-es/translations.xml +++ b/features/home/impl/src/main/res/values-es/translations.xml @@ -3,9 +3,11 @@ "Deshabilita la optimización de la batería en esta aplicación para asegurarte de que recibes notificaciones." "Deshabilitar la optimización" "¿No llegan las notificaciones?" - "Recupera tu identidad criptográfica y tu historial de mensajes con una clave de recuperación si has perdido todos tus dispositivos actuales." - "Configurar la recuperación" - "Configura la recuperación para proteger tu cuenta" + "Se ha actualizado tu sonido de notificación: más claro, rápido y menos disruptivo." + "Hemos actualizado tus sonidos" + "Tus chats se respaldan automáticamente con cifrado de extremo a extremo. Para restaurar esta copia de seguridad y conservar tu identidad digital si pierdes el acceso a todos tus dispositivos, necesitarás tu clave de recuperación." + "Obtener clave de recuperación" + "Copia de seguridad de tus chats" "Confirma tu clave de recuperación para mantener el acceso a tu almacén de claves y al historial de mensajes." "Introduce tu clave de recuperación" "¿Olvidaste tu clave de recuperación?" @@ -13,6 +15,7 @@ "Para asegurarte de que nunca te pierdas una llamada importante, modifica tus ajustes para permitir notificaciones a pantalla completa cuando el teléfono esté bloqueado." "Mejora tu experiencia de llamada" "Chats" + "Espacios" "¿Estás seguro de que quieres rechazar la invitación a unirte a %1$s?" "Rechazar la invitación" "¿Estás seguro de que quieres rechazar este chat privado con %1$s?" @@ -32,6 +35,7 @@ Por ahora, puedes deseleccionar los filtros para ver tus otros chats" "Invitaciones" "No tienes ninguna invitación pendiente." "Prioridad baja" + "Aún no tienes ningún chat de prioridad baja" "Puedes deseleccionar filtros para ver tus otros chats." "No tienes chats para esta selección" "Personas" @@ -46,6 +50,7 @@ Por ahora, puedes deseleccionar los filtros para ver tus otros chats" "Marcar como leído" "Marcar como no leído" "Esta sala ha sido renovada" + "Tus espacios" "Parece que estás usando un nuevo dispositivo. Verifica que eres tú para acceder a tus mensajes cifrados." "Verifica que eres tú" diff --git a/features/home/impl/src/main/res/values-fa/translations.xml b/features/home/impl/src/main/res/values-fa/translations.xml index b0c6a30bc4..64ce86ddc7 100644 --- a/features/home/impl/src/main/res/values-fa/translations.xml +++ b/features/home/impl/src/main/res/values-fa/translations.xml @@ -3,12 +3,16 @@ "از کار انداختن بهینه‌سازی باتری برای این کاره برای اطمینان از گرفتن همهٔ آگاهی‌ها." "از کار انداختن بهینه سازی" "آگاهی‌ها نمی‌رسند؟" - "بازگردانی تاریخچهٔ پیام‌ها و هویت رمزنگاشته‌تان با کلید بازیابی در صورت از دست دادن همهٔ افزاره‌های موجودتان." + "پینگ اعلان شما به‌روزرسانی شده است—واضح‌تر، سریع‌تر و کم‌دردسرتر." + "ما صداهای شما را تازه کرده‌ایم" + "چت‌های شما به طور خودکار با رمزگذاری سراسری پشتیبان‌گیری می‌شوند. برای بازیابی این پشتیبان‌گیری و حفظ هویت دیجیتال خود در زمانی که دسترسی به تمام دستگاه‌هایتان را از دست می‌دهید، به کلید بازیابی خود نیاز خواهید داشت." "دریافت کلید بازیابی" - "برپایی بازیابی" + "از چت‌هایتان پشتیبان بگیرید" "کلید بازیابی خود را تأیید کنید تا دسترسی به حافظه کلیدها و تاریخچه پیام‌هایتان حفظ شود ." "ورود کلید بازیابیتان" + "کلید بازیابی خود را فراموش کرده‌اید؟" "ذخیره‌ساز کلیدتان از هم‌گام بودن در آمده" + "برای اطمینان از اینکه هرگز تماس مهمی را از دست نمی‌دهید، لطفاً تنظیمات خود را تغییر دهید تا وقتی تلفنتان قفل است، اعلان‌ها به صورت تمام صفحه نمایش داده شوند." "بهبود تجریهٔ تماستان" "گپ‌ها" "فضاها" @@ -30,6 +34,7 @@ "دعوت‌ها" "هیچ دعوت منتظری ندارید." "اولویت کم" + "شما هنوز هیچ چت با اولویت پایین ندارید" "می توانید پالایه‌ها را برای دیدن دیگر گپ‌هایتان بردارید" "هیچ گپی برای این گزینش ندارید" "افراد" @@ -44,6 +49,7 @@ "علامت‌گذاری به عنوان خوانده شده" "نشان به ناخوانده" "این اتاق ارتقا یافته" + "فضاهای شما" "گویا از افزاره‌ای جدید استفاده می‌کنید. تأیید با افزاره‌ای دیگر برای دسترسی به پیام‌های رمزنگاری شده‌تان." "تأیید کنید که خودتانید" diff --git a/features/home/impl/src/main/res/values-pl/translations.xml b/features/home/impl/src/main/res/values-pl/translations.xml index 0c1b07f27b..f6e2e70519 100644 --- a/features/home/impl/src/main/res/values-pl/translations.xml +++ b/features/home/impl/src/main/res/values-pl/translations.xml @@ -5,7 +5,7 @@ "Powiadomienia nie dochodzą?" "Sygnał powiadomień został zaktualizowany — jest wyraźniejszy, szybszy i mniej uciążliwy." "Odświeżyliśmy Twoje dźwięki" - "Twoje czaty są automatycznie archiwizowane za pomocą szyfrowania end-to-end. Aby przywrócić tę kopię zapasową i swoją tożsamość cyfrową, wymagany będzie klucz przywracania." + "Twoje czaty są automatycznie archiwizowane za pomocą szyfrowania end-to-end. Aby przywrócić kopię zapasową i swoją tożsamość cyfrową, wymagany będzie klucz przywracania." "Uzyskaj klucz przywracania" "Utwórz kopię zapasową swoich czatów" "Potwierdź klucz przywracania, aby zachować dostęp do magazynu kluczy i historii wiadomości." diff --git a/features/home/impl/src/main/res/values-ro/translations.xml b/features/home/impl/src/main/res/values-ro/translations.xml index 14cf100c22..2446ebd495 100644 --- a/features/home/impl/src/main/res/values-ro/translations.xml +++ b/features/home/impl/src/main/res/values-ro/translations.xml @@ -5,7 +5,7 @@ "Nu primiți notificări?" "Sunetul pentru notificări a fost actualizat — mai clar, mai rapid și mai puțin perturbatoar." "Am reîmprospătat sunetele" - "Chaturile dumneavoastră sunt salvate automat cu criptare end-to-end. Pentru a restaura această copie de rezervă și a vă păstra identitatea digitală atunci când pierzdeți accesul la toate dispozitivele dumneavoastră, veți avea nevoie de cheia de recuperare." + "Chaturile dumneavoastră sunt salvate automat cu criptare end-to-end. Pentru a restaura aceast backup și a vă păstra identitatea digitală atunci când pierzdeți accesul la toate dispozitivele dumneavoastră, veți avea nevoie de cheia de recuperare." "Obțineți cheia de recuperare" "Faceți un backup al mesajelor" "Backup-ul pentru chat nu este sincronizat. Trebuie să confirmați cheia de recuperare pentru a menține accesul la backup." diff --git a/features/home/impl/src/main/res/values/temporary.xml b/features/home/impl/src/main/res/values/temporary.xml new file mode 100644 index 0000000000..c44001e5a6 --- /dev/null +++ b/features/home/impl/src/main/res/values/temporary.xml @@ -0,0 +1,17 @@ + + + + + Start searching… + Search for chats and messages + Chats + From your messages + Messages + No results + There are no results for “%1$s”. Try a new search term. + diff --git a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/DefaultHomeEntryPointTest.kt b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/DefaultHomeEntryPointTest.kt index 8eee8e1ee2..c0cb5f7c01 100644 --- a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/DefaultHomeEntryPointTest.kt +++ b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/DefaultHomeEntryPointTest.kt @@ -11,6 +11,8 @@ package io.element.android.features.home.impl import com.bumble.appyx.core.modality.BuildContext import com.google.common.truth.Truth.assertThat import io.element.android.features.home.api.HomeEntryPoint +import io.element.android.features.invite.test.declineandblock.FakeDeclineInviteAndBlockEntryPoint +import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.test.FakeMatrixClient @@ -36,14 +38,14 @@ class DefaultHomeEntryPointTest : RobolectricTest() { acceptDeclineInviteView = { _, _, _, _ -> lambdaError() }, directLogoutView = { _ -> lambdaError() }, reportRoomEntryPoint = { _, _, _ -> lambdaError() }, - declineInviteAndBlockUserEntryPoint = { _, _, _ -> lambdaError() }, + declineInviteAndBlockUserEntryPoint = FakeDeclineInviteAndBlockEntryPoint(), changeRoomMemberRolesEntryPoint = { _, _, _, _ -> lambdaError() }, leaveRoomRenderer = { _, _, _ -> lambdaError() }, sessionCoroutineScope = backgroundScope, ) } val callback = object : HomeEntryPoint.Callback { - override fun navigateToRoom(roomId: RoomId, joinedRoom: JoinedRoom?) = lambdaError() + override fun navigateToRoom(roomId: RoomId, eventId: EventId?, joinedRoom: JoinedRoom?) = lambdaError() override fun navigateToCreateRoom() = lambdaError() override fun navigateToCreateSpace() = lambdaError() override fun navigateToSettings() = lambdaError() diff --git a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersPresenterTest.kt b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersPresenterTest.kt index 9fb87c0eec..02d947613f 100644 --- a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersPresenterTest.kt +++ b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/filters/RoomListFiltersPresenterTest.kt @@ -72,6 +72,49 @@ class RoomListFiltersPresenterTest { } } + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `present - toggling two incompatible filters in the same frame keeps the first one`() = runTest { + val presenter = createRoomListFiltersPresenter() + presenter.test { + awaitItem().let { state -> + state.eventSink.invoke(RoomListFiltersEvent.ToggleFilter(RoomListFilter.Favourites)) + state.eventSink.invoke(RoomListFiltersEvent.ToggleFilter(RoomListFilter.Invites)) + } + advanceUntilIdle() + awaitLastSequentialItem().let { state -> + assertThat(state.selectedFilters()).containsExactly(RoomListFilter.Favourites) + assertThat(state.filterSelectionStates).containsExactly( + filterSelectionState(RoomListFilter.Favourites, true), + filterSelectionState(RoomListFilter.Unread, false), + filterSelectionState(RoomListFilter.People, false), + filterSelectionState(RoomListFilter.Rooms, false), + ).inOrder() + } + } + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `present - toggling two incompatible categories in the same frame keeps the first one`() = runTest { + val presenter = createRoomListFiltersPresenter() + presenter.test { + awaitItem().let { state -> + state.eventSink.invoke(RoomListFiltersEvent.ToggleFilter(RoomListFilter.People)) + state.eventSink.invoke(RoomListFiltersEvent.ToggleFilter(RoomListFilter.Rooms)) + } + advanceUntilIdle() + awaitLastSequentialItem().let { state -> + assertThat(state.selectedFilters()).containsExactly(RoomListFilter.People) + assertThat(state.filterSelectionStates).containsExactly( + filterSelectionState(RoomListFilter.People, true), + filterSelectionState(RoomListFilter.Unread, false), + filterSelectionState(RoomListFilter.Favourites, false), + ).inOrder() + } + } + } + @Test @OptIn(ExperimentalCoroutinesApi::class) fun `present - clear filters event`() = runTest { diff --git a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenterTest.kt b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenterTest.kt index 64dfc46ee2..d2e33c77c1 100644 --- a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenterTest.kt +++ b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListPresenterTest.kt @@ -20,6 +20,7 @@ import io.element.android.features.home.impl.filters.aRoomListFiltersState import io.element.android.features.home.impl.model.createRoomListRoomSummary import io.element.android.features.home.impl.search.RoomListSearchEvent import io.element.android.features.home.impl.search.RoomListSearchState +import io.element.android.features.home.impl.search.aGlobalSearchState import io.element.android.features.home.impl.search.aRoomListSearchState import io.element.android.features.home.impl.spacefilters.SpaceFiltersState import io.element.android.features.home.impl.spacefilters.aDisabledSpaceFiltersState @@ -680,6 +681,7 @@ class RoomListPresenterTest { analyticsService = FakeAnalyticsService(), ), searchPresenter = searchPresenter, + globalSearchPresenter = { aGlobalSearchState() }, filtersPresenter = filtersPresenter, spaceFiltersPresenter = spaceFiltersPresenter, analyticsService = analyticsService, diff --git a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListViewTest.kt b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListViewTest.kt index 773f428917..bd18cd903e 100644 --- a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListViewTest.kt +++ b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/roomlist/RoomListViewTest.kt @@ -277,7 +277,7 @@ private fun AndroidComposeUiTest.setRoomListView( setSafeContent { HomeView( homeState = aHomeState(roomListState = state), - onRoomClick = onRoomClick, + onRoomClick = { roomId, _ -> onRoomClick(roomId) }, onSettingsClick = onSettingsClick, onSetUpRecoveryClick = onSetUpRecoveryClick, onConfirmRecoveryKeyClick = onConfirmRecoveryKeyClick, diff --git a/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/search/GlobalSearchPresenterTest.kt b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/search/GlobalSearchPresenterTest.kt new file mode 100644 index 0000000000..94c19bb81d --- /dev/null +++ b/features/home/impl/src/test/kotlin/io/element/android/features/home/impl/search/GlobalSearchPresenterTest.kt @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +@file:OptIn(ExperimentalCoroutinesApi::class) + +package io.element.android.features.home.impl.search + +import com.google.common.truth.Truth.assertThat +import io.element.android.features.home.impl.datasource.aRoomListRoomSummaryFactory +import io.element.android.libraries.androidutils.filesize.FakeFileSizeFormatter +import io.element.android.libraries.androidutils.filesize.FileSizeFormatter +import io.element.android.libraries.architecture.AsyncData +import io.element.android.libraries.dateformatter.api.DateFormatter +import io.element.android.libraries.dateformatter.test.FakeDateFormatter +import io.element.android.libraries.eventformatter.api.RoomLatestEventFormatter +import io.element.android.libraries.eventformatter.test.FakeRoomLatestEventFormatter +import io.element.android.libraries.featureflag.api.FeatureFlagService +import io.element.android.libraries.featureflag.api.FeatureFlags +import io.element.android.libraries.featureflag.test.FakeFeatureFlagService +import io.element.android.libraries.matrix.api.MatrixClient +import io.element.android.libraries.matrix.api.permalink.PermalinkParser +import io.element.android.libraries.matrix.api.roomlist.RoomListService +import io.element.android.libraries.matrix.api.search.MessageSearchService +import io.element.android.libraries.matrix.test.FakeMatrixClient +import io.element.android.libraries.matrix.test.permalink.FakePermalinkParser +import io.element.android.libraries.matrix.test.room.aRoomSummary +import io.element.android.libraries.matrix.test.roomlist.FakeDynamicRoomList +import io.element.android.libraries.matrix.test.roomlist.FakeRoomListService +import io.element.android.libraries.matrix.test.search.FakeMessageSearch +import io.element.android.libraries.matrix.test.search.FakeMessageSearchService +import io.element.android.tests.testutils.consumeItemsUntilPredicate +import io.element.android.tests.testutils.test +import io.element.android.tests.testutils.testCoroutineDispatchers +import kotlinx.collections.immutable.persistentListOf +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Test +import java.util.Optional + +class GlobalSearchPresenterTest { + @Test + fun `present - initial state`() = runTest { + val presenter = createGlobalSearchPresenter() + presenter.test { + awaitItem().let { state -> + assertThat(state.isEnabled).isFalse() + assertThat(state.isSearchActive).isFalse() + assertThat(state.queryState.text.toString()).isEmpty() + assertThat(state.currentTarget).isEqualTo(GlobalSearchTarget.ROOMS) + assertThat(state.results).isEqualTo(AsyncData.Uninitialized) + } + } + } + + @Test + fun `present - isEnabled reflects the feature flag`() = runTest { + val presenter = createGlobalSearchPresenter( + featureFlagService = FakeFeatureFlagService( + initialState = mapOf(FeatureFlags.MessageSearch.key to true), + ), + ) + presenter.test { + // isEnabled is emitted asynchronously via produceState, so it starts as false and flips to true + var state = awaitItem() + while (!state.isEnabled) { + state = awaitItem() + } + assertThat(state.isEnabled).isTrue() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - toggle search visibility`() = runTest { + val presenter = createGlobalSearchPresenter() + presenter.test { + awaitItem().let { state -> + assertThat(state.isSearchActive).isFalse() + state.eventSink(GlobalSearchEvent.ToggleSearchVisibility) + } + awaitItem().let { state -> + assertThat(state.isSearchActive).isTrue() + state.eventSink(GlobalSearchEvent.ToggleSearchVisibility) + } + awaitItem().let { state -> + assertThat(state.isSearchActive).isFalse() + } + } + } + + @Test + fun `present - update target`() = runTest { + val presenter = createGlobalSearchPresenter() + presenter.test { + awaitItem().let { state -> + assertThat(state.currentTarget).isEqualTo(GlobalSearchTarget.ROOMS) + state.eventSink(GlobalSearchEvent.UpdateTarget(GlobalSearchTarget.MESSAGES)) + } + awaitItem().let { state -> + assertThat(state.currentTarget).isEqualTo(GlobalSearchTarget.MESSAGES) + } + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - clear query`() = runTest { + val presenter = createGlobalSearchPresenter() + presenter.test { + val initialState = awaitItem() + initialState.queryState.edit { append("A query") } + awaitItem().let { state -> + assertThat(state.queryState.text.toString()).isEqualTo("A query") + state.eventSink(GlobalSearchEvent.ClearQuery) + } + awaitItem().let { state -> + assertThat(state.queryState.text.toString()).isEmpty() + } + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - room search results are emitted when the room list changes`() = runTest { + val roomList = FakeDynamicRoomList() + val roomListService = FakeRoomListService(createRoomListLambda = { roomList }) + val presenter = createGlobalSearchPresenter(roomListService = roomListService) + presenter.test { + val initialState = awaitItem() + assertThat(initialState.results).isEqualTo(AsyncData.Uninitialized) + + initialState.queryState.edit { append("A query") } + // Let the query be propagated to the data source before emitting results + testScheduler.advanceUntilIdle() + roomList.summaries.emit(listOf(aRoomSummary())) + + // Wait for the presenter to emit a loading state before the success state + consumeItemsUntilPredicate { it.results is AsyncData.Loading } + + val successState = awaitItem() + val results = (successState.results.dataOrNull() as GlobalSearchResults.RoomListResults).results + assertThat(results).hasSize(1) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - room search displays the uninitialized state when removing the query`() = runTest { + val roomList = FakeDynamicRoomList() + val roomListService = FakeRoomListService(createRoomListLambda = { roomList }) + val presenter = createGlobalSearchPresenter(roomListService = roomListService) + presenter.test { + val initialState = awaitItem() + assertThat(initialState.results).isEqualTo(AsyncData.Uninitialized) + + initialState.queryState.edit { append("A query") } + // Let the query be propagated to the data source before emitting results + testScheduler.advanceUntilIdle() + roomList.summaries.emit(listOf(aRoomSummary())) + + // Wait for the presenter to emit a loading state before the success state + consumeItemsUntilPredicate { it.results is AsyncData.Loading } + + val successState = awaitItem() + val results = (successState.results.dataOrNull() as GlobalSearchResults.RoomListResults).results + assertThat(results).hasSize(1) + + // Remove the query + successState.queryState.edit { replace(0, length, "") } + // Skip the intermediate state where the query is empty but results are still present + skipItems(1) + // It's back to the uninitialized state + assertThat(awaitItem().results).isInstanceOf(AsyncData.Uninitialized::class.java) + // This happens even if for some reason the room results still contained any items + assertThat(roomList.summaries.value).isNotEmpty() + } + } + + @Test + fun `present - message search results are mapped when the message search emits`() = runTest { + val messageSearch = FakeMessageSearch() + val matrixClient = FakeMatrixClient().apply { + getRoomInfoFlowLambda = { flowOf(Optional.of(aRoomInfo())) } + } + val presenter = createGlobalSearchPresenter( + messageSearchService = FakeMessageSearchService(messageSearch), + matrixClient = matrixClient, + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(GlobalSearchEvent.UpdateTarget(GlobalSearchTarget.MESSAGES)) + initialState.queryState.edit { append("A query") } + testScheduler.advanceUntilIdle() + + messageSearch.emitResults(persistentListOf(aMessageSearchResult())) + testScheduler.advanceUntilIdle() + + val successState = consumeItemsUntilPredicate { it.results is AsyncData.Success }.last() + val results = (successState.results.dataOrNull() as GlobalSearchResults.MessageSearchResults).results + assertThat(results).hasSize(1) + assertThat(results.first()).isInstanceOf(MessageSearchResultItem.Message::class.java) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - message search displays the uninitialized state after removing the query`() = runTest { + val messageSearch = FakeMessageSearch() + val matrixClient = FakeMatrixClient().apply { + getRoomInfoFlowLambda = { flowOf(Optional.of(aRoomInfo())) } + } + val presenter = createGlobalSearchPresenter( + messageSearchService = FakeMessageSearchService(messageSearch), + matrixClient = matrixClient, + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(GlobalSearchEvent.UpdateTarget(GlobalSearchTarget.MESSAGES)) + initialState.queryState.edit { append("A query") } + testScheduler.advanceUntilIdle() + + messageSearch.emitResults(persistentListOf(aMessageSearchResult())) + testScheduler.advanceUntilIdle() + + val successState = consumeItemsUntilPredicate { it.results is AsyncData.Success }.last() + val results = (successState.results.dataOrNull() as GlobalSearchResults.MessageSearchResults).results + assertThat(results).hasSize(1) + assertThat(results.first()).isInstanceOf(MessageSearchResultItem.Message::class.java) + + // Remove the query + successState.queryState.edit { replace(0, length, "") } + // Skip the intermediate state where the query is empty but results are still present + skipItems(1) + // It's back to the uninitialized state + assertThat(awaitItem().results).isInstanceOf(AsyncData.Uninitialized::class.java) + // This happens even if for some reason the message results still contained any items + assertThat(messageSearch.results.value).isNotEmpty() + } + } + + @Test + fun `present - UpdateVisibleRange triggers pagination for messages when near the end`() = runTest { + val messageSearch = FakeMessageSearch() + val matrixClient = FakeMatrixClient().apply { + getRoomInfoFlowLambda = { flowOf(Optional.of(aRoomInfo())) } + } + val presenter = createGlobalSearchPresenter( + messageSearchService = FakeMessageSearchService(messageSearch), + matrixClient = matrixClient, + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(GlobalSearchEvent.UpdateTarget(GlobalSearchTarget.MESSAGES)) + initialState.queryState.edit { append("A query") } + testScheduler.advanceUntilIdle() + + messageSearch.emitResults(persistentListOf(aMessageSearchResult())) + val successState = consumeItemsUntilPredicate { it.results is AsyncData.Success }.last() + + successState.eventSink(GlobalSearchEvent.UpdateVisibleRange(IntRange(0, 0))) + runCurrent() + testScheduler.advanceUntilIdle() + + assertThat(messageSearch.paginateCallCount).isEqualTo(1) + cancelAndIgnoreRemainingEvents() + } + } +} + +private fun TestScope.createGlobalSearchPresenter( + roomListService: RoomListService = FakeRoomListService(), + messageSearchService: MessageSearchService = FakeMessageSearchService(), + featureFlagService: FeatureFlagService = FakeFeatureFlagService(), + latestEventFormatter: RoomLatestEventFormatter = FakeRoomLatestEventFormatter(), + dateFormatter: DateFormatter = FakeDateFormatter(), + fileSizeFormatter: FileSizeFormatter = FakeFileSizeFormatter(), + permalinkParser: PermalinkParser = FakePermalinkParser(), + matrixClient: MatrixClient = FakeMatrixClient(), +): GlobalSearchPresenter { + return GlobalSearchPresenter( + roomListSearchDataSourceFactory = object : RoomListSearchDataSource.Factory { + override fun create(coroutineScope: CoroutineScope): RoomListSearchDataSource { + return RoomListSearchDataSource( + coroutineScope = coroutineScope, + roomListService = roomListService, + coroutineDispatchers = testCoroutineDispatchers(), + roomSummaryFactory = aRoomListRoomSummaryFactory(), + ) + } + }, + messageSearchService = messageSearchService, + featureFlagService = featureFlagService, + latestEventFormatter = latestEventFormatter, + dateFormatter = dateFormatter, + fileSizeFormatter = fileSizeFormatter, + permalinkParser = permalinkParser, + coroutineDispatchers = testCoroutineDispatchers(), + matrixClient = matrixClient, + ) +} diff --git a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/SeenInvitesStore.kt b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/SeenInvitesStore.kt index 046303ca4f..d8ab7c71c8 100644 --- a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/SeenInvitesStore.kt +++ b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/SeenInvitesStore.kt @@ -11,6 +11,9 @@ package io.element.android.features.invite.api import io.element.android.libraries.matrix.api.core.RoomId import kotlinx.coroutines.flow.Flow +/** + * Remembers which invitations the user has already looked at, so that only genuinely new ones are highlighted in the room list. + */ interface SeenInvitesStore { /** * Returns a flow of seen room IDs of invitation. @@ -32,7 +35,7 @@ interface SeenInvitesStore { suspend fun markAsUnSeen(roomId: RoomId) /** - * Delete the store. + * Delete the store, so every invitation counts as unseen again. */ suspend fun clear() } diff --git a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteEvents.kt b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteEvents.kt index 2caaacab2b..5691b19ef7 100644 --- a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteEvents.kt +++ b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteEvents.kt @@ -10,6 +10,9 @@ package io.element.android.features.invite.api.acceptdecline import io.element.android.features.invite.api.InviteData +/** + * Events sent to the accept/decline invite presenter, from whichever screen is showing the invitation. + */ interface AcceptDeclineInviteEvents { data class AcceptInvite(val invite: InviteData) : AcceptDeclineInviteEvents data class DeclineInvite(val invite: InviteData, val blockUser: Boolean, val shouldConfirm: Boolean) : AcceptDeclineInviteEvents diff --git a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteStateProvider.kt b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteStatePreviewParam.kt similarity index 100% rename from features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteStateProvider.kt rename to features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteStatePreviewParam.kt diff --git a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteView.kt b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteView.kt index b6eec03a6f..6e9d78082b 100644 --- a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteView.kt +++ b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/acceptdecline/AcceptDeclineInviteView.kt @@ -12,7 +12,20 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import io.element.android.libraries.matrix.api.core.RoomId +/** + * Renders the confirmation dialogs and error states of accepting or declining an invitation; it draws nothing until such an event is sent. + * + * Embedded by every screen that can act on an invitation, so the behaviour stays identical between the invite list and a room preview. + */ fun interface AcceptDeclineInviteView { + /** + * Draws whichever dialog the current state calls for. + * + * @param state the state produced by the accept/decline presenter. + * @param onAcceptInviteSuccess called once the room has been joined, so the host screen can navigate into it. + * @param onDeclineInviteSuccess called once the invitation has been declined. + * @param modifier layout modifier for the container. + */ @Composable fun Render( state: AcceptDeclineInviteState, diff --git a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/declineandblock/DeclineInviteAndBlockEntryPoint.kt b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/declineandblock/DeclineInviteAndBlockEntryPoint.kt index 4174d99222..3b9d512d80 100644 --- a/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/declineandblock/DeclineInviteAndBlockEntryPoint.kt +++ b/features/invite/api/src/main/kotlin/io/element/android/features/invite/api/declineandblock/DeclineInviteAndBlockEntryPoint.kt @@ -10,13 +10,19 @@ package io.element.android.features.invite.api.declineandblock import com.bumble.appyx.core.modality.BuildContext import com.bumble.appyx.core.node.Node +import com.bumble.appyx.core.plugin.Plugin import io.element.android.features.invite.api.InviteData import io.element.android.libraries.architecture.FeatureEntryPoint -fun interface DeclineInviteAndBlockEntryPoint : FeatureEntryPoint { +interface DeclineInviteAndBlockEntryPoint : FeatureEntryPoint { fun createNode( parentNode: Node, buildContext: BuildContext, inviteData: InviteData, + callback: Callback, ): Node + + interface Callback : Plugin { + fun onDeclineSuccess() + } } diff --git a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteStateProvider.kt b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteStatePreviewParam.kt similarity index 95% rename from features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteStateProvider.kt rename to features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteStatePreviewParam.kt index db2e76c1c3..ad9bf01667 100644 --- a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteStateProvider.kt +++ b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteStatePreviewParam.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.designsystem.preview.ROOM_NAME import io.element.android.libraries.matrix.api.core.RoomId -open class AcceptDeclineInviteStateProvider : PreviewParameterProvider { +open class AcceptDeclineInviteStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAcceptDeclineInviteState(), diff --git a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteView.kt b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteView.kt index da035f0ff1..c3df984604 100644 --- a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteView.kt +++ b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/acceptdecline/AcceptDeclineInviteView.kt @@ -123,7 +123,7 @@ private fun DeclineConfirmationDialog( @PreviewsDayNight @Composable -internal fun AcceptDeclineInviteViewPreview(@PreviewParameter(AcceptDeclineInviteStateProvider::class) state: AcceptDeclineInviteState) = +internal fun AcceptDeclineInviteViewPreview(@PreviewParameter(AcceptDeclineInviteStatePreviewParam::class) state: AcceptDeclineInviteState) = ElementPreview { AcceptDeclineInviteView( state = state, diff --git a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockNode.kt b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockNode.kt index 2fe5c23088..89a2aaf238 100644 --- a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockNode.kt +++ b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockNode.kt @@ -17,7 +17,9 @@ import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedInject import io.element.android.annotations.ContributesNode import io.element.android.features.invite.api.InviteData +import io.element.android.features.invite.api.declineandblock.DeclineInviteAndBlockEntryPoint import io.element.android.libraries.architecture.NodeInputs +import io.element.android.libraries.architecture.callback import io.element.android.libraries.architecture.inputs import io.element.android.libraries.di.SessionScope @@ -31,6 +33,7 @@ class DeclineAndBlockNode( data class Inputs(val inviteData: InviteData) : NodeInputs private val inviteData = inputs().inviteData + private val callback: DeclineInviteAndBlockEntryPoint.Callback = callback() private val presenter = presenterFactory.create(inviteData) @Composable @@ -39,6 +42,7 @@ class DeclineAndBlockNode( DeclineAndBlockView( state = state, onBackClick = ::navigateUp, + onDeclineSuccess = callback::onDeclineSuccess, modifier = modifier ) } diff --git a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockStateProvider.kt b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockStatePreviewParam.kt similarity index 93% rename from features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockStateProvider.kt rename to features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockStatePreviewParam.kt index 2e78214306..704fc9f045 100644 --- a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockStateProvider.kt +++ b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.invite.impl.declineandblock import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class DeclineAndBlockStateProvider : PreviewParameterProvider { +open class DeclineAndBlockStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDeclineAndBlockState(), diff --git a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockView.kt b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockView.kt index 1d14df024a..c30742de12 100644 --- a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockView.kt +++ b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockView.kt @@ -46,6 +46,7 @@ import io.element.android.libraries.ui.strings.CommonStrings fun DeclineAndBlockView( state: DeclineAndBlockState, onBackClick: () -> Unit, + onDeclineSuccess: () -> Unit, modifier: Modifier = Modifier, ) { val focusManager = LocalFocusManager.current @@ -53,7 +54,7 @@ fun DeclineAndBlockView( val isDeclining = state.declineAction is AsyncAction.Loading AsyncActionView( async = state.declineAction, - onSuccess = { onBackClick() }, + onSuccess = { onDeclineSuccess() }, errorMessage = { stringResource(CommonStrings.error_unknown) }, onRetry = { state.eventSink(DeclineAndBlockEvents.Decline) }, onErrorDismiss = { state.eventSink(DeclineAndBlockEvents.ClearDeclineAction) } @@ -144,10 +145,11 @@ fun DeclineAndBlockView( @PreviewsDayNight @Composable internal fun DeclineAndBlockViewPreview( - @PreviewParameter(DeclineAndBlockStateProvider::class) state: DeclineAndBlockState + @PreviewParameter(DeclineAndBlockStatePreviewParam::class) state: DeclineAndBlockState ) = ElementPreview { DeclineAndBlockView( state = state, onBackClick = {}, + onDeclineSuccess = {}, ) } diff --git a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPoint.kt b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPoint.kt index d6e93fb805..4a5734af45 100644 --- a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPoint.kt +++ b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPoint.kt @@ -22,8 +22,9 @@ class DefaultDeclineAndBlockEntryPoint : DeclineInviteAndBlockEntryPoint { parentNode: Node, buildContext: BuildContext, inviteData: InviteData, + callback: DeclineInviteAndBlockEntryPoint.Callback, ): Node { val inputs = DeclineAndBlockNode.Inputs(inviteData) - return parentNode.createNode(buildContext, plugins = listOf(inputs)) + return parentNode.createNode(buildContext, plugins = listOf(inputs, callback)) } } diff --git a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/di/InviteModule.kt b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/di/InviteBindingContainer.kt similarity index 89% rename from features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/di/InviteModule.kt rename to features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/di/InviteBindingContainer.kt index f78c0358a6..f7cd346755 100644 --- a/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/di/InviteModule.kt +++ b/features/invite/impl/src/main/kotlin/io/element/android/features/invite/impl/di/InviteBindingContainer.kt @@ -22,9 +22,9 @@ import io.element.android.libraries.matrix.api.MatrixClient @ContributesTo(SessionScope::class) @BindingContainer -interface InviteModule { +interface InviteBindingContainer { @Binds - fun bindAcceptDeclinePresenter(presenter: AcceptDeclineInvitePresenter): Presenter + fun bindAcceptDeclineInvitePresenter(presenter: AcceptDeclineInvitePresenter): Presenter companion object { @Provides diff --git a/features/invite/impl/src/main/res/values-ar/translations.xml b/features/invite/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..31ed141c3e --- /dev/null +++ b/features/invite/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,18 @@ + + + "لن ترى أي رسائل أو دعوات إلى غرف من هذا المستخدم" + "حظر المستخدم" + "أبلغ موفّر حسابك عن هذه الغرفة." + "صِف سبب الإبلاغ…" + "رفض وحظر" + "أمتأكد من رغبتك برفض دعوة للانضمام إلى %1$s؟" + "رفض الدعوة" + "أمتأكد من رغبتك برفض المحادثة الخاصة مع %1$s؟" + "رفض المحادثة" + "لا دعوات" + "دعاك %1$s (%2$s)" + "نعم، ارفض واحظر" + "هل أنت متأكد من رغبتك في رفض الدعوة للانضمام إلى هذه الغرفة؟ سيمنع هذا أيضًا %1$s من التواصل معك أو دعوتك إلى غرف." + "رفض الدعوة والحظر" + "رفض وحظر" + diff --git a/features/invite/impl/src/main/res/values-fa/translations.xml b/features/invite/impl/src/main/res/values-fa/translations.xml index 9cbad94f91..9e245d7e9f 100644 --- a/features/invite/impl/src/main/res/values-fa/translations.xml +++ b/features/invite/impl/src/main/res/values-fa/translations.xml @@ -1,6 +1,8 @@ + "شما هیچ پیام یا دعوتنامه‌ای از این کاربر نخواهید دید." "انسداد کاربر" + "این اتاق را به ارائه دهنده حساب خود گزارش دهید." "شرح دلیل گزارش…" "رد و انسداد" "مطمئنید که می‌خواهید دعوت پیوستن به %1$s را رد کنید؟" @@ -10,6 +12,7 @@ "بدون دعوت" "%1$s (%2$s) دعوتتان کرد" "بله. رد و انسداد" + "آیا مطمئنید که می‌خواهید دعوت به عضویت در این اتاق را رد کنید؟ این کار همچنین مانع از تماس %1$s با شما یا دعوت شما به اتاق‌ها می‌شود." "رد دعوت و انسداد" "رد و انسداد" diff --git a/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockViewTest.kt b/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockViewTest.kt index 55c31a09d2..5cfb091e82 100644 --- a/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockViewTest.kt +++ b/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DeclineAndBlockViewTest.kt @@ -17,6 +17,7 @@ import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.v2.runAndroidComposeUiTest import io.element.android.features.invite.impl.R +import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.ui.strings.CommonStrings import io.element.android.tests.testutils.EnsureNeverCalled import io.element.android.tests.testutils.EventsRecorder @@ -41,6 +42,20 @@ class DeclineAndBlockViewTest : RobolectricTest() { } } + @Test + fun `a successful decline invokes the expected callback`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder(expectEvents = false) + ensureCalledOnce { + setDeclineAndBlockView( + aDeclineAndBlockState( + declineAction = AsyncAction.Success(Unit), + eventSink = eventsRecorder, + ), + onDeclineSuccess = it, + ) + } + } + @Test fun `clicking on decline when enabled emits the expected event`() = runAndroidComposeUiTest { val eventsRecorder = EventsRecorder() @@ -112,11 +127,13 @@ class DeclineAndBlockViewTest : RobolectricTest() { private fun AndroidComposeUiTest.setDeclineAndBlockView( state: DeclineAndBlockState, onBackClick: () -> Unit = EnsureNeverCalled(), + onDeclineSuccess: () -> Unit = EnsureNeverCalled(), ) { setContent { DeclineAndBlockView( state = state, onBackClick = onBackClick, + onDeclineSuccess = onDeclineSuccess, ) } } diff --git a/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPointTest.kt b/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPointTest.kt index 13bb13dccf..f09cda2337 100644 --- a/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPointTest.kt +++ b/features/invite/impl/src/test/kotlin/io/element/android/features/invite/impl/declineandblock/DefaultDeclineAndBlockEntryPointTest.kt @@ -11,7 +11,9 @@ package io.element.android.features.invite.impl.declineandblock import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.bumble.appyx.core.modality.BuildContext import com.google.common.truth.Truth.assertThat +import io.element.android.features.invite.api.declineandblock.DeclineInviteAndBlockEntryPoint import io.element.android.features.invite.test.anInviteData +import io.element.android.tests.testutils.lambda.lambdaError import io.element.android.tests.testutils.node.TestParentNode import org.junit.Rule import org.junit.Test @@ -31,12 +33,17 @@ class DefaultDeclineAndBlockEntryPointTest { ) } val inviteData = anInviteData() + val callback = object : DeclineInviteAndBlockEntryPoint.Callback { + override fun onDeclineSuccess() = lambdaError() + } val result = entryPoint.createNode( parentNode = parentNode, buildContext = BuildContext.root(null), - inviteData = inviteData + inviteData = inviteData, + callback = callback, ) assertThat(result).isInstanceOf(DeclineAndBlockNode::class.java) assertThat(result.plugins).contains(DeclineAndBlockNode.Inputs(inviteData)) + assertThat(result.plugins).contains(callback) } } diff --git a/features/invite/test/src/main/kotlin/io/element/android/features/invite/test/declineandblock/FakeDeclineInviteAndBlockEntryPoint.kt b/features/invite/test/src/main/kotlin/io/element/android/features/invite/test/declineandblock/FakeDeclineInviteAndBlockEntryPoint.kt index 52d4d17790..19625f1473 100644 --- a/features/invite/test/src/main/kotlin/io/element/android/features/invite/test/declineandblock/FakeDeclineInviteAndBlockEntryPoint.kt +++ b/features/invite/test/src/main/kotlin/io/element/android/features/invite/test/declineandblock/FakeDeclineInviteAndBlockEntryPoint.kt @@ -19,6 +19,7 @@ class FakeDeclineInviteAndBlockEntryPoint : DeclineInviteAndBlockEntryPoint { parentNode: Node, buildContext: BuildContext, inviteData: InviteData, + callback: DeclineInviteAndBlockEntryPoint.Callback, ): Node { lambdaError() } diff --git a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleEvents.kt b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleEvents.kt index 0422fac4f1..9570ab8152 100644 --- a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleEvents.kt +++ b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleEvents.kt @@ -8,6 +8,9 @@ package io.element.android.features.invitepeople.api +/** + * Events the invite people UI sends to its presenter through [InvitePeopleState.eventSink]. + */ interface InvitePeopleEvents { data object SendInvites : InvitePeopleEvents data object CloseSearch : InvitePeopleEvents diff --git a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeoplePresenter.kt b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeoplePresenter.kt index 0be0798680..1863397e48 100644 --- a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeoplePresenter.kt +++ b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeoplePresenter.kt @@ -13,7 +13,14 @@ import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.room.JoinedRoom interface InvitePeoplePresenter : Presenter { + /** + * Creates a presenter for one invite flow. + */ interface Factory { + /** + * @param joinedRoom the room to invite into, or `null` when the room does not exist yet, as when inviting from a direct message. + * @param roomId the id of the room to invite into. + */ fun create( joinedRoom: JoinedRoom?, roomId: RoomId, diff --git a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleRenderer.kt b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleRenderer.kt index 7bad81ab65..0bbaa45a2f 100644 --- a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleRenderer.kt +++ b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleRenderer.kt @@ -11,7 +11,16 @@ package io.element.android.features.invitepeople.api import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +/** + * Renders the invite people UI, so that other screens can embed it without depending on its implementation. + */ interface InvitePeopleRenderer { + /** + * Draws the invite list and its search field. + * + * @param state the state produced by [InvitePeoplePresenter]. + * @param modifier layout modifier for the container. + */ @Composable fun Render( state: InvitePeopleState, diff --git a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleState.kt b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleState.kt index d14042cff7..0863ec7212 100644 --- a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleState.kt +++ b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleState.kt @@ -11,10 +11,22 @@ package io.element.android.features.invitepeople.api import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.core.RoomId +/** + * State of the invite people UI, produced by an [InvitePeoplePresenter] and consumed by an [InvitePeopleRenderer]. + */ interface InvitePeopleState { + /** Whether the send button should be enabled, i.e. at least one user is selected and the user has the permission. */ val canInvite: Boolean + + /** Whether the search field currently has focus, which the host screen uses to adapt its own layout. */ val isSearchActive: Boolean + + /** Progress of the invite request, so the UI can show a loader and surface failures. */ val sendInvitesAction: AsyncAction + + /** Progress of turning a direct message into a room, which happens when inviting a third person into a DM. */ val createRoomFromDmAction: AsyncAction + + /** Where the UI sends its events. */ val eventSink: (InvitePeopleEvents) -> Unit } diff --git a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleStateProvider.kt b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleStatePreviewParam.kt similarity index 95% rename from features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleStateProvider.kt rename to features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleStatePreviewParam.kt index b233ed07ef..860efc2771 100644 --- a/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleStateProvider.kt +++ b/features/invitepeople/api/src/main/kotlin/io/element/android/features/invitepeople/api/InvitePeopleStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.core.RoomId -class InvitePeopleStateProvider : PreviewParameterProvider { +class InvitePeopleStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aPreviewInvitePeopleState(), diff --git a/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/DefaultInvitePeopleStateProvider.kt b/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/DefaultInvitePeopleStatePreviewParam.kt similarity index 98% rename from features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/DefaultInvitePeopleStateProvider.kt rename to features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/DefaultInvitePeopleStatePreviewParam.kt index 1e41114406..9aad913856 100644 --- a/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/DefaultInvitePeopleStateProvider.kt +++ b/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/DefaultInvitePeopleStatePreviewParam.kt @@ -26,7 +26,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -internal class DefaultInvitePeopleStateProvider : PreviewParameterProvider { +internal class DefaultInvitePeopleStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDefaultInvitePeopleState(), diff --git a/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/InvitePeopleView.kt b/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/InvitePeopleView.kt index 0ee3559aa3..7dced41b13 100644 --- a/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/InvitePeopleView.kt +++ b/features/invitepeople/impl/src/main/kotlin/io/element/android/features/invitepeople/impl/InvitePeopleView.kt @@ -316,7 +316,7 @@ private fun InvitePeopleConfirmModal( @PreviewsDayNight @Composable -internal fun InvitePeopleViewPreview(@PreviewParameter(DefaultInvitePeopleStateProvider::class) state: DefaultInvitePeopleState) = +internal fun InvitePeopleViewPreview(@PreviewParameter(DefaultInvitePeopleStatePreviewParam::class) state: DefaultInvitePeopleState) = ElementPreview { InvitePeopleView(state = state) } diff --git a/features/invitepeople/impl/src/main/res/values-ar/translations.xml b/features/invitepeople/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..fa28cb13b9 --- /dev/null +++ b/features/invitepeople/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,9 @@ + + + "أنت عضو بالفعل" + "مَدعُوّ بالفعل" + "ليست لديك حاليًا أي دردشات مع جهات الاتصال هذه. أكّد دعوتهم إلى هذه الغرفة قبل المتابعة." + "ليست لديك حاليًا أي دردشات مع جهة الاتصال هذه. أكّد دعوتها إلى هذه الغرفة قبل المتابعة." + "هل تريد دعوة جهات اتصال جديدة إلى هذه الغرفة؟" + "هل تريد دعوة جهة اتصال جديدة إلى هذه الغرفة؟" + diff --git a/features/invitepeople/impl/src/main/res/values-de/translations.xml b/features/invitepeople/impl/src/main/res/values-de/translations.xml index 182d9f289a..d0c2da50b4 100644 --- a/features/invitepeople/impl/src/main/res/values-de/translations.xml +++ b/features/invitepeople/impl/src/main/res/values-de/translations.xml @@ -2,4 +2,8 @@ "Bereits Mitglied" "Bereits eingeladen" + "Du hast derzeit keine Chats mit diesen Kontakten. Bestätige, dass du sie in diesen Chat einladen möchtest, bevor du fortfährst." + "Du hast derzeit keine Chats mit diesem Kontakt. Bestätige, dass du ihn in diesen Chat einladen möchtest, bevor du fortfährst." + "Möchtest du neue Kontakte in diesen Chat einladen?" + "Willst du einen neuen Kontakt in diesen Chat einladen?" diff --git a/features/invitepeople/impl/src/main/res/values-es/translations.xml b/features/invitepeople/impl/src/main/res/values-es/translations.xml index e62bb211e5..b9058446b4 100644 --- a/features/invitepeople/impl/src/main/res/values-es/translations.xml +++ b/features/invitepeople/impl/src/main/res/values-es/translations.xml @@ -1,5 +1,9 @@ - "Ya eres miembro" + "Ya es miembro" "Ya estás invitado" + "De momento no tienes ningún chat con estos contactos. Confirma que quieres invitarlos a esta sala antes de continuar." + "De momento no tienes ningún chat con este contacto. Confirma que quieres invitarlo a esta sala antes de continuar." + "¿Invitar contactos nuevos a esta sala?" + "¿Invitar contacto nuevo a esta sala?" diff --git a/features/invitepeople/impl/src/main/res/values-fa/translations.xml b/features/invitepeople/impl/src/main/res/values-fa/translations.xml index 544f01b8c8..100abe539c 100644 --- a/features/invitepeople/impl/src/main/res/values-fa/translations.xml +++ b/features/invitepeople/impl/src/main/res/values-fa/translations.xml @@ -2,4 +2,8 @@ "از پیش عضو است" "از پیش دعوت شده" + "شما در حال حاضر هیچ گفت‌وگویی با این مخاطبین ندارید. قبل از ادامه، دعوت آنها را به این اتاق تأیید کنید." + "شما در حال حاضر هیچ گفت‌وگویی با این مخاطب ندارید. قبل از ادامه، دعوت او را به این اتاق تأیید کنید." + "مخاطبین جدید را به این اتاق دعوت کنید؟" + "مخاطب جدید را به این اتاق دعوت می‌کنید؟" diff --git a/features/invitepeople/impl/src/main/res/values-zh-rTW/translations.xml b/features/invitepeople/impl/src/main/res/values-zh-rTW/translations.xml index c8117ec283..5197f7758c 100644 --- a/features/invitepeople/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/invitepeople/impl/src/main/res/values-zh-rTW/translations.xml @@ -2,4 +2,8 @@ "已是成員" "已邀請" + "您目前與這些聯絡人沒有任何聊天紀錄。請確認是否要邀請他們加入此聊天室,然後再繼續。" + "您目前與此聯絡人沒有任何聊天紀錄。請確認是否要邀請對方加入此聊天室,然後再繼續。" + "要邀請新聯絡人加入此聊天室嗎?" + "要邀請新聯絡人加入此聊天室嗎?" diff --git a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomFlowNode.kt b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomFlowNode.kt index 93f8f53412..493c180731 100644 --- a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomFlowNode.kt +++ b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomFlowNode.kt @@ -69,6 +69,9 @@ class JoinRoomFlowNode( parentNode = this, buildContext = buildContext, inviteData = navTarget.inviteData, + callback = object : DeclineInviteAndBlockEntryPoint.Callback { + override fun onDeclineSuccess() = navigateUp() + }, ) NavTarget.Root -> rootNode(buildContext) } @@ -99,7 +102,7 @@ class JoinRoomFlowNode( acceptDeclineInviteView.Render( state = state.acceptDeclineInviteState, onAcceptInviteSuccess = {}, - onDeclineInviteSuccess = {}, + onDeclineInviteSuccess = { navigateUp() }, modifier = Modifier ) } diff --git a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomStateProvider.kt b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomStatePreviewParam.kt similarity index 99% rename from features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomStateProvider.kt rename to features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomStatePreviewParam.kt index 4bfa741321..f47377b16b 100644 --- a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomStateProvider.kt +++ b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomStatePreviewParam.kt @@ -30,7 +30,7 @@ import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.ui.model.InviteSender import kotlinx.collections.immutable.toImmutableList -open class JoinRoomStateProvider : PreviewParameterProvider { +open class JoinRoomStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aJoinRoomState( diff --git a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomView.kt b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomView.kt index 977308178d..f1adf1705f 100644 --- a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomView.kt +++ b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/JoinRoomView.kt @@ -642,7 +642,7 @@ private fun JoinRoomTopBar( @PreviewsDayNight @Composable -internal fun JoinRoomViewPreview(@PreviewParameter(JoinRoomStateProvider::class) state: JoinRoomState) = ElementPreview { +internal fun JoinRoomViewPreview(@PreviewParameter(JoinRoomStatePreviewParam::class) state: JoinRoomState) = ElementPreview { JoinRoomView( state = state, onBackClick = { }, diff --git a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/di/JoinRoomModule.kt b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/di/JoinRoomBindingContainer.kt similarity index 98% rename from features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/di/JoinRoomModule.kt rename to features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/di/JoinRoomBindingContainer.kt index 3304169b1a..3ab9cbfa97 100644 --- a/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/di/JoinRoomModule.kt +++ b/features/joinroom/impl/src/main/kotlin/io/element/android/features/joinroom/impl/di/JoinRoomBindingContainer.kt @@ -27,7 +27,7 @@ import java.util.Optional @BindingContainer @ContributesTo(SessionScope::class) -object JoinRoomModule { +object JoinRoomBindingContainer { @Provides fun providesJoinRoomPresenterFactory( client: MatrixClient, diff --git a/features/joinroom/impl/src/main/res/values-ar/translations.xml b/features/joinroom/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..84a81ad6a5 --- /dev/null +++ b/features/joinroom/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,34 @@ + + + "لقد حظرك %1$s." + "تم حظرك" + "السبب: %1$s." + "إلغاء الطلب" + "نعم، ألغِ" + "هل أنت متأكد من رغبتك في إلغاء طلبك للانضمام إلى هذه الغرفة؟" + "إلغاء طلب الانضمام" + "نعم، ارفض واحظر" + "هل أنت متأكد من رغبتك في رفض الدعوة للانضمام إلى هذه الغرفة؟ سيمنع هذا أيضًا %1$s من التواصل معك أو دعوتك إلى غرف." + "رفض الدعوة والحظر" + "رفض وحظر" + "فشل الانضمام" + "إما أنك تحتاج إلى دعوة للانضمام، أو قد توجد قيود على الوصول." + "نسيان" + "تحتاج إلى دعوة للانضمام" + "بدعوة من" + "إنضمام" + "قد تحتاج إلى دعوة أو إلى أن تكون عضوًا في مساحة لتتمكن من الانضمام." + "إرسال طلب الانضمام" + "الأحرف المسموح بها: %1$d من %2$d" + "رسالة (اختيارية)" + "ستتلقى دعوة للانضمام إلى الغرفة إذا تم قبول طلبك." + "تم إرسال طلب الانضمام" + "تعذّر عرض معاينة الغرفة. قد يكون ذلك بسبب مشكلات في الشبكة أو الخادم." + "تعذّر عرض معاينة هذه الغرفة" + "لا يدعم %1$s المساحات بعد. يمكنك الوصول إلى المساحات عبر الويب." + "المساحات غير مدعومة بعد" + "انقر على الزر أدناه وسيتم إشعار مسؤول الغرفة. ستتمكن من الانضمام إلى المحادثة بعد الموافقة." + "يجب أن تكون عضوًا في هذه الغرفة لعرض سجل الرسائل." + "هل تريد الانضمام إلى هذه الغرفة؟" + "المعاينة غير متاحة" + diff --git a/features/joinroom/impl/src/main/res/values-es/translations.xml b/features/joinroom/impl/src/main/res/values-es/translations.xml index 698a6eb1c9..6773318776 100644 --- a/features/joinroom/impl/src/main/res/values-es/translations.xml +++ b/features/joinroom/impl/src/main/res/values-es/translations.xml @@ -1,7 +1,7 @@ - "Has sido baneado por %1$s." - "Has sido baneado." + "Has sido vetado por %1$s." + "Has sido vetado" "Motivo: %1$s." "Cancelar solicitud" "Sí, cancelar" @@ -15,9 +15,11 @@ "O es necesario estar invitado para unirse o puede haber restricciones de acceso." "Olvidar" "Necesitas una invitación para unirte" + "Te invitó" "Unirse" "Es posible que necesites ser invitado o ser miembro de un espacio para poder unirte." "Enviar solicitud de unión" + "%1$d de %2$d caracteres permitidos" "Mensaje (opcional)" "Recibirás una invitación para unirte a la sala si se acepta tu solicitud." "Solicitud de unión enviada" diff --git a/features/joinroom/impl/src/main/res/values-fa/translations.xml b/features/joinroom/impl/src/main/res/values-fa/translations.xml index 3f9fc99877..d5102b939f 100644 --- a/features/joinroom/impl/src/main/res/values-fa/translations.xml +++ b/features/joinroom/impl/src/main/res/values-fa/translations.xml @@ -1,23 +1,30 @@ - "به دست %1$s از این اتاق محروم شدید." - "از این اتاق محروم شدید" + "شما توسط %1$s مسدود شده‌اید." + "شما محروم شدید" "دلیل: %1$s." "لغو درخواست" "بله. لغو" + "آیا مطمئن هستید که می‌خواهید درخواست عضویت خود در این اتاق را لغو کنید؟" "لغو درخواست پیوستن" "بله. رد و انسداد" + "آیا مطمئنید که می‌خواهید دعوت به عضویت در این اتاق را رد کنید؟ این کار همچنین مانع از تماس %1$s با شما یا دعوت شما به اتاق‌ها می‌شود." "رد دعوت و انسداد" "رد و انسداد" "پیوستن شکست خورد" - "فراموشی این اتاق" - "برای پیوستن به این اتاق نیاز به دعوت دارید" + "یا باید دعوتنامه داشته باشید یا ممکن است محدودیت‌هایی برای دسترسی وجود داشته باشد." + "فراموش کردن" + "برای عضویت نیاز به دعوتنامه دارید" "دعوت شده از سوی" "پیوستن" "برای پیوستن به فضا باید دعوت شده باشید." "در زدن برای پیوستن" + "کاراکترهای مجاز %1$d از %2$d" "پیام (اختیاری)" + "در صورت پذیرش درخواست، دعوتنامه‌ای برای ورود به اتاق دریافت خواهید کرد." "درخواست پیوستن فرستاده شد" + "ما نتوانستیم پیش‌نمایش اتاق را نمایش دهیم. این ممکن است به دلیل مشکلات شبکه یا سرور باشد." + "ما نتوانستیم پیش‌نمایش این اتاق را نمایش دهیم" "%1$s هنوز از فضاها پشتیبانی نمی‌کند. می‌توانید روی وب به فضاها دسترسی داشته باشید." "فضاها هنوز پشتیبانی نمی‌شوند" "زدن روی این دکمه برای آگاه شدن مدیر اتاق. پس از تأیید می‌توانید به گفت‌وگو بپیوندید." diff --git a/features/knockrequests/api/src/main/kotlin/io/element/android/features/knockrequests/api/banner/KnockRequestsBannerRenderer.kt b/features/knockrequests/api/src/main/kotlin/io/element/android/features/knockrequests/api/banner/KnockRequestsBannerRenderer.kt index 34061db335..e6be68b95a 100644 --- a/features/knockrequests/api/src/main/kotlin/io/element/android/features/knockrequests/api/banner/KnockRequestsBannerRenderer.kt +++ b/features/knockrequests/api/src/main/kotlin/io/element/android/features/knockrequests/api/banner/KnockRequestsBannerRenderer.kt @@ -11,7 +11,16 @@ package io.element.android.features.knockrequests.api.banner import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +/** + * Renders the banner shown at the top of a room when people are waiting to join it. + */ interface KnockRequestsBannerRenderer { + /** + * Draws the banner, or nothing when there is no pending request or the user cannot moderate the room. + * + * @param modifier layout modifier for the container. + * @param onViewRequestsClick called when the user asks to see the full list of requests. + */ @Composable fun View(modifier: Modifier, onViewRequestsClick: () -> Unit) } diff --git a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerStateProvider.kt b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerStatePreviewParam.kt similarity index 96% rename from features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerStateProvider.kt rename to features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerStatePreviewParam.kt index 7210e783fe..fb05ae1fe0 100644 --- a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerStateProvider.kt +++ b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.designsystem.preview.USER_NAME_BOB import io.element.android.libraries.designsystem.preview.USER_NAME_CHARLIE import kotlinx.collections.immutable.toImmutableList -class KnockRequestsBannerStateProvider : PreviewParameterProvider { +class KnockRequestsBannerStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aKnockRequestsBannerState(), diff --git a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerView.kt b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerView.kt index 431bd14d10..037ec16d00 100644 --- a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerView.kt +++ b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/banner/KnockRequestsBannerView.kt @@ -227,7 +227,7 @@ private fun KnockRequestAvatarListView( @Composable @PreviewsDayNight -internal fun KnockRequestsBannerViewPreview(@PreviewParameter(KnockRequestsBannerStateProvider::class) state: KnockRequestsBannerState) = ElementPreview { +internal fun KnockRequestsBannerViewPreview(@PreviewParameter(KnockRequestsBannerStatePreviewParam::class) state: KnockRequestsBannerState) = ElementPreview { KnockRequestsBannerView( state = state, onViewRequestsClick = {}, diff --git a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/data/KnockRequestsModule.kt b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/data/di/KnockRequestsBindingContainer.kt similarity index 81% rename from features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/data/KnockRequestsModule.kt rename to features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/data/di/KnockRequestsBindingContainer.kt index 73e4a2ddeb..04d5400831 100644 --- a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/data/KnockRequestsModule.kt +++ b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/data/di/KnockRequestsBindingContainer.kt @@ -6,7 +6,7 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.features.knockrequests.impl.data +package io.element.android.features.knockrequests.impl.data.di import dev.zacsweers.metro.BindingContainer import dev.zacsweers.metro.ContributesTo @@ -14,16 +14,17 @@ import dev.zacsweers.metro.Provides import dev.zacsweers.metro.SingleIn import io.element.android.features.knockrequests.api.KnockRequestPermissions import io.element.android.features.knockrequests.api.knockRequestPermissions +import io.element.android.features.knockrequests.impl.data.KnockRequestsService import io.element.android.libraries.di.RoomScope import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.api.room.powerlevels.permissionsFlow @BindingContainer @ContributesTo(RoomScope::class) -object KnockRequestsModule { +object KnockRequestsBindingContainer { @Provides @SingleIn(RoomScope::class) - fun knockRequestsService(room: JoinedRoom): KnockRequestsService { + fun providesKnockRequestsService(room: JoinedRoom): KnockRequestsService { return KnockRequestsService( knockRequestsFlow = room.knockRequestsFlow, permissionsFlow = room.permissionsFlow(KnockRequestPermissions.DEFAULT) { perms -> diff --git a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListStateProvider.kt b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListStatePreviewParam.kt similarity index 98% rename from features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListStateProvider.kt rename to features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListStatePreviewParam.kt index 85fc0675ad..b51223a5e9 100644 --- a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListStateProvider.kt +++ b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListStatePreviewParam.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.matrix.api.core.UserId import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -open class KnockRequestsListStateProvider : PreviewParameterProvider { +open class KnockRequestsListStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aKnockRequestsListState( diff --git a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListView.kt b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListView.kt index db40596892..d750927f74 100644 --- a/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListView.kt +++ b/features/knockrequests/impl/src/main/kotlin/io/element/android/features/knockrequests/impl/list/KnockRequestsListView.kt @@ -491,7 +491,7 @@ private fun KnockRequestsListTopBar(onBackClick: () -> Unit) { @PreviewsDayNight @Composable internal fun KnockRequestsListViewPreview( - @PreviewParameter(KnockRequestsListStateProvider::class) state: KnockRequestsListState + @PreviewParameter(KnockRequestsListStatePreviewParam::class) state: KnockRequestsListState ) = ElementPreview { KnockRequestsListView( state = state, diff --git a/features/knockrequests/impl/src/main/res/values-ar/translations.xml b/features/knockrequests/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..4ff4995748 --- /dev/null +++ b/features/knockrequests/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,40 @@ + + + "نعم، قبول الكل" + "هل أنت متأكد من رغبتك في قبول جميع طلبات الانضمام؟" + "قبول جميع الطلبات" + "قبول الكل" + "تعذّر قبول جميع الطلبات. هل ترغب في المحاولة مرة أخرى؟" + "فشل قبول جميع الطلبات" + "جارٍ قبول جميع طلبات الانضمام" + "تعذّر قبول هذا الطلب. هل ترغب في المحاولة مرة أخرى؟" + "فشل قبول الطلب" + "جارٍ قبول طلب الانضمام" + "نعم، ارفض واحظر" + "هل أنت متأكد من رغبتك في رفض %1$s وحظره؟ لن يتمكن هذا المستخدم من طلب الوصول للانضمام إلى هذه الغرفة مرة أخرى." + "رفض الوصول والحظر" + "جارٍ رفض الوصول وحظره" + "نعم، ارفض" + "هل أنت متأكد من رغبتك في رفض طلب %1$s للانضمام إلى هذه الغرفة؟" + "رفض الوصول" + "رفض وحظر" + "تعذّر رفض هذا الطلب. هل ترغب في المحاولة مرة أخرى؟" + "فشل رفض الطلب" + "جارٍ رفض طلب الانضمام" + "عندما يطلب أحدهم الانضمام إلى الغرفة، ستتمكن من رؤية طلبه هنا." + "لا توجد طلبات انضمام معلّقة" + "جارٍ تحميل طلبات الانضمام…" + "طلبات الانضمام" + + "%1$s يريد الانضمام إلى هذه الغرفة" + "%1$s +%2$d آخر يريدان الانضمام إلى هذه الغرفة" + "%1$s +%2$d آخران يريدون الانضمام إلى هذه الغرفة" + "%1$s +%2$d آخرون يريدون الانضمام إلى هذه الغرفة" + "%1$s +%2$d آخرين يريدون الانضمام إلى هذه الغرفة" + "%1$s +%2$d آخرين يريدون الانضمام إلى هذه الغرفة" + + "عرض الكل" + "قبول" + "%1$s يريد الانضمام إلى هذه الغرفة" + "عرض" + diff --git a/features/knockrequests/impl/src/main/res/values-fa/translations.xml b/features/knockrequests/impl/src/main/res/values-fa/translations.xml index 5b931e4f00..af786de6de 100644 --- a/features/knockrequests/impl/src/main/res/values-fa/translations.xml +++ b/features/knockrequests/impl/src/main/res/values-fa/translations.xml @@ -1,21 +1,34 @@ "بله. پذیرش همه" + "آیا مطمئن هستید که می‌خواهید همه درخواست‌های عضویت را بپذیرید؟" "پذیرش همهٔ درخواست‌ها" "پذیرش همه" + "ما نتوانستیم همه درخواست‌ها را بپذیریم. آیا مایلید دوباره امتحان کنید؟" "شکست در پذیرش همهٔ درخواست‌ها" "پذیرفتن همهٔ درخواست‌های پیوستن" + "ما نتوانستیم این درخواست را بپذیریم. آیا مایلید دوباره امتحان کنید؟" "شکست در پذیرش درخواست" "پذیرفتن درخواست پیوستن" "بله. رد و انسداد" + "آیا مطمئن هستید که می‌خواهید %1$s را رد و مسدود کنید؟ این کاربر دیگر نمی‌تواند درخواست دسترسی برای پیوستن به این اتاق را بدهد." "رد و تحریم دسترسی" "رد کردن و تحریم دسترسی" "بله. رد شود" + "آیا مطمئن هستید که می‌خواهید درخواست %1$s برای پیوستن به این اتاق را رد کنید؟" "رد کردن دسترسی" "رد و تحریم" + "ما نمی‌توانستیم این درخواست را رد کنیم. آیا مایلید دوباره امتحان کنید؟" "شکتس در رد درخواست" "در کردن درخواست پیوستن" + "وقتی کسی درخواست عضویت در اتاق را می‌دهد، می‌توانید درخواست او را اینجا ببینید." + "درخواست عضویت در حال بررسی نیست" + "در حال بارگیری درخواست‌های عضویت…" "درخواست‌های پیوستن" + + "%1$s +%2$d افراد دیگری هم می‌خواهند به این اتاق بپیوندند" + "%1$s +%2$d دیگران می‌خواهند به این اتاق بپیوندند" + "دیدن همه" "پذیرش" "%1$s می‌خواهد به این اتاق بپیوندد" diff --git a/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomEvent.kt b/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomEvent.kt index 6d228ee887..f0c3eaf7bf 100644 --- a/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomEvent.kt +++ b/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomEvent.kt @@ -10,6 +10,9 @@ package io.element.android.features.leaveroom.api import io.element.android.libraries.matrix.api.core.RoomId +/** + * Events sent to the leave room presenter through [LeaveRoomState.eventSink]. + */ interface LeaveRoomEvent { data class LeaveRoom(val roomId: RoomId, val needsConfirmation: Boolean) : LeaveRoomEvent } diff --git a/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomRenderer.kt b/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomRenderer.kt index 852193d874..8472e098ec 100644 --- a/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomRenderer.kt +++ b/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomRenderer.kt @@ -12,7 +12,17 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import io.element.android.libraries.matrix.api.core.RoomId +/** + * Renders the confirmation dialogs of the leave room flow; it draws nothing until the host screen sends a leave event. + */ fun interface LeaveRoomRenderer { + /** + * Draws whichever dialog the current state calls for. + * + * @param state the state produced by the leave room presenter. + * @param onSelectNewOwners called when the user is the last owner of a room that still has other members, and must promote someone before leaving. + * @param modifier layout modifier for the container. + */ @Composable fun Render( state: LeaveRoomState, diff --git a/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomState.kt b/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomState.kt index 92a5916858..b9150b59f0 100644 --- a/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomState.kt +++ b/features/leaveroom/api/src/main/kotlin/io/element/android/features/leaveroom/api/LeaveRoomState.kt @@ -10,7 +10,11 @@ package io.element.android.features.leaveroom.api import androidx.compose.runtime.Immutable +/** + * State of the leave room flow, which is only the confirmation dialogs: the screen it is hosted in owns the rest of the UI. + */ @Immutable interface LeaveRoomState { + /** Where the host screen sends its events to start or confirm leaving a room. */ val eventSink: (LeaveRoomEvent) -> Unit } diff --git a/features/leaveroom/api/src/main/res/values-ar/translations.xml b/features/leaveroom/api/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..9253cb5365 --- /dev/null +++ b/features/leaveroom/api/src/main/res/values-ar/translations.xml @@ -0,0 +1,10 @@ + + + "هل أنت متأكد من رغبتك في مغادرة هذه المحادثة؟ هذه المحادثة ليست عامة ولن تتمكن من الانضمام إليها مرة أخرى دون دعوة." + "أأنت متأكد من رغبتك بخروج الغرفة؟ أنت الشخص الوحيد هنا. وإذا ما غادرت فلن يعود أحد قادراً على الدخول في المستقبل، بما فيهم أنت." + "أأنت متأكد من رغبتك بخروج الغرفة؟ هذه الغرفة ليست عامة ولن تعود قادراً على الدخول مجدداً بلا دعوة" + "اختيار المالكين" + "أنت المالك الوحيد لهذه الغرفة. يجب أن تنقل الملكية إلى شخص آخر قبل مغادرة الغرفة." + "نقل الملكية" + "أأنت متأكد من رغبتك بخروج الغرفة؟" + diff --git a/features/leaveroom/api/src/main/res/values-es/translations.xml b/features/leaveroom/api/src/main/res/values-es/translations.xml index 81b169e5c9..59457c8dad 100644 --- a/features/leaveroom/api/src/main/res/values-es/translations.xml +++ b/features/leaveroom/api/src/main/res/values-es/translations.xml @@ -3,5 +3,8 @@ "¿Estás seguro de que quieres salir de esta conversación? Esta conversación no es pública y no podrás volver a unirte sin una invitación." "¿Estás seguro de que quieres salir de esta sala? Eres la única persona aquí. Si te vas, nadie podrá unirse en el futuro, ni siquiera tú." "¿Seguro que quieres salir de esta sala? Esta sala no es pública y no podrás volver a entrar sin una invitación." + "Elegir propietarios" + "Eres el único propietario de esta sala. Debes transferir la propiedad a otra persona antes de salir de la sala." + "Transferir la propiedad" "¿Seguro que quieres salir de la sala?" diff --git a/features/leaveroom/api/src/main/res/values-fa/translations.xml b/features/leaveroom/api/src/main/res/values-fa/translations.xml index ec2cd89314..6391a70210 100644 --- a/features/leaveroom/api/src/main/res/values-fa/translations.xml +++ b/features/leaveroom/api/src/main/res/values-fa/translations.xml @@ -4,6 +4,7 @@ "مطمئنید که می‌خواهید این اتاق را ترک کنید؟ تنها فرد این‌جا هستید. در صورت ترک، هیچ‌کسی از جمله خودتان در آینده نخواهد توانست به آن بپیوندد." "مطمئنید که می‌خواهید این اتاق را ترک کنید؟ این اتاق عمومی نبوده قادر نخواهید بود بدون دعوت دوباره بپیوندید." "گزینش مالکان" + "شما تنها مالک این اتاق هستید. قبل از ترک اتاق، باید مالکیت را به شخص دیگری منتقل کنید." "انتقال مالکیت" "مطمئنید که می‌خواهید این اتاق را ترک کنید؟" diff --git a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/InternalLeaveRoomStateProvider.kt b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/InternalLeaveRoomStatePreviewParam.kt similarity index 94% rename from features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/InternalLeaveRoomStateProvider.kt rename to features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/InternalLeaveRoomStatePreviewParam.kt index 769015f301..5f68a6f192 100644 --- a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/InternalLeaveRoomStateProvider.kt +++ b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/InternalLeaveRoomStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.features.leaveroom.api.LeaveRoomEvent import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.core.RoomId -class InternalLeaveRoomStateProvider : PreviewParameterProvider { +class InternalLeaveRoomStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLeaveRoomState(), diff --git a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomPresenter.kt b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomPresenter.kt index d11dc7e7e8..e2065bca1f 100644 --- a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomPresenter.kt +++ b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomPresenter.kt @@ -60,7 +60,13 @@ class LeaveRoomPresenter( roomId: RoomId, leaveAction: MutableState>, ) = launch(dispatchers.io) { - client.getRoom(roomId)?.use { room -> + val room = client.getRoom(roomId) + if (room == null) { + Timber.e("Unable to find room $roomId to leave it") + leaveAction.value = AsyncAction.Failure(RoomNotFoundException(roomId)) + return@launch + } + room.use { val roomInfo = room.roomInfoFlow.first() leaveAction.value = when { roomInfo.isDm -> Confirmation.Dm(roomId) @@ -78,7 +84,8 @@ class LeaveRoomPresenter( leaveAction: MutableState>, ) = launch(dispatchers.io) { leaveAction.runCatchingUpdatingState { - client.getRoom(roomId)!!.use { room -> + val room = client.getRoom(roomId) ?: throw RoomNotFoundException(roomId) + room.use { room .leave() .onSuccess { notificationConversationService.onLeftRoom(client.sessionId, roomId) } @@ -100,3 +107,5 @@ class LeaveRoomPresenter( } } } + +internal class RoomNotFoundException(roomId: RoomId) : IllegalStateException("Room $roomId not found") diff --git a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomView.kt b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomView.kt index 131801b014..c3a916b141 100644 --- a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomView.kt +++ b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/LeaveRoomView.kt @@ -139,7 +139,7 @@ private fun LeaveRoomProgressDialog(modifier: Modifier = Modifier) { @PreviewsDayNight @Composable internal fun LeaveRoomViewPreview( - @PreviewParameter(InternalLeaveRoomStateProvider::class) state: InternalLeaveRoomState + @PreviewParameter(InternalLeaveRoomStatePreviewParam::class) state: InternalLeaveRoomState ) = ElementPreview { Box( modifier = Modifier.size(300.dp, 300.dp), diff --git a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/di/LeaveRoomModule.kt b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/di/LeaveRoomBindingContainer.kt similarity index 95% rename from features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/di/LeaveRoomModule.kt rename to features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/di/LeaveRoomBindingContainer.kt index db5b1416ee..866af68cc8 100644 --- a/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/di/LeaveRoomModule.kt +++ b/features/leaveroom/impl/src/main/kotlin/io/element/android/features/leaveroom/impl/di/LeaveRoomBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.di.SessionScope @ContributesTo(SessionScope::class) @BindingContainer -interface LeaveRoomModule { +interface LeaveRoomBindingContainer { @Binds fun bindLeaveRoomPresenter(presenter: LeaveRoomPresenter): Presenter } diff --git a/features/leaveroom/impl/src/test/kotlin/io/element/android/features/leaveroom/impl/LeaveBaseRoomPresenterTest.kt b/features/leaveroom/impl/src/test/kotlin/io/element/android/features/leaveroom/impl/LeaveBaseRoomPresenterTest.kt index 90b7f2369f..f8f7a771e1 100644 --- a/features/leaveroom/impl/src/test/kotlin/io/element/android/features/leaveroom/impl/LeaveBaseRoomPresenterTest.kt +++ b/features/leaveroom/impl/src/test/kotlin/io/element/android/features/leaveroom/impl/LeaveBaseRoomPresenterTest.kt @@ -175,6 +175,32 @@ class LeaveBaseRoomPresenterTest { } } + @Test + fun `present - show error if the room to confirm leaving is not found`() = runTest { + val presenter = createLeaveRoomPresenter(client = FakeMatrixClient()) + presenter.stateFlow().test { + val initialState = awaitItem() + initialState.eventSink(LeaveRoomEvent.LeaveRoom(A_ROOM_ID, needsConfirmation = true)) + val errorState = awaitItem() + assertThat(errorState.leaveAction).isInstanceOf(AsyncAction.Failure::class.java) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - show error if the room to leave is not found`() = runTest { + val presenter = createLeaveRoomPresenter(client = FakeMatrixClient()) + presenter.stateFlow().test { + val initialState = awaitItem() + initialState.eventSink(LeaveRoomEvent.LeaveRoom(A_ROOM_ID, needsConfirmation = false)) + val progressState = awaitItem() + assertThat(progressState.leaveAction).isEqualTo(AsyncAction.Loading) + val errorState = awaitItem() + assertThat(errorState.leaveAction).isInstanceOf(AsyncAction.Failure::class.java) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `present - reset state after error`() = runTest { val presenter = createLeaveRoomPresenter( diff --git a/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListStateProvider.kt b/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListStatePreviewParam.kt similarity index 95% rename from features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListStateProvider.kt rename to features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListStatePreviewParam.kt index 6a74cc01eb..b984c43398 100644 --- a/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListStateProvider.kt +++ b/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.architecture.AsyncData import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -open class DependencyLicensesListStateProvider : PreviewParameterProvider { +open class DependencyLicensesListStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDependencyLicensesListState( diff --git a/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListView.kt b/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListView.kt index 943f57ab3b..17f82cd14e 100644 --- a/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListView.kt +++ b/features/licenses/impl/src/main/kotlin/io/element/android/features/licenses/impl/list/DependencyLicensesListView.kt @@ -126,7 +126,7 @@ fun DependencyLicensesListView( @PreviewsDayNight @Composable internal fun DependencyLicensesListViewPreview( - @PreviewParameter(DependencyLicensesListStateProvider::class) state: DependencyLicensesListState + @PreviewParameter(DependencyLicensesListStatePreviewParam::class) state: DependencyLicensesListState ) = ElementPreview { DependencyLicensesListView( state = state, diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDesktopHandler.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDesktopHandler.kt index a8a8ff14b6..bff81a3e9e 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDesktopHandler.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDesktopHandler.kt @@ -12,10 +12,12 @@ import dev.zacsweers.metro.SingleIn import io.element.android.libraries.core.log.logger.LoggerTag import io.element.android.libraries.di.SessionScope import io.element.android.libraries.matrix.api.MatrixClient +import io.element.android.libraries.matrix.api.linknewdevice.ErrorType import io.element.android.libraries.matrix.api.linknewdevice.LinkDesktopHandler import io.element.android.libraries.matrix.api.linknewdevice.LinkDesktopStep import io.element.android.libraries.matrix.api.logs.LoggerTags import kotlinx.coroutines.Job +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -23,6 +25,7 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import timber.log.Timber +import kotlin.time.Duration.Companion.minutes private val loggerTag = LoggerTag("LinkNewDesktopHandler", LoggerTags.linkNewDevice) @@ -36,29 +39,64 @@ class LinkNewDesktopHandler( LinkDesktopStep.Uninitialized ) + /** + * A [StateFlow] that emits the current step of the link desktop process. + * It starts with [LinkDesktopStep.Uninitialized] and will emit other steps as they occur. + */ val stepFlow: StateFlow get() = linkDesktopStepFlow.asStateFlow() private var currentJob: Job? = null + private var timerJob: Job? = null private var handler: LinkDesktopHandler? = null + private fun resetJobs() { + currentJob?.cancel() + currentJob = null + timerJob?.cancel() + timerJob = null + } + + /** + * Starts (or restarts) a timer that will emit an error in [stepFlow] after 2 minutes. + */ + fun startTimer() { + timerJob?.cancel() + timerJob = sessionScope.launch { + delay(2.minutes) + linkDesktopStepFlow.emit(LinkDesktopStep.Error(ErrorType.Expired("Scanning QrCode took too long."))) + } + } + + /** + * Creates a new [LinkDesktopHandler] and cancels any existing job. + * This should be called when the user wants to retry scanning a QR code. + */ fun createNewHandler() { currentJob?.cancel() currentJob = null handler = matrixClient.createLinkDesktopHandler().getOrNull() } + /** + * Resets the state of the handler and cancels any existing job. + * This should be called when the user wants to start over. + */ fun reset() { - currentJob?.cancel() - currentJob = null + resetJobs() sessionScope.launch { linkDesktopStepFlow.emit(LinkDesktopStep.Uninitialized) } } + /** + * Handles the scanned QR code data. + * This should be called when the user scans a QR code. + * + * @param data The scanned QR code data as a byte array. + */ fun onScannedCode(data: ByteArray) { - currentJob?.cancel() - currentJob = null + resetJobs() val currentHandler = handler if (currentHandler == null) { Timber.tag(loggerTag.value).e("onScannedCode: Handler is not initialized. Call createNewHandler() first.") diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDeviceFlowNode.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDeviceFlowNode.kt index d686b22860..b31aca8cb2 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDeviceFlowNode.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewDeviceFlowNode.kt @@ -56,6 +56,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch import kotlinx.parcelize.Parcelize import timber.log.Timber @@ -102,6 +103,7 @@ class LinkNewDeviceFlowNode( @Suppress("AssignedValueIsNeverRead") linkDesktopHandlerJob = observeLinkNewDesktopHandler() }, + onResume = ::onResume, onDestroy = { linkMobileHandlerJob?.cancel() linkDesktopHandlerJob?.cancel() @@ -209,6 +211,18 @@ class LinkNewDeviceFlowNode( .launchIn(sessionCoroutineScope) } + private fun onResume() = sessionCoroutineScope.launch { + // Application is resumed, if the step is waiting for auth, send the confirmation + (linkNewMobileHandler.stepFlow.value as? LinkMobileStep.WaitingForAuth)?.let { + Timber.tag(tag.value).d("Resuming while waiting for auth on mobile, sending confirmation") + it.continuationMessageSender.confirm() + } + (linkNewDesktopHandler.stepFlow.value as? LinkDesktopStep.WaitingForAuth)?.let { + Timber.tag(tag.value).d("Resuming while waiting for auth on desktop, sending confirmation") + it.continuationMessageSender.confirm() + } + } + private fun navigateToError(errorType: ErrorType) { // Map the error to an error screen val error = when (errorType) { @@ -249,6 +263,8 @@ class LinkNewDeviceFlowNode( } LinkDeviceType.Desktop -> { linkNewDesktopHandler.reset() + // Ensure unlock state does not last longer than the timeout for scanning the QR code, so start the timer after unlock + linkNewDesktopHandler.startTimer() backstack.push(NavTarget.DesktopNotice) } } @@ -264,10 +280,14 @@ class LinkNewDeviceFlowNode( NavTarget.DesktopNotice -> { val callback = object : DesktopNoticeNode.Callback { override fun navigateBack() { + // Stop the timer when the user leaves the screen (user will have to authenticate again) + linkNewDesktopHandler.reset() backstack.pop() } override fun navigateToQrCodeScanner() { + // Start again the timer when the user enters the next screen (they clicked on "Ready to scan") + linkNewDesktopHandler.startTimer() backstack.push(NavTarget.DesktopScanQrCode) } } @@ -276,6 +296,8 @@ class LinkNewDeviceFlowNode( NavTarget.DesktopScanQrCode -> { val callback = object : ScanQrCodeNode.Callback { override fun cancel() { + // start again the timer when the user goes back to the DesktopNoticeNode + linkNewDesktopHandler.startTimer() backstack.pop() } } diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewMobileHandler.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewMobileHandler.kt index 39c9c6fef3..9436c0e901 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewMobileHandler.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/LinkNewMobileHandler.kt @@ -40,9 +40,19 @@ class LinkNewMobileHandler( LinkMobileStep.Uninitialized ) + /** + * A [StateFlow] that emits the current step of the link mobile process. + * It starts with [LinkMobileStep.Uninitialized] and will emit other steps as they occur. + */ val stepFlow: StateFlow get() = linkMobileStepFlow.asStateFlow() + /** + * Creates a new [LinkMobileHandler] and starts the linking process. + * If [forRotating] is true, it indicates that this is a rotation of the QR code. + * + * @param forRotating Whether this is a rotation of the QR code. Defaults to false. + */ fun createAndStartNewHandler(forRotating: Boolean = false) { Timber.tag(loggerTag.value).d("createAndStartNewHandler()") currentJob?.cancel() @@ -62,6 +72,10 @@ class LinkNewMobileHandler( } } + /** + * Resets the handler and cancels any ongoing job. + * This will also emit [LinkMobileStep.Uninitialized] to the [stepFlow]. + */ fun reset() { currentJob?.cancel() currentJob = null @@ -70,10 +84,18 @@ class LinkNewMobileHandler( } } + /** + * Rotates the QR code by creating a new handler and starting the linking process. + * This is typically called when a timeout occurs for the current QR code. + */ fun rotateQrCode() { createAndStartNewHandler(forRotating = true) } + /** + * Handles the case where there are too many QR code rotations. + * This will reset the handler and emit an error to the [stepFlow]. + */ fun onTooManyRotation() { reset() sessionScope.launch { diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeStateProvider.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeStatePreviewParam.kt similarity index 92% rename from features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeStateProvider.kt rename to features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeStatePreviewParam.kt index 194bd6fafc..c539563fc7 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeStateProvider.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeStatePreviewParam.kt @@ -13,7 +13,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.permissions.api.PermissionsState import io.element.android.libraries.permissions.api.aPermissionsState -open class DesktopNoticeStateProvider : PreviewParameterProvider { +open class DesktopNoticeStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDesktopNoticeState(), diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeView.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeView.kt index a66ea7b391..935c848e42 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeView.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/desktop/DesktopNoticeView.kt @@ -118,7 +118,7 @@ fun DesktopNoticeView( @PreviewsDayNight @Composable internal fun DesktopNoticeViewPreview( - @PreviewParameter(DesktopNoticeStateProvider::class) state: DesktopNoticeState, + @PreviewParameter(DesktopNoticeStatePreviewParam::class) state: DesktopNoticeState, ) = ElementPreview { DesktopNoticeView( state = state, diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorScreenTypeProvider.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorScreenTypePreviewParam.kt similarity index 90% rename from features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorScreenTypeProvider.kt rename to features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorScreenTypePreviewParam.kt index 5946eb9ab2..bfaf511e66 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorScreenTypeProvider.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorScreenTypePreviewParam.kt @@ -9,7 +9,7 @@ package io.element.android.features.linknewdevice.impl.screens.error import androidx.compose.ui.tooling.preview.PreviewParameterProvider -class ErrorScreenTypeProvider : PreviewParameterProvider { +class ErrorScreenTypePreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( ErrorScreenType.Cancelled, ErrorScreenType.Declined, diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorView.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorView.kt index 7b830626f6..90e9c4616b 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorView.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/error/ErrorView.kt @@ -165,7 +165,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable -internal fun ErrorViewPreview(@PreviewParameter(ErrorScreenTypeProvider::class) errorScreenType: ErrorScreenType) { +internal fun ErrorViewPreview(@PreviewParameter(ErrorScreenTypePreviewParam::class) errorScreenType: ErrorScreenType) { ElementPreview { ErrorView( errorScreenType = errorScreenType, diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberStateProvider.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberStatePreviewParam.kt similarity index 93% rename from features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberStateProvider.kt rename to features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberStatePreviewParam.kt index 126bfeee52..56071f3e8f 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberStateProvider.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberStatePreviewParam.kt @@ -11,7 +11,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.linknewdevice.ErrorType -open class EnterNumberStateProvider : PreviewParameterProvider { +open class EnterNumberStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aEnterNumberState(), diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberView.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberView.kt index 240a3143af..b60fd285af 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberView.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/number/EnterNumberView.kt @@ -117,7 +117,7 @@ fun EnterNumberView( @PreviewsDayNight @Composable internal fun EnterNumberViewPreview( - @PreviewParameter(EnterNumberStateProvider::class) state: EnterNumberState, + @PreviewParameter(EnterNumberStatePreviewParam::class) state: EnterNumberState, ) = ElementPreview { EnterNumberView( state = state, diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeNode.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeNode.kt index 20bd50f488..5110f8938f 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeNode.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeNode.kt @@ -20,6 +20,13 @@ import io.element.android.libraries.architecture.callback import io.element.android.libraries.architecture.inputs import io.element.android.libraries.di.SessionScope +/** + * Max number of QrCode rotation. + * When QrCode is rotated this number of time, a TimeOut error is emitted. + * Set to 0 to disable QrCode rotation. + */ +private const val MAX_QR_CODE_ROTATION = 0 + @ContributesNode(SessionScope::class) @AssistedInject class ShowQrCodeNode( @@ -39,6 +46,7 @@ class ShowQrCodeNode( private val callback: Callback = callback() private val showQrCodePresenter: ShowQrCodePresenter = showQrCodePresenterFactory.create( initialData = inputs.data, + maxQrCodeRotation = MAX_QR_CODE_ROTATION, ) @Composable diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenter.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenter.kt index 21071a6831..1a5eac0522 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenter.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenter.kt @@ -26,24 +26,29 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import timber.log.Timber +import kotlin.time.Duration.Companion.seconds private val tag = LoggerTag("ShowQrCodePresenter", LoggerTags.linkNewDevice) @AssistedInject class ShowQrCodePresenter( @Assisted private val initialData: String, + @Assisted private val maxQrCodeRotation: Int, private val linkNewMobileHandler: LinkNewMobileHandler, ) : Presenter { @AssistedFactory interface Factory { - fun create(initialData: String): ShowQrCodePresenter + fun create( + initialData: String, + maxQrCodeRotation: Int, + ): ShowQrCodePresenter } private var loadingJob: Job? = null @Composable override fun present(): ShowQrCodeState { - var qrCodeRotationCounter by remember { mutableIntStateOf(MAX_QR_CODE_ROTATION) } + var qrCodeRotationCounter by remember { mutableIntStateOf(maxQrCodeRotation) } val state by produceState( initialValue = ShowQrCodeState( data = AsyncData.Success(initialData), @@ -63,7 +68,7 @@ class ShowQrCodePresenter( linkNewMobileHandler.rotateQrCode() // Ensure that outdated data is not rendered too long while rotating QR code loadingJob = launch { - delay(1000) + delay(1.seconds) value = ShowQrCodeState( data = AsyncData.Loading(), ) @@ -80,8 +85,4 @@ class ShowQrCodePresenter( return state } - - companion object { - const val MAX_QR_CODE_ROTATION = 10 - } } diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeStateProvider.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeStatePreviewParam.kt similarity index 90% rename from features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeStateProvider.kt rename to features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeStatePreviewParam.kt index e6d33c2544..bc424746ae 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeStateProvider.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.linknewdevice.impl.screens.qrcode import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncData -class ShowQrCodeStateProvider : PreviewParameterProvider { +class ShowQrCodeStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aShowQrCodeState(), diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeView.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeView.kt index f2cd07f4a5..4cd22e37d2 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeView.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodeView.kt @@ -117,7 +117,7 @@ private fun QrCodeOrLoading( @PreviewsDayNight @Composable internal fun ShowQrCodeViewPreview( - @PreviewParameter(ShowQrCodeStateProvider::class) state: ShowQrCodeState, + @PreviewParameter(ShowQrCodeStatePreviewParam::class) state: ShowQrCodeState, ) = ElementPreview { ShowQrCodeView( state = state, diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootStateProvider.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootStatePreviewParam.kt similarity index 94% rename from features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootStateProvider.kt rename to features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootStatePreviewParam.kt index f1bb7ad455..20721e4a85 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootStateProvider.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootStatePreviewParam.kt @@ -11,7 +11,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.linknewdevice.ErrorType -open class LinkNewDeviceRootStateProvider : PreviewParameterProvider { +open class LinkNewDeviceRootStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLinkNewDeviceRootState(), diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootView.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootView.kt index 5778abfb2c..b27cce17d9 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootView.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/root/LinkNewDeviceRootView.kt @@ -140,7 +140,7 @@ fun LinkNewDeviceRootView( @PreviewsDayNight @Composable internal fun LinkNewDeviceRootViewPreview( - @PreviewParameter(LinkNewDeviceRootStateProvider::class) state: LinkNewDeviceRootState + @PreviewParameter(LinkNewDeviceRootStatePreviewParam::class) state: LinkNewDeviceRootState ) = ElementPreview { LinkNewDeviceRootView( state = state, diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeStateProvider.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeStatePreviewParam.kt similarity index 91% rename from features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeStateProvider.kt rename to features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeStatePreviewParam.kt index 40e7df8884..a088bf7bd3 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeStateProvider.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.linknewdevice.impl.screens.scan import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class ScanQrCodeStateProvider : PreviewParameterProvider { +open class ScanQrCodeStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aScanQrCodeState(), diff --git a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeView.kt b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeView.kt index 937aee08b4..4cd30fd904 100644 --- a/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeView.kt +++ b/features/linknewdevice/impl/src/main/kotlin/io/element/android/features/linknewdevice/impl/screens/scan/ScanQrCodeView.kt @@ -166,7 +166,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable -internal fun ScanQrCodeViewPreview(@PreviewParameter(ScanQrCodeStateProvider::class) state: ScanQrCodeState) = ElementPreview { +internal fun ScanQrCodeViewPreview(@PreviewParameter(ScanQrCodeStatePreviewParam::class) state: ScanQrCodeState) = ElementPreview { ScanQrCodeView( state = state, onBackClick = {}, diff --git a/features/linknewdevice/impl/src/main/res/values-ar/translations.xml b/features/linknewdevice/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..895a0e7efe --- /dev/null +++ b/features/linknewdevice/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,60 @@ + + + "امسح رمز QR ضوئيًا" + "افتح %1$s على كمبيوتر محمول أو مكتبي" + "امسح رمز QR ضوئيًا باستخدام هذا الجهاز" + "جاهز للمسح الضوئي" + "افتح %1$s على كمبيوتر مكتبي للحصول على رمز QR" + "الأرقام غير متطابقة" + "أدخل الرمز المكوّن من رقمين" + "سيؤكد هذا أن الاتصال بجهازك الآخر آمن." + "أدخل الرقم المعروض على جهازك الآخر" + "لا يدعم موفّر حسابك %1$s." + "%1$s غير مدعوم" + "لا يدعم موفّر حسابك تسجيل الدخول إلى جهاز جديد باستخدام رمز QR." + "رمز QR غير مدعوم" + "تم إلغاء تسجيل الدخول على الجهاز الآخر." + "تم إلغاء طلب تسجيل الدخول" + "انتهت صلاحية تسجيل الدخول. يرجى المحاولة مرة أخرى." + "لم يكتمل تسجيل الدخول في الوقت المحدد" + "افتح %1$s على الجهاز الآخر" + "اختر %1$s" + "«تسجيل الدخول باستخدام رمز QR»" + "امسح رمز QR المعروض هنا باستخدام الجهاز الآخر" + "افتح %1$s على الجهاز الآخر" + "كمبيوتر مكتبي" + "جارٍ تحميل رمز QR…" + "جهاز محمول" + "ما نوع الجهاز الذي تريد ربطه؟" + "يرجى المحاولة مرة أخرى والتأكد من إدخال الرمز المكوّن من رقمين بشكل صحيح. إذا ظلت الأرقام غير متطابقة، فتواصل مع موفّر حسابك." + "الأرقام غير متطابقة" + "تعذّر إنشاء اتصال آمن بالجهاز الجديد. لا تزال أجهزتك الحالية آمنة ولا داعي للقلق بشأنها." + "ماذا الآن؟" + "حاول تسجيل الدخول مجددًا باستخدام رمز QR إذا كانت هذه مشكلة في الشبكة." + "إذا واجهت المشكلة نفسها، جرّب شبكة Wi-Fi مختلفة أو استخدم بيانات الهاتف المحمول بدلًا من Wi-Fi." + "إذا لم ينجح ذلك، سجّل الدخول يدويًا" + "الاتصال غير آمن" + "سيُطلب منك إدخال الرقمين الظاهرين على هذا الجهاز." + "أدخل الرقم أدناه على جهازك الآخر" + "تم إلغاء تسجيل الدخول على الجهاز الآخر." + "تم إلغاء طلب تسجيل الدخول" + "تم رفض تسجيل الدخول على الجهاز الآخر." + "تم رفض تسجيل الدخول" + "لست بحاجة إلى فعل أي شيء آخر." + "جهازك الآخر مسجّل الدخول بالفعل" + "انتهت صلاحية تسجيل الدخول. يرجى المحاولة مرة أخرى." + "لم يكتمل تسجيل الدخول في الوقت المحدد" + "جهازك الآخر لا يدعم تسجيل الدخول إلى %s باستخدام رمز QR. + +جرّب تسجيل الدخول يدويًا، أو امسح رمز QR ضوئيًا باستخدام جهاز آخر." + "رمز QR غير مدعوم" + "لا يدعم موفّر حسابك %1$s." + "%1$s غير مدعوم" + "استخدم رمز QR المعروض على الجهاز الآخر." + "حاول مرة أخرى" + "رمز QR غير صحيح" + "تحتاج إلى منح %1$s إذنًا لاستخدام كاميرا جهازك للمتابعة." + "اسمح بالوصول إلى الكاميرا لمسح رمز QR ضوئيًا" + "حدث خطأ غير متوقع. يرجى المحاولة مرة أخرى." + "في انتظار جهازك الآخر" + diff --git a/features/linknewdevice/impl/src/main/res/values-es/translations.xml b/features/linknewdevice/impl/src/main/res/values-es/translations.xml index c33dc3ad88..5593f4bfd6 100644 --- a/features/linknewdevice/impl/src/main/res/values-es/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-es/translations.xml @@ -1,16 +1,34 @@ "Escanea el código QR" + "Abre %1$s en un ordenador" "Escanea el código QR con este dispositivo" "Listo para escanear" + "Abre %1$s en un ordenador para obtener el código QR" + "Solo escanea un código QR después de haber seguido los pasos anteriores en tu propio dispositivo. Nunca escanees un código que te haya enviado otra persona." + "Los números no coinciden" + "Introduce el código de 2 dígitos" + "Esto verificará que la conexión con tu otro dispositivo sea segura." + "Introduce el número que aparece en tu otro dispositivo" "Tu proveedor de cuentas no es compatible con %1$s." "%1$s no admitido" + "El proveedor de tu cuenta no admite el inicio de sesión en un nuevo dispositivo con un código QR." "Código QR no admitido" "El inicio de sesión se canceló en el otro dispositivo." "Solicitud de inicio de sesión cancelada" "El inicio de sesión ha caducado. Inténtalo de nuevo." "El inicio de sesión no se completó a tiempo" + "Abre %1$s en el otro dispositivo" "Selecciona %1$s" + "«Iniciar sesión con un código QR»" + "Escanea el código QR que se muestra aquí con el otro dispositivo" + "Abre %1$s en el otro dispositivo" + "Ordenador" + "Cargando código QR…" + "Dispositivo móvil" + "¿Qué tipo de dispositivo quieres vincular?" + "Inténtalo de nuevo y asegúrate de haber introducido correctamente el código de 2 dígitos. Si los números siguen sin coincidir, ponte en contacto con el proveedor de tu cuenta." + "Los números no coinciden" "No se pudo establecer una conexión segura con el nuevo dispositivo. Tus dispositivos actuales siguen siendo seguros y no tienes que preocuparte por ellos." "¿Y ahora qué?" "Intenta iniciar sesión de nuevo con un código QR en caso de que se trate de un problema de red" @@ -23,6 +41,8 @@ "Solicitud de inicio de sesión cancelada" "El inicio de sesión se rechazó en el otro dispositivo." "Inicio de sesión rechazado" + "No tienes que hacer nada más." + "Tu otro dispositivo ya está conectado" "El inicio de sesión ha caducado. Inténtalo de nuevo." "El inicio de sesión no se completó a tiempo" "Tu otro dispositivo no admite el inicio de sesión en %s con un código QR. diff --git a/features/linknewdevice/impl/src/main/res/values-et/translations.xml b/features/linknewdevice/impl/src/main/res/values-et/translations.xml index 10f8af5e11..95f9f5f586 100644 --- a/features/linknewdevice/impl/src/main/res/values-et/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-et/translations.xml @@ -5,6 +5,7 @@ "Skaneeri QR-koodi selle seadmega" "Skaneerimiseks valmis" "QR-koodi laadimiseks ava %1$s süle- või lauaarvutis" + "Skaneeri QR-koodi peale järgnevate sammude läbitegemist oma seadmes. Ära iialgi skaneeri QR-koodi, mille on saatnud keegi teine." "Numbrid ei klapi" "Sisesta kahekohaline kood" "Sellega verifitseerime, et ühendus sinu teise seadmega on turvaline." diff --git a/features/linknewdevice/impl/src/main/res/values-fa/translations.xml b/features/linknewdevice/impl/src/main/res/values-fa/translations.xml index f7b0d7f3db..20c064410c 100644 --- a/features/linknewdevice/impl/src/main/res/values-fa/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-fa/translations.xml @@ -1,16 +1,34 @@ "پویش کد پاس" + "%1$s را روی لپ‌تاپ یا رایانه رومیزی باز کنید." "پویش کد پاس با این افزاره" "آمادهٔ پویش" + "برای دریافت کد QR، %1$s را روی رایانه رومیزی باز کنید." + "فقط پس از انجام مراحل بالا در دستگاه خود، کد QR را اسکن کنید. هرگز کدی را که توسط شخص دیگری ارسال شده است، اسکن نکنید." + "اعداد مطابقت ندارند" + "کد دو رقمی را وارد کنید" + "این کار تأیید می‌کند که اتصال به دستگاه دیگر شما ایمن است." + "عدد نمایش داده شده در دستگاه دیگر خود را وارد کنید" "فراهم کنندهٔ حسابتان از %1$s پشتیبانی نمی‌کند." "%1$s پشتیبانی نمی‌شود" + "ارائه دهنده حساب شما از ورود به دستگاه جدید با کد QR پشتیبانی نمی‌کند." "کد پاس پشتیبانی نمی‌شود" "ورود روی افزارهٔ دیگر لغو شد." "درخواست ورد لغو شد" "ورود منقضی شد. لطفاً دوباره تلاش کنید." "ورود در زمان معیّن کامل نشد" + "%1$s را در دستگاه دیگر باز کنید" "گزینش %1$s" + "«ورود با کد QR»" + "کد QR نشان داده شده در اینجا را با دستگاه دیگر اسکن کنید" + "%1$s را در دستگاه دیگر باز کنید" + "کامپیوتر رومیزی" + "در حال بارگذاری کد QR…" + "دستگاه همراه" + "چه نوع دستگاهی را می‌خواهید لینک کنید؟" + "لطفاً دوباره امتحان کنید و مطمئن شوید که کد دو رقمی را به درستی وارد کرده‌اید. اگر اعداد هنوز مطابقت ندارند، با ارائه دهنده حساب خود تماس بگیرید." + "اعداد مطابقت ندارند" "نتوانست اتّصالی امن به افزارهٔ جدید بسازد. افزاره‌های موجودتان هنوز امنند و نیازی نیست نگرانشان باشید." "اکنون چه؟" "آزمودن ورود دوباره با کد پاس در صورت مشکل شبکه" @@ -23,6 +41,8 @@ "درخواست ورد لغو شد" "ورود به دست افزارهٔ دیگر رد شد." "ورود رد شد" + "لازم نیست کار دیگری انجام دهید." + "دستگاه دیگر شما قبلاً وارد سیستم شده است" "ورود منقضی شد. لطفاً دوباره تلاش کنید." "ورود در زمان معیّن کامل نشد" "افزارهٔ دیگرتان از ورود به %s با کد پاس پشتیبانی نمی‌کند. diff --git a/features/linknewdevice/impl/src/main/res/values-fi/translations.xml b/features/linknewdevice/impl/src/main/res/values-fi/translations.xml index 0ba5a30e58..c18b9bbfd0 100644 --- a/features/linknewdevice/impl/src/main/res/values-fi/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-fi/translations.xml @@ -5,6 +5,7 @@ "Skannaa QR-koodi tällä laitteella" "Valmis skannaamaan" "Avaa %1$s pöytätietokoneella saadaksesi QR-koodin" + "Skannaa QR-koodi vasta, kun olet noudattanut yllä olevia ohjeita omalla laitteellasi. Älä koskaan skannaa toisen henkilön lähettämää koodia." "Numerot eivät täsmää" "Kirjoita 2-numeroinen koodi" "Tämä varmistaa, että yhteys toiseen laitteeseesi on turvallinen." diff --git a/features/linknewdevice/impl/src/main/res/values-fr/translations.xml b/features/linknewdevice/impl/src/main/res/values-fr/translations.xml index 12a770af17..7e642578af 100644 --- a/features/linknewdevice/impl/src/main/res/values-fr/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-fr/translations.xml @@ -5,6 +5,7 @@ "Scanner le code QR avec cet appareil" "Prêt à scanner" "Ouvrir %1$s sur un ordinateur pour obtenir le code QR" + "Ne scannez un code QR qu’après avoir suivi les étapes ci-dessus sur votre propre appareil. Ne scannez jamais un code envoyé par quelqu’un d’autre." "Les nombres ne correspondent pas" "Saisissez le code à 2 chiffres" "Cela permettra de vérifier que la connexion à votre autre appareil est sécurisée." diff --git a/features/linknewdevice/impl/src/main/res/values-hr/translations.xml b/features/linknewdevice/impl/src/main/res/values-hr/translations.xml index 8561e63ad3..b77fcc5088 100644 --- a/features/linknewdevice/impl/src/main/res/values-hr/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-hr/translations.xml @@ -5,6 +5,7 @@ "Skenirajte QR kod ovim uređajem" "Spremno za skeniranje" "Otvorite %1$s na stolnom računalu kako biste dobili QR kod" + "QR kod skenirajte tek nakon što ste na vlastitom uređaju slijedili gore navedene korake. Nikada ne skenirajte kod koji vam je poslala druga osoba." "Brojevi se ne podudaraju" "Unesite dvoznamenkasti kod" "Time ćete potvrditi da je veza s vašim drugim uređajem sigurna." diff --git a/features/linknewdevice/impl/src/main/res/values-hu/translations.xml b/features/linknewdevice/impl/src/main/res/values-hu/translations.xml index 8cefed94cc..49556cf43a 100644 --- a/features/linknewdevice/impl/src/main/res/values-hu/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-hu/translations.xml @@ -5,6 +5,7 @@ "Olvassa be a QR-kódot ezzel az eszközzel" "Készen áll a beolvasásra" "Nyissa meg az asztali %1$s alkalmazást, hogy megkapja a QR-kódot" + "Csak a fenti lépések végrehajtása után olvass be QR-kódot a saját eszközén. Soha ne olvasson be más által küldött kódot." "A számok nem egyeznek" "Írja be a kétjegyű kódot" "Ezzel ellenőrizni fogja, hogy a másik eszközzel való kapcsolat biztonságos-e." diff --git a/features/linknewdevice/impl/src/main/res/values-ro/translations.xml b/features/linknewdevice/impl/src/main/res/values-ro/translations.xml index 57d439240d..5ba904c7fc 100644 --- a/features/linknewdevice/impl/src/main/res/values-ro/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-ro/translations.xml @@ -5,6 +5,7 @@ "Scanați codul QR cu acest dispozitiv" "Gata de scanare" "Deschide %1$s pe un computer desktop pentru a obține codul QR" + "Scanați un cod QR doar după ce urmați pașii de mai sus pe propriul dispozitiv. Nu scanați niciodată un cod trimis de o altă persoană." "Numerele nu se potrivesc" "Introduceți codul de 2 cifre" "Aceasta va verifica dacă conexiunea cu celălalt dispozitiv este sigură." diff --git a/features/linknewdevice/impl/src/main/res/values-zh-rTW/translations.xml b/features/linknewdevice/impl/src/main/res/values-zh-rTW/translations.xml index e18fbc13b6..04bea08c86 100644 --- a/features/linknewdevice/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/linknewdevice/impl/src/main/res/values-zh-rTW/translations.xml @@ -5,6 +5,7 @@ "使用此裝置掃描 QR code" "準備掃描" "在桌上型電腦上開啟 %1$s 以取得 QR code" + "請務必先在您的裝置上完成上述步驟,之後才掃描 QR code。切勿掃描他人傳送的 QR code。" "數字不符" "輸入兩位數代碼" "這將確認您與另一台裝置之間的連線是否安全。" diff --git a/features/linknewdevice/impl/src/test/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenterTest.kt b/features/linknewdevice/impl/src/test/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenterTest.kt index f92cf66102..db7c3e8c01 100644 --- a/features/linknewdevice/impl/src/test/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenterTest.kt +++ b/features/linknewdevice/impl/src/test/kotlin/io/element/android/features/linknewdevice/impl/screens/qrcode/ShowQrCodePresenterTest.kt @@ -91,10 +91,36 @@ class ShowQrCodePresenterTest { } } + @Test + fun `present - when handler emits QrRotating, the presenter does not emit anything when rotation is disabled`() = runTest { + val linkMobileHandler = FakeLinkMobileHandler( + startResult = {}, + ) + val matrixClient = FakeMatrixClient( + sessionCoroutineScope = backgroundScope, + createLinkMobileHandlerResult = { Result.success(linkMobileHandler) }, + ) + val linkNewMobileHandler = LinkNewMobileHandler(matrixClient) + linkNewMobileHandler.createAndStartNewHandler() + createPresenter( + linkNewMobileHandler = linkNewMobileHandler, + maxQrCodeRotation = 0, + ).test { + awaitItem() + linkMobileHandler.emitStep( + LinkMobileStep.QrRotating + ) + runCurrent() + expectNoEvents() + } + } + private fun createPresenter( linkNewMobileHandler: LinkNewMobileHandler = LinkNewMobileHandler(FakeMatrixClient()), + maxQrCodeRotation: Int = 10, ) = ShowQrCodePresenter( initialData = "DATA", + maxQrCodeRotation = maxQrCodeRotation, linkNewMobileHandler = linkNewMobileHandler, ) } diff --git a/features/location/api/build.gradle.kts b/features/location/api/build.gradle.kts index f8377389f1..8830b39a22 100644 --- a/features/location/api/build.gradle.kts +++ b/features/location/api/build.gradle.kts @@ -70,6 +70,8 @@ dependencies { implementation(projects.libraries.matrix.api) implementation(projects.libraries.matrixui) implementation(projects.libraries.uiStrings) + implementation(projects.libraries.wellknown.api) + implementation(projects.features.enterprise.api) implementation(libs.coil.compose) implementation(libs.datetime) diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/LocalMapTilerConfig.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/LocalMapTilerConfig.kt new file mode 100644 index 0000000000..752dd2401c --- /dev/null +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/LocalMapTilerConfig.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.location.api + +import androidx.compose.runtime.staticCompositionLocalOf +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig + +/** + * Provides a [MapTilerConfig] for the MapLibre maps. + */ +val LocalMapTilerConfig = staticCompositionLocalOf { + MapTilerConfig( + apiKey = BuildConfig.MAPTILER_API_KEY, + lightStyleId = BuildConfig.MAPTILER_LIGHT_MAP_ID, + darkStyleId = BuildConfig.MAPTILER_DARK_MAP_ID, + baseUrl = BuildConfig.MAPTILER_BASE_URL + ) +} diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/LocationService.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/LocationService.kt index 22049c9548..41c58c396f 100644 --- a/features/location/api/src/main/kotlin/io/element/android/features/location/api/LocationService.kt +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/LocationService.kt @@ -8,6 +8,10 @@ package io.element.android.features.location.api +/** + * Tells whether the location features can be used at all, which depends on the build having a map provider configured. + */ interface LocationService { + /** Whether location sharing and map rendering are available; `false` disables the whole feature in the UI. */ fun isServiceAvailable(): Boolean } diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/StaticMapView.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/StaticMapView.kt index c16b1ae560..b3149964e4 100644 --- a/features/location/api/src/main/kotlin/io/element/android/features/location/api/StaticMapView.kt +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/StaticMapView.kt @@ -37,9 +37,10 @@ import coil3.compose.rememberAsyncImagePainter import coil3.request.ImageRequest import coil3.request.SuccessResult import io.element.android.compound.theme.ElementTheme +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.api.internal.StaticMapPlaceholder -import io.element.android.features.location.api.internal.StaticMapUrlBuilder import io.element.android.features.location.api.internal.centerBottomEdge +import io.element.android.features.location.api.internal.rememberStaticMapBuilder import io.element.android.libraries.designsystem.components.LocationPin import io.element.android.libraries.designsystem.components.PinVariant import io.element.android.libraries.designsystem.preview.ElementPreview @@ -57,6 +58,7 @@ import io.element.android.libraries.designsystem.utils.CommonDrawables */ @Composable fun StaticMapView( + mapTilerConfig: MapTilerConfig?, location: Location?, zoom: Double, pinVariant: PinVariant, @@ -94,6 +96,7 @@ fun StaticMapView( } // Cases 3 & 4: Non-null location - fetch map else -> LoadableMapContent( + mapTilerConfig = mapTilerConfig, location = location, zoom = zoom, pinVariant = pinVariant, @@ -124,6 +127,7 @@ private fun BoxWithConstraintsScope.StaleMapContent( @Composable private fun BoxWithConstraintsScope.LoadableMapContent( + mapTilerConfig: MapTilerConfig?, location: Location, zoom: Double, pinVariant: PinVariant, @@ -132,7 +136,7 @@ private fun BoxWithConstraintsScope.LoadableMapContent( ) { val context = LocalContext.current var retryHash by remember { mutableIntStateOf(0) } - val builder = remember { StaticMapUrlBuilder() } + val builder = rememberStaticMapBuilder(mapTilerConfig) val (painter, state, contentScale) = if (LocalInspectionMode.current) { val painter = painterResource(CommonDrawables.sample_map) @@ -203,6 +207,7 @@ private fun BoxWithConstraintsScope.LoadableMapContent( @Composable internal fun StaticMapViewPreview() = ElementPreview { StaticMapView( + mapTilerConfig = null, location = Location(0.0, 0.0), zoom = 0.0, contentDescription = null, diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerStaticMapUrlBuilder.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerStaticMapUrlBuilder.kt index 666ca07a08..cd339f67b0 100644 --- a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerStaticMapUrlBuilder.kt +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerStaticMapUrlBuilder.kt @@ -8,6 +8,7 @@ package io.element.android.features.location.api.internal +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.api.BuildConfig import kotlin.math.roundToInt @@ -29,6 +30,13 @@ internal class MapTilerStaticMapUrlBuilder( darkMapId = BuildConfig.MAPTILER_DARK_MAP_ID, ) + constructor(mapTilerConfig: MapTilerConfig) : this( + baseUrl = (mapTilerConfig.baseUrl ?: BuildConfig.MAPTILER_BASE_URL).removeSuffix("/"), + apiKey = mapTilerConfig.apiKey.takeIf { it.isNotBlank() } ?: BuildConfig.MAPTILER_API_KEY, + lightMapId = mapTilerConfig.lightStyleId ?: BuildConfig.MAPTILER_LIGHT_MAP_ID, + darkMapId = mapTilerConfig.darkStyleId ?: BuildConfig.MAPTILER_DARK_MAP_ID, + ) + override fun build( lat: Double, lon: Double, diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilder.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilder.kt index 054805d1ab..d817a3307f 100644 --- a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilder.kt +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilder.kt @@ -10,6 +10,7 @@ package io.element.android.features.location.api.internal +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.api.BuildConfig internal class MapTilerTileServerStyleUriBuilder( @@ -26,17 +27,17 @@ internal class MapTilerTileServerStyleUriBuilder( ) override fun build( - customMapStyleUrl: String?, + customMapTilerConfig: MapTilerConfig?, darkMode: Boolean, ): String { - return buildString { - if (customMapStyleUrl.isNullOrBlank()) { - val mapId = if (darkMode) darkMapId else lightMapId - append("$baseUrl/$mapId/style.json") - } else { - append(customMapStyleUrl) - } - append("?key=$apiKey") + val baseUrl = customMapTilerConfig?.baseUrl.takeIf { !it.isNullOrBlank() } ?: baseUrl + val apiKey = customMapTilerConfig?.apiKey ?: apiKey + val mapId = if (darkMode) { + customMapTilerConfig?.darkStyleId ?: darkMapId + } else { + customMapTilerConfig?.lightStyleId ?: lightMapId } + + return "$baseUrl/$mapId/style.json?key=$apiKey" } } diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/StaticMapUrlBuilder.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/StaticMapUrlBuilder.kt index 6636976828..31992b1dd6 100644 --- a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/StaticMapUrlBuilder.kt +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/StaticMapUrlBuilder.kt @@ -8,10 +8,24 @@ package io.element.android.features.location.api.internal +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig /** * Builds an URL for a 3rd party service provider static maps API. */ interface StaticMapUrlBuilder { + /** + * Builds the URL of a map image centred on the given coordinates. + * + * @param lat latitude of the centre of the map. + * @param lon longitude of the centre of the map. + * @param zoom zoom level to render at. + * @param darkMode whether to request the dark map style. + * @param width width of the image in density independent pixels. + * @param height height of the image in density independent pixels. + * @param density screen density, used to request a matching pixel size. + */ fun build( lat: Double, lon: Double, @@ -22,7 +36,17 @@ interface StaticMapUrlBuilder { density: Float, ): String + /** Whether a map provider is configured for this build; the URLs are unusable when it is not. */ fun isServiceAvailable(): Boolean } -fun StaticMapUrlBuilder(): StaticMapUrlBuilder = MapTilerStaticMapUrlBuilder() +@Composable +fun rememberStaticMapBuilder(mapTilerConfig: MapTilerConfig?): StaticMapUrlBuilder { + return remember(mapTilerConfig) { + if (mapTilerConfig != null) { + MapTilerStaticMapUrlBuilder(mapTilerConfig) + } else { + MapTilerStaticMapUrlBuilder() + } + } +} diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/TileServerStyleUriBuilder.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/TileServerStyleUriBuilder.kt index 762d580f8e..67936525e5 100644 --- a/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/TileServerStyleUriBuilder.kt +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/internal/TileServerStyleUriBuilder.kt @@ -11,6 +11,7 @@ package io.element.android.features.location.api.internal import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import io.element.android.compound.theme.ElementTheme +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig /** * Builds a style URI for a MapLibre compatible tile server. @@ -18,8 +19,14 @@ import io.element.android.compound.theme.ElementTheme * Used for rendering dynamic maps. */ interface TileServerStyleUriBuilder { + /** + * Builds the style URI the map view loads its tiles from. + * + * @param customMapTilerConfig the custom MapTiler configuration received from the server, or null if not available. + * @param darkMode whether to request the dark map style. + */ fun build( - customMapStyleUrl: String?, + customMapTilerConfig: MapTilerConfig?, darkMode: Boolean, ): String } @@ -31,12 +38,12 @@ interface TileServerStyleUriBuilder { */ @Composable fun rememberTileStyleUrl( - customMapStyleUrl: String?, + customMapTileConfig: MapTilerConfig?, ): String { val darkMode = !ElementTheme.isLightTheme - return remember(darkMode, customMapStyleUrl) { + return remember(darkMode, customMapTileConfig) { MapTilerTileServerStyleUriBuilder().build( - customMapStyleUrl = customMapStyleUrl, + customMapTilerConfig = customMapTileConfig, darkMode = darkMode, ) } diff --git a/features/location/api/src/main/kotlin/io/element/android/features/location/api/live/ActiveLiveLocationShareManager.kt b/features/location/api/src/main/kotlin/io/element/android/features/location/api/live/ActiveLiveLocationShareManager.kt index cd6b8731c1..64c28209ca 100644 --- a/features/location/api/src/main/kotlin/io/element/android/features/location/api/live/ActiveLiveLocationShareManager.kt +++ b/features/location/api/src/main/kotlin/io/element/android/features/location/api/live/ActiveLiveLocationShareManager.kt @@ -12,6 +12,9 @@ import io.element.android.libraries.matrix.api.core.RoomId import kotlinx.coroutines.flow.StateFlow import kotlin.time.Duration +/** + * Owns the live location shares running on this device, across every room, and the foreground service that feeds them GPS updates. + */ interface ActiveLiveLocationShareManager { /** All rooms currently sharing live location on this device. */ val sharingRoomIds: StateFlow> @@ -27,6 +30,9 @@ interface ActiveLiveLocationShareManager { * Starts live location sharing in the given room. * Calls room.startLiveLocationShare() on the SDK, registers the share, * and starts the foreground GPS service if not already running. + * + * @param roomId the room to start sharing the location in. + * @param duration how long the share should last before it expires on its own. */ suspend fun startShare(roomId: RoomId, duration: Duration): Result @@ -34,6 +40,8 @@ interface ActiveLiveLocationShareManager { * Stops live location sharing in the given room. * Calls room.stopLiveLocationShare() on the SDK, removes the share, * and stops the foreground service if no shares remain. + * + * @param roomId the room to stop sharing the location in. */ suspend fun stopShare(roomId: RoomId): Result } diff --git a/features/location/api/src/test/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilderTest.kt b/features/location/api/src/test/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilderTest.kt index 2e07204594..c153ab1ce4 100644 --- a/features/location/api/src/test/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilderTest.kt +++ b/features/location/api/src/test/kotlin/io/element/android/features/location/api/internal/MapTilerTileServerStyleUriBuilderTest.kt @@ -9,6 +9,7 @@ package io.element.android.features.location.api.internal import com.google.common.truth.Truth.assertThat +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import org.junit.Test class MapTilerTileServerStyleUriBuilderTest { @@ -23,7 +24,7 @@ class MapTilerTileServerStyleUriBuilderTest { fun `light map uri`() { assertThat( builder.build( - customMapStyleUrl = null, + customMapTilerConfig = null, darkMode = false, ) ).isEqualTo("https://base.url/aLightMapId/style.json?key=anApiKey") @@ -33,7 +34,7 @@ class MapTilerTileServerStyleUriBuilderTest { fun `dark map uri`() { assertThat( builder.build( - customMapStyleUrl = null, + customMapTilerConfig = null, darkMode = true, ) ).isEqualTo("https://base.url/aDarkMapId/style.json?key=anApiKey") @@ -43,19 +44,44 @@ class MapTilerTileServerStyleUriBuilderTest { fun `custom map uri light`() { assertThat( builder.build( - customMapStyleUrl = "https://custom.url/style.json", + customMapTilerConfig = MapTilerConfig( + apiKey = "API_KEY", + lightStyleId = "light", + darkStyleId = "dark", + baseUrl = "https://custom.url/style.json" + ), darkMode = false, ) - ).isEqualTo("https://custom.url/style.json?key=anApiKey") + ).isEqualTo("https://custom.url/style.json/light/style.json?key=API_KEY") } @Test fun `custom map uri dark`() { assertThat( builder.build( - customMapStyleUrl = "https://custom.url/style.json", + customMapTilerConfig = MapTilerConfig( + apiKey = "API_KEY", + lightStyleId = "light", + darkStyleId = "dark", + baseUrl = "https://custom.url/style.json" + ), darkMode = true, ) - ).isEqualTo("https://custom.url/style.json?key=anApiKey") + ).isEqualTo("https://custom.url/style.json/dark/style.json?key=API_KEY") + } + + @Test + fun `blank custom map uri falls back to the built-in style`() { + assertThat( + builder.build( + customMapTilerConfig = MapTilerConfig( + apiKey = "API_KEY", + lightStyleId = "light", + darkStyleId = "dark", + baseUrl = " " + ), + darkMode = false, + ) + ).isEqualTo("https://base.url/light/style.json?key=API_KEY") } } diff --git a/features/location/impl/build.gradle.kts b/features/location/impl/build.gradle.kts index 165c32b7c5..43e4f58cab 100644 --- a/features/location/impl/build.gradle.kts +++ b/features/location/impl/build.gradle.kts @@ -26,6 +26,7 @@ setupDependencyInjection() dependencies { api(projects.features.location.api) + implementation(projects.features.enterprise.api) implementation(projects.features.messages.api) implementation(libs.maplibre.compose) implementation(libs.coil) @@ -45,6 +46,7 @@ dependencies { implementation(projects.libraries.preferences.api) implementation(projects.libraries.push.api) implementation(projects.libraries.sessionStorage.api) + implementation(projects.libraries.wellknown.api) implementation(libs.androidx.datastore.preferences) implementation(libs.datetime) @@ -58,5 +60,7 @@ dependencies { testImplementation(projects.libraries.featureflag.test) testImplementation(projects.libraries.preferences.test) testImplementation(projects.libraries.sessionStorage.test) + testImplementation(projects.libraries.wellknown.test) testImplementation(projects.features.location.test) + testImplementation(projects.features.enterprise.test) } diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/common/ui/MapBottomSheetScaffold.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/common/ui/MapBottomSheetScaffold.kt index 0eff1b6028..84c4ab4fba 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/common/ui/MapBottomSheetScaffold.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/common/ui/MapBottomSheetScaffold.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.api.internal.rememberTileStyleUrl import io.element.android.features.location.impl.common.MapDefaults import io.element.android.libraries.architecture.AsyncData @@ -66,7 +67,7 @@ import kotlin.math.roundToInt * - Updating camera position padding based on sheet height * - Rendering the MaplibreMap with proper ornament positioning * - * @param customMapStyleUrl Optional custom style URL for the map + * @param customMapTilerConfig Optional custom style URL for the map * @param modifier Modifier for the root layout * @param scaffoldState State for the bottom sheet scaffold * @param cameraState The camera state for the map @@ -83,7 +84,7 @@ import kotlin.math.roundToInt @OptIn(ExperimentalMaterial3Api::class) @Composable fun MapBottomSheetScaffold( - customMapStyleUrl: AsyncData, + customMapTilerConfig: AsyncData, modifier: Modifier = Modifier, scaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState( bottomSheetState = rememberBottomSheetState( @@ -137,11 +138,11 @@ fun MapBottomSheetScaffold( val ornamentOptions = mapOptions.ornamentOptions.copy(padding = sheetPadding) val mapOptions = mapOptions.copy(ornamentOptions = ornamentOptions) Box { - when (customMapStyleUrl) { + when (customMapTilerConfig) { is AsyncData.Success -> { MaplibreMap( options = mapOptions, - baseStyle = BaseStyle.Uri(rememberTileStyleUrl(customMapStyleUrl.data)), + baseStyle = BaseStyle.Uri(rememberTileStyleUrl(customMapTilerConfig.data)), modifier = Modifier.fillMaxSize(), cameraState = cameraState, content = mapContent, diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenter.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenter.kt index a3f3cac432..55f1e088d2 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenter.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenter.kt @@ -22,6 +22,7 @@ import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedFactory import dev.zacsweers.metro.AssistedInject import im.vector.app.features.analytics.plan.Composer +import io.element.android.features.enterprise.api.remoteconfig.CustomMapTilerConfigProvider import io.element.android.features.location.api.live.ActiveLiveLocationShareManager import io.element.android.features.location.impl.common.LocationConstraintsCheck import io.element.android.features.location.impl.common.MapDefaults @@ -72,6 +73,7 @@ class ShareLocationPresenter( private val liveLocationShareManager: ActiveLiveLocationShareManager, private val liveLocationStore: LiveLocationStore, private val userLocationStateFactory: UserLocationState.Factory, + private val customMapTilerConfigProvider: CustomMapTilerConfigProvider, ) : Presenter { @AssistedFactory fun interface Factory { @@ -92,9 +94,9 @@ class ShareLocationPresenter( var pendingLiveLocationShare by remember { mutableStateOf(false) } val startLiveLocationAction = remember { mutableStateOf>(AsyncAction.Uninitialized) } val currentUser by client.userProfile.collectAsState() - val customMapStyleUrl by produceState(AsyncData.Loading()) { + val customMapConfig by produceState(AsyncData.Loading()) { // Ignore errors - value = AsyncData.Success(client.getMapStyleUrl().getOrNull()) + value = AsyncData.Success(customMapTilerConfigProvider.get().getOrNull()) } val sendLiveLocationPermissions by room.permissionsAsState(SendLiveLocationPermissions.DEFAULT) { perms -> perms.sendLiveLocationPermissions() @@ -199,7 +201,7 @@ class ShareLocationPresenter( } return ShareLocationState( - customMapStyleUrl = customMapStyleUrl, + customMapTilerConfig = customMapConfig, currentUser = currentUser, dialogState = dialogState, trackUserLocation = trackUserPosition, diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationState.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationState.kt index fb1b803435..b29228f866 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationState.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationState.kt @@ -8,6 +8,7 @@ package io.element.android.features.location.impl.share +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.impl.common.ui.LocationConstraintsDialogState import io.element.android.features.location.impl.common.userlocation.UserLocationState import io.element.android.libraries.architecture.AsyncAction @@ -16,7 +17,7 @@ import io.element.android.libraries.matrix.api.user.MatrixUser import kotlinx.collections.immutable.ImmutableList data class ShareLocationState( - val customMapStyleUrl: AsyncData, + val customMapTilerConfig: AsyncData, val currentUser: MatrixUser, val dialogState: Dialog, val trackUserLocation: Boolean, diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationStateProvider.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationStatePreviewParam.kt similarity index 91% rename from features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationStateProvider.kt rename to features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationStatePreviewParam.kt index ed8d46afd3..908c7f0641 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationStateProvider.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationStatePreviewParam.kt @@ -9,6 +9,7 @@ package io.element.android.features.location.impl.share import androidx.compose.ui.tooling.preview.PreviewParameterProvider +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.impl.common.ui.LocationConstraintsDialogState import io.element.android.features.location.impl.common.userlocation.UserLocationState import io.element.android.libraries.architecture.AsyncAction @@ -21,7 +22,7 @@ import kotlin.time.Duration.Companion.minutes private const val APP_NAME = "ApplicationName" -class ShareLocationStateProvider : PreviewParameterProvider { +class ShareLocationStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aShareLocationState( @@ -70,13 +71,13 @@ class ShareLocationStateProvider : PreviewParameterProvider canShareLiveLocation = true, ), aShareLocationState( - customMapStyleUrl = AsyncData.Loading(), + customMapTilerConfig = AsyncData.Loading(), ), ) } fun aShareLocationState( - customMapStyleUrl: AsyncData = AsyncData.Success(null), + customMapTilerConfig: AsyncData = AsyncData.Success(null), currentUser: MatrixUser = MatrixUser(UserId("@user:matrix.org")), dialogState: ShareLocationState.Dialog = ShareLocationState.Dialog.None, trackUserPosition: Boolean = false, @@ -87,7 +88,7 @@ fun aShareLocationState( eventSink: (ShareLocationEvent) -> Unit = {}, ): ShareLocationState { return ShareLocationState( - customMapStyleUrl = customMapStyleUrl, + customMapTilerConfig = customMapTilerConfig, currentUser = currentUser, dialogState = dialogState, trackUserLocation = trackUserPosition, @@ -95,6 +96,6 @@ fun aShareLocationState( canShareLiveLocation = canShareLiveLocation, appName = appName, startLiveLocationAction = startLiveLocationAction, - eventSink = eventSink + eventSink = eventSink, ) } diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationView.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationView.kt index 8b7106e939..36827cc919 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationView.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/share/ShareLocationView.kt @@ -118,7 +118,7 @@ fun ShareLocationView( } MapBottomSheetScaffold( - customMapStyleUrl = state.customMapStyleUrl, + customMapTilerConfig = state.customMapTilerConfig, cameraState = cameraState, modifier = modifier, scaffoldState = scaffoldState, @@ -332,7 +332,7 @@ private fun LiveLocationDurationDialog( @PreviewsDayNight @Composable internal fun ShareLocationViewPreview( - @PreviewParameter(ShareLocationStateProvider::class) state: ShareLocationState + @PreviewParameter(ShareLocationStatePreviewParam::class) state: ShareLocationState ) = ElementPreview { ShareLocationView( state = state, diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenter.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenter.kt index f187e91c53..bbec7b449f 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenter.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenter.kt @@ -22,6 +22,7 @@ import androidx.compose.runtime.setValue import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedFactory import dev.zacsweers.metro.AssistedInject +import io.element.android.features.enterprise.api.remoteconfig.CustomMapTilerConfigProvider import io.element.android.features.location.api.Location import io.element.android.features.location.api.ShowLocationMode import io.element.android.features.location.api.live.ActiveLiveLocationShareManager @@ -46,7 +47,6 @@ import io.element.android.libraries.dateformatter.api.DateFormatter import io.element.android.libraries.dateformatter.api.DateFormatterMode import io.element.android.libraries.designsystem.components.avatar.AvatarData import io.element.android.libraries.designsystem.components.avatar.AvatarSize -import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.api.room.getBestName import io.element.android.libraries.matrix.api.room.joinedRoomMembers @@ -57,17 +57,18 @@ import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch -@AssistedInject class ShowLocationPresenter( +@AssistedInject +class ShowLocationPresenter( @Assisted private val mode: ShowLocationMode, permissionsPresenterFactory: PermissionsPresenter.Factory, private val locationActions: LocationActions, private val buildMeta: BuildMeta, private val dateFormatter: DateFormatter, private val stringProvider: StringProvider, - private val client: MatrixClient, private val joinedRoom: JoinedRoom, private val liveLocationShareManager: ActiveLiveLocationShareManager, private val userLocationStateFactory: UserLocationState.Factory, + private val customMapTilerConfigProvider: CustomMapTilerConfigProvider, ) : Presenter { @AssistedFactory fun interface Factory { fun create(mode: ShowLocationMode): ShowLocationPresenter @@ -85,9 +86,9 @@ import kotlinx.coroutines.launch mutableStateOf(LocationConstraintsDialogState.None) } - val customMapStyleUrl by produceState(AsyncData.Loading()) { + val customMapTilerConfig by produceState(AsyncData.Loading()) { // Ignore errors - value = AsyncData.Success(client.getMapStyleUrl().getOrNull()) + value = AsyncData.Success(customMapTilerConfigProvider.get().getOrNull()) } fun checkLocationConstraints() { @@ -220,7 +221,7 @@ import kotlinx.coroutines.launch userLocationStateFactory.create(hasLocationPermission = permissionsState.isAnyGranted) } return ShowLocationState( - customMapStyleUrl = customMapStyleUrl, + customMapTilerConfig = customMapTilerConfig, dialogState = dialogState, locationShares = locationShares, focusedLocation = focusedLocation, diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationState.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationState.kt index e5ddf589b0..0472eb94e9 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationState.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationState.kt @@ -8,6 +8,7 @@ package io.element.android.features.location.impl.show +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.api.Location import io.element.android.features.location.impl.common.ui.LocationConstraintsDialogState import io.element.android.features.location.impl.common.ui.LocationMarkerData @@ -20,7 +21,7 @@ import io.element.android.libraries.matrix.api.room.location.AssetType import kotlinx.collections.immutable.ImmutableList data class ShowLocationState( - val customMapStyleUrl: AsyncData, + val customMapTilerConfig: AsyncData, val isLive: Boolean, val dialogState: LocationConstraintsDialogState, val locationShares: ImmutableList, diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationStateProvider.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationStatePreviewParam.kt similarity index 90% rename from features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationStateProvider.kt rename to features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationStatePreviewParam.kt index cd7ea108bb..8473eaeb04 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationStateProvider.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationStatePreviewParam.kt @@ -9,6 +9,7 @@ package io.element.android.features.location.impl.show import androidx.compose.ui.tooling.preview.PreviewParameterProvider +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig import io.element.android.features.location.api.Location import io.element.android.features.location.impl.common.ui.LocationConstraintsDialogState import io.element.android.features.location.impl.common.userlocation.UserLocationState @@ -20,7 +21,7 @@ import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.room.location.AssetType import kotlinx.collections.immutable.toImmutableList -class ShowLocationStateProvider : PreviewParameterProvider { +class ShowLocationStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aShowLocationState(), @@ -36,14 +37,14 @@ class ShowLocationStateProvider : PreviewParameterProvider { constraintsDialogState = LocationConstraintsDialogState.LocationServiceDisabled, ), aShowLocationState(isTrackMyLocation = true), - aShowLocationState(customMapStyleUrl = AsyncData.Loading()), + aShowLocationState(customMapTilerConfig = AsyncData.Loading()), ) } private const val APP_NAME = "ApplicationName" fun aShowLocationState( - customMapStyleUrl: AsyncData = AsyncData.Success(null), + customMapTilerConfig: AsyncData = AsyncData.Success(null), isLive: Boolean = false, constraintsDialogState: LocationConstraintsDialogState = LocationConstraintsDialogState.None, locationShares: List = listOf(aLocationShareItem(isLive = isLive)), @@ -55,7 +56,7 @@ fun aShowLocationState( eventSink: (ShowLocationEvent) -> Unit = {}, ): ShowLocationState { return ShowLocationState( - customMapStyleUrl = customMapStyleUrl, + customMapTilerConfig = customMapTilerConfig, dialogState = constraintsDialogState, locationShares = locationShares.toImmutableList(), focusedLocation = focusedLocation, diff --git a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationView.kt b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationView.kt index 9fdbe3aac8..26eb1ee27a 100644 --- a/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationView.kt +++ b/features/location/impl/src/main/kotlin/io/element/android/features/location/impl/show/ShowLocationView.kt @@ -102,7 +102,7 @@ fun ShowLocationView( } } MapBottomSheetScaffold( - customMapStyleUrl = state.customMapStyleUrl, + customMapTilerConfig = state.customMapTilerConfig, sheetDragHandle = if (state.isSheetDraggable) { { BottomSheetDefaults.DragHandle() } } else { @@ -200,7 +200,7 @@ fun ShowLocationView( @PreviewsDayNight @Composable -internal fun ShowLocationViewPreview(@PreviewParameter(ShowLocationStateProvider::class) state: ShowLocationState) = ElementPreview { +internal fun ShowLocationViewPreview(@PreviewParameter(ShowLocationStatePreviewParam::class) state: ShowLocationState) = ElementPreview { ShowLocationView( state = state, onBackClick = {}, diff --git a/features/location/impl/src/main/res/values-ar/translations.xml b/features/location/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..fb70505fbe --- /dev/null +++ b/features/location/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,6 @@ + + + "سيُخزَّن سجل موقعك المباشر في الغرفة وسيكون مرئيًا للأعضاء بعد انتهاء الجلسة." + "اختر مدة مشاركة موقعك المباشر." + "ليست لديك صلاحيات لمشاركة موقعك المباشر في هذه الغرفة" + diff --git a/features/location/impl/src/main/res/values-de/translations.xml b/features/location/impl/src/main/res/values-de/translations.xml index 1a1e208c3b..1d10fea641 100644 --- a/features/location/impl/src/main/res/values-de/translations.xml +++ b/features/location/impl/src/main/res/values-de/translations.xml @@ -1,4 +1,5 @@ + "Der Verlauf deines Live-Standorts wird im Chat gespeichert und bleibt für die Mitglieder sichtbar, auch nachdem du die Freigabe beendet hast." "Wie lange soll der Live-Standort geteilt werden?" diff --git a/features/location/impl/src/main/res/values-es/translations.xml b/features/location/impl/src/main/res/values-es/translations.xml new file mode 100644 index 0000000000..9fc15d3468 --- /dev/null +++ b/features/location/impl/src/main/res/values-es/translations.xml @@ -0,0 +1,6 @@ + + + "Tu historial de ubicación en tiempo real se guardará en la sala y será visible para los miembros después de que termine la sesión." + "Elige por cuánto tiempo quieres compartir tu ubicación en tiempo real" + "No tienes permiso para compartir tu ubicación en tiempo real en esta sala." + diff --git a/features/location/impl/src/main/res/values-fa/translations.xml b/features/location/impl/src/main/res/values-fa/translations.xml new file mode 100644 index 0000000000..5183ed2f43 --- /dev/null +++ b/features/location/impl/src/main/res/values-fa/translations.xml @@ -0,0 +1,6 @@ + + + "سابقه موقعیت مکانی زنده شما در اتاق ذخیره می‌شود و پس از پایان جلسه برای اعضا قابل مشاهده خواهد بود." + "مدت زمان اشتراک‌گذاری موقعیت مکانی زنده خود را انتخاب کنید." + "شما مجوز اشتراک‌گذاری موقعیت مکانی زنده خود را در این اتاق ندارید" + diff --git a/features/location/impl/src/main/res/values-zh-rTW/translations.xml b/features/location/impl/src/main/res/values-zh-rTW/translations.xml index 27f507732d..d7647730de 100644 --- a/features/location/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/location/impl/src/main/res/values-zh-rTW/translations.xml @@ -2,4 +2,5 @@ "您的即時位置歷史將儲存於聊天室中,並在工作階段結束後對其他成員可見。" "選擇分享即時位置的時間長度。" + "您無權在此聊天室分享您的即時位置" diff --git a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/DefaultShareLocationEntryPointTest.kt b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/DefaultShareLocationEntryPointTest.kt index 49df684666..a37011e1d9 100644 --- a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/DefaultShareLocationEntryPointTest.kt +++ b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/DefaultShareLocationEntryPointTest.kt @@ -58,6 +58,7 @@ class DefaultShareLocationEntryPointTest { sessionId = room.sessionId, ), userLocationStateFactory = FakeUserLocationStateFactory(), + customMapTilerConfigProvider = { Result.success(null) }, ) }, analyticsService = FakeAnalyticsService(), diff --git a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenterTest.kt b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenterTest.kt index f4cc135e9e..d249fdaf69 100644 --- a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenterTest.kt +++ b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/share/ShareLocationPresenterTest.kt @@ -19,6 +19,8 @@ import app.cash.turbine.ReceiveTurbine import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import im.vector.app.features.analytics.plan.Composer +import io.element.android.features.enterprise.api.remoteconfig.MapTilerConfig +import io.element.android.features.enterprise.test.remoteconfig.aMapTilerConfig import io.element.android.features.location.api.Location import io.element.android.features.location.impl.aPermissionsState import io.element.android.features.location.impl.common.FakeUserLocationStateFactory @@ -60,7 +62,6 @@ import io.element.android.tests.testutils.test import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import org.junit.Rule @@ -77,20 +78,18 @@ class ShareLocationPresenterTest { private val fakeMessageComposerContext = FakeMessageComposerContext() private val fakeLocationActions = FakeLocationActions() private val fakeBuildMeta = aBuildMeta(applicationName = "app name") - private val fakeMatrixClient = FakeMatrixClient( - sessionId = A_USER_ID, - getMapStyleUrlResult = { Result.success(null) }, - ) + private val fakeMatrixClient = FakeMatrixClient(sessionId = A_USER_ID) private val durationFormatter = FakeDurationFormatter() - private fun TestScope.createShareLocationPresenter( + private fun createShareLocationPresenter( joinedRoom: JoinedRoom = FakeJoinedRoom(), timelineMode: Timeline.Mode = Timeline.Mode.Live, locationActions: FakeLocationActions = fakeLocationActions, liveLocationShareManager: FakeActiveLiveLocationShareManager = FakeActiveLiveLocationShareManager(), liveLocationStore: LiveLocationStore = createLiveLocationStore(sessionId = joinedRoom.sessionId), client: FakeMatrixClient = fakeMatrixClient, + customMapTilerConfigProvider: () -> Result = { Result.success(null) }, ): ShareLocationPresenter = ShareLocationPresenter( permissionsPresenterFactory = { fakePermissionsPresenter }, room = joinedRoom, @@ -104,6 +103,7 @@ class ShareLocationPresenterTest { liveLocationShareManager = liveLocationShareManager, liveLocationStore = liveLocationStore, userLocationStateFactory = FakeUserLocationStateFactory(), + customMapTilerConfigProvider = customMapTilerConfigProvider, ) @Test @@ -118,7 +118,7 @@ class ShareLocationPresenterTest { val shareLocationPresenter = createShareLocationPresenter() shareLocationPresenter.test { val state = awaitFirstItem() - assertThat(state.customMapStyleUrl.isLoading()).isFalse() + assertThat(state.customMapTilerConfig.isLoading()).isFalse() assertThat(state.trackUserLocation).isTrue() assertThat(state.dialogState).isEqualTo(ShareLocationState.Dialog.Constraints(LocationConstraintsDialogState.None)) } @@ -126,18 +126,18 @@ class ShareLocationPresenterTest { @Test fun `present - non-null customMapStyleUrl`() = runTest { + val mapTilerConfig = aMapTilerConfig(apiKey = "A KEY") val shareLocationPresenter = createShareLocationPresenter( client = FakeMatrixClient( sessionId = A_USER_ID, - getMapStyleUrlResult = { Result.success("aUrl") }, - ) + ), + customMapTilerConfigProvider = { Result.success(mapTilerConfig) } ) shareLocationPresenter.test { - skipItems(1) val state = awaitItem() - assertThat(state.customMapStyleUrl.isLoading()).isTrue() + assertThat(state.customMapTilerConfig.isLoading()).isTrue() val finalState = awaitItem() - assertThat(finalState.customMapStyleUrl.dataOrNull()).isEqualTo("aUrl") + assertThat(finalState.customMapTilerConfig.dataOrNull()).isEqualTo(mapTilerConfig) } } @@ -709,7 +709,7 @@ class ShareLocationPresenterTest { } private suspend fun ReceiveTurbine.awaitFirstItem(): T { - skipItems(2) + skipItems(1) return awaitItem() } } diff --git a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/DefaultShowLocationEntryPointTest.kt b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/DefaultShowLocationEntryPointTest.kt index 23b7e9bf4d..db5c6b9f9f 100644 --- a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/DefaultShowLocationEntryPointTest.kt +++ b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/DefaultShowLocationEntryPointTest.kt @@ -20,7 +20,6 @@ import io.element.android.features.location.impl.common.permissions.FakePermissi import io.element.android.features.location.test.FakeActiveLiveLocationShareManager import io.element.android.libraries.dateformatter.test.FakeDateFormatter import io.element.android.libraries.matrix.api.core.UserId -import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.libraries.matrix.test.core.aBuildMeta import io.element.android.libraries.matrix.test.room.FakeJoinedRoom import io.element.android.services.analytics.test.FakeAnalyticsService @@ -41,8 +40,8 @@ class DefaultShowLocationEntryPointTest { ShowLocationNode( buildContext = buildContext, plugins = plugins, - presenterFactory = object : ShowLocationPresenter.Factory { - override fun create(mode: ShowLocationMode) = ShowLocationPresenter( + presenterFactory = { mode -> + ShowLocationPresenter( mode = mode, permissionsPresenterFactory = { FakePermissionsPresenter() }, locationActions = FakeLocationActions(), @@ -50,9 +49,9 @@ class DefaultShowLocationEntryPointTest { dateFormatter = FakeDateFormatter(), stringProvider = FakeStringProvider(), joinedRoom = joinedRoom, - client = FakeMatrixClient(), liveLocationShareManager = FakeActiveLiveLocationShareManager(), userLocationStateFactory = FakeUserLocationStateFactory(), + customMapTilerConfigProvider = { Result.success(null) }, ) }, analyticsService = FakeAnalyticsService(), diff --git a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenterTest.kt b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenterTest.kt index b579a79e4f..7d9b0d5e03 100644 --- a/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenterTest.kt +++ b/features/location/impl/src/test/kotlin/io/element/android/features/location/impl/show/ShowLocationPresenterTest.kt @@ -12,6 +12,8 @@ import app.cash.molecule.RecompositionMode import app.cash.molecule.moleculeFlow import app.cash.turbine.test import com.google.common.truth.Truth.assertThat +import io.element.android.features.enterprise.api.remoteconfig.CustomMapTilerConfigProvider +import io.element.android.features.enterprise.test.remoteconfig.aMapTilerConfig import io.element.android.features.location.api.Location import io.element.android.features.location.api.ShowLocationMode import io.element.android.features.location.impl.aPermissionsState @@ -23,13 +25,11 @@ import io.element.android.features.location.impl.common.permissions.PermissionsS import io.element.android.features.location.impl.common.ui.LocationConstraintsDialogState import io.element.android.features.location.test.FakeActiveLiveLocationShareManager import io.element.android.libraries.dateformatter.test.FakeDateFormatter -import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.api.room.location.AssetType import io.element.android.libraries.matrix.api.room.location.LiveLocationShare import io.element.android.libraries.matrix.test.A_USER_ID -import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.libraries.matrix.test.core.aBuildMeta import io.element.android.libraries.matrix.test.room.FakeJoinedRoom import io.element.android.libraries.matrix.test.room.location.aLiveLocationShare @@ -65,8 +65,8 @@ class ShowLocationPresenterTest { ), locationActions: FakeLocationActions = fakeLocationActions, joinedRoom: JoinedRoom = FakeJoinedRoom(), - client: MatrixClient = FakeMatrixClient(), liveLocationShareManager: FakeActiveLiveLocationShareManager = FakeActiveLiveLocationShareManager(), + customMapTilerConfigProvider: CustomMapTilerConfigProvider = { Result.success(null) }, ) = ShowLocationPresenter( mode = mode, permissionsPresenterFactory = { fakePermissionsPresenter }, @@ -75,24 +75,20 @@ class ShowLocationPresenterTest { dateFormatter = fakeDateFormatter, stringProvider = FakeStringProvider(), joinedRoom = joinedRoom, - client = client, liveLocationShareManager = liveLocationShareManager, userLocationStateFactory = FakeUserLocationStateFactory(), + customMapTilerConfigProvider = customMapTilerConfigProvider, ) @Test fun `present - non-null customMapStyleUrl`() = runTest { - val shareLocationPresenter = createShowLocationPresenter( - client = FakeMatrixClient( - sessionId = A_USER_ID, - getMapStyleUrlResult = { Result.success("aUrl") }, - ) - ) + val mapTilerConfig = aMapTilerConfig(apiKey = "A KEY") + val shareLocationPresenter = createShowLocationPresenter(customMapTilerConfigProvider = { Result.success(mapTilerConfig) }) shareLocationPresenter.test { val state = awaitItem() - assertThat(state.customMapStyleUrl.isLoading()).isTrue() + assertThat(state.customMapTilerConfig.isLoading()).isTrue() val finalState = awaitItem() - assertThat(finalState.customMapStyleUrl.dataOrNull()).isEqualTo("aUrl") + assertThat(finalState.customMapTilerConfig.dataOrNull()).isEqualTo(mapTilerConfig) } } @@ -115,6 +111,8 @@ class ShowLocationPresenterTest { initialState.eventSink(ShowLocationEvent.Share(location)) assertThat(fakeLocationActions.sharedLocation).isEqualTo(location) + + cancelAndIgnoreRemainingEvents() } } @@ -122,11 +120,8 @@ class ShowLocationPresenterTest { fun `centers on user location`() = runTest { fakePermissionsPresenter.givenState(aPermissionsState(permissions = PermissionsState.Permissions.AllGranted)) - val presenter = createShowLocationPresenter( - client = FakeMatrixClient( - getMapStyleUrlResult = { Result.success(null) } - ) - ) + val presenter = createShowLocationPresenter(customMapTilerConfigProvider = { Result.success(aMapTilerConfig()) }) + presenter.test { val initialState = awaitItem() assertThat(initialState.isTrackMyLocation).isFalse() @@ -281,6 +276,8 @@ class ShowLocationPresenterTest { }.test { val initialState = awaitItem() assertThat(initialState.appName).isEqualTo("app name") + + cancelAndIgnoreRemainingEvents() } } @@ -334,6 +331,8 @@ class ShowLocationPresenterTest { val initialState = awaitItem() assertThat(initialState.locationShares).isEmpty() assertThat(initialState.isSheetDraggable).isFalse() + + cancelAndIgnoreRemainingEvents() } } @@ -408,6 +407,9 @@ class ShowLocationPresenterTest { val initialState = awaitItem() assertThat(initialState.locationShares).isEmpty() + // Wait until we receive the custom map style URL result + skipItems(1) + // Emit a new live share liveSharesFlow.value = listOf( aLiveLocationShare(userId = userId) @@ -447,6 +449,8 @@ class ShowLocationPresenterTest { assertThat(item.avatarData.id).isEqualTo(senderId.value) assertThat(item.avatarData.name).isEqualTo(senderName) assertThat(item.avatarData.url).isEqualTo(avatarUrl) + + cancelAndIgnoreRemainingEvents() } } @@ -456,6 +460,7 @@ class ShowLocationPresenterTest { presenter.test { val state = awaitItem() assertThat(state.isSheetDraggable).isFalse() + cancelAndIgnoreRemainingEvents() } } @@ -465,6 +470,8 @@ class ShowLocationPresenterTest { presenter.test { val state = awaitItem() assertThat(state.hideUserLocationPuck).isFalse() + + cancelAndIgnoreRemainingEvents() } } @@ -476,6 +483,8 @@ class ShowLocationPresenterTest { presenter.test { val state = awaitItem() assertThat(state.hideUserLocationPuck).isFalse() + + cancelAndIgnoreRemainingEvents() } } diff --git a/features/lockscreen/api/src/main/kotlin/io/element/android/features/lockscreen/api/LockScreenService.kt b/features/lockscreen/api/src/main/kotlin/io/element/android/features/lockscreen/api/LockScreenService.kt index bd644e69e9..59c148660e 100644 --- a/features/lockscreen/api/src/main/kotlin/io/element/android/features/lockscreen/api/LockScreenService.kt +++ b/features/lockscreen/api/src/main/kotlin/io/element/android/features/lockscreen/api/LockScreenService.kt @@ -17,6 +17,9 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach +/** + * Exposes the app lock state: whether a PIN or biometric lock is set up, whether it is mandatory, and whether the app is locked right now. + */ interface LockScreenService { /** * The current lock state of the app. diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/LockScreenConfig.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/LockScreenConfig.kt index c246390a63..fa3ca9cfd9 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/LockScreenConfig.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/LockScreenConfig.kt @@ -8,12 +8,7 @@ package io.element.android.features.lockscreen.impl -import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.BindingContainer -import dev.zacsweers.metro.ContributesTo -import dev.zacsweers.metro.Provides import kotlin.time.Duration -import io.element.android.appconfig.LockScreenConfig as AppConfigLockScreenConfig data class LockScreenConfig( val isPinMandatory: Boolean, @@ -24,18 +19,3 @@ data class LockScreenConfig( val isStrongBiometricsEnabled: Boolean, val isWeakBiometricsEnabled: Boolean, ) - -@ContributesTo(AppScope::class) -@BindingContainer -object LockScreenConfigModule { - @Provides - fun providesLockScreenConfig(): LockScreenConfig = LockScreenConfig( - isPinMandatory = AppConfigLockScreenConfig.IS_PIN_MANDATORY, - forbiddenPinCodes = AppConfigLockScreenConfig.FORBIDDEN_PIN_CODES, - pinSize = AppConfigLockScreenConfig.PIN_SIZE, - maxPinCodeAttemptsBeforeLogout = AppConfigLockScreenConfig.MAX_PIN_CODE_ATTEMPTS_BEFORE_LOGOUT, - gracePeriod = AppConfigLockScreenConfig.GRACE_PERIOD, - isStrongBiometricsEnabled = AppConfigLockScreenConfig.IS_STRONG_BIOMETRICS_ENABLED, - isWeakBiometricsEnabled = AppConfigLockScreenConfig.IS_WEAK_BIOMETRICS_ENABLED, - ) -} diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/biometric/BiometricAuthenticator.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/biometric/BiometricAuthenticator.kt index 74d36b0834..f08d2fc1af 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/biometric/BiometricAuthenticator.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/biometric/BiometricAuthenticator.kt @@ -59,7 +59,7 @@ class DefaultBiometricAuthentication( private var cryptoObject: CryptoObject? = null override suspend fun setup() { - if (cryptoObject != null) return + Timber.d("Setup biometric authentication") try { val secretKey = ensureKey() val cipher = encryptionDecryptionService.createEncryptionCipher(secretKey) @@ -126,6 +126,9 @@ private class AuthenticationCallback( if (this == null) return false return runCatchingExceptions { doFinal("biometric_challenge".toByteArray()) - }.isSuccess + }.onFailure { + Timber.e(it, "Failed to validate cipher") + } + .isSuccess } } diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/di/LockScreenConfigBindingContainer.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/di/LockScreenConfigBindingContainer.kt new file mode 100644 index 0000000000..3acade5e86 --- /dev/null +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/di/LockScreenConfigBindingContainer.kt @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.lockscreen.impl.di + +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides +import io.element.android.features.lockscreen.impl.LockScreenConfig + +@ContributesTo(AppScope::class) +@BindingContainer +object LockScreenConfigBindingContainer { + @Provides + fun providesLockScreenConfig(): LockScreenConfig = LockScreenConfig( + isPinMandatory = io.element.android.appconfig.LockScreenConfig.IS_PIN_MANDATORY, + forbiddenPinCodes = io.element.android.appconfig.LockScreenConfig.FORBIDDEN_PIN_CODES, + pinSize = io.element.android.appconfig.LockScreenConfig.PIN_SIZE, + maxPinCodeAttemptsBeforeLogout = io.element.android.appconfig.LockScreenConfig.MAX_PIN_CODE_ATTEMPTS_BEFORE_LOGOUT, + gracePeriod = io.element.android.appconfig.LockScreenConfig.GRACE_PERIOD, + isStrongBiometricsEnabled = io.element.android.appconfig.LockScreenConfig.IS_STRONG_BIOMETRICS_ENABLED, + isWeakBiometricsEnabled = io.element.android.appconfig.LockScreenConfig.IS_WEAK_BIOMETRICS_ENABLED, + ) +} diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsStateProvider.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsStatePreviewParam.kt similarity index 91% rename from features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsStateProvider.kt rename to features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsStatePreviewParam.kt index 43f20c1c52..8929138077 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsStateProvider.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.lockscreen.impl.settings import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class LockScreenSettingsStateProvider : PreviewParameterProvider { +open class LockScreenSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLockScreenSettingsState(), diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsView.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsView.kt index d8655e29a3..291906caf0 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsView.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsView.kt @@ -84,7 +84,7 @@ fun LockScreenSettingsView( @PreviewsDayNight @Composable internal fun LockScreenSettingsViewPreview( - @PreviewParameter(LockScreenSettingsStateProvider::class) state: LockScreenSettingsState, + @PreviewParameter(LockScreenSettingsStatePreviewParam::class) state: LockScreenSettingsState, ) { ElementPreview { LockScreenSettingsView( diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricStateProvider.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricStatePreviewParam.kt similarity index 87% rename from features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricStateProvider.kt rename to features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricStatePreviewParam.kt index d725d2de97..6ad44f3273 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricStateProvider.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.lockscreen.impl.setup.biometric import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class SetupBiometricStateProvider : PreviewParameterProvider { +open class SetupBiometricStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSetupBiometricState(), diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricView.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricView.kt index 70a1046e36..13fad4e9d0 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricView.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/biometric/SetupBiometricView.kt @@ -79,7 +79,7 @@ private fun SetupBiometricFooter( @Composable @PreviewsDayNight -internal fun SetupBiometricViewPreview(@PreviewParameter(SetupBiometricStateProvider::class) state: SetupBiometricState) { +internal fun SetupBiometricViewPreview(@PreviewParameter(SetupBiometricStatePreviewParam::class) state: SetupBiometricState) { ElementPreview { SetupBiometricView( state = state, diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinStateProvider.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinStatePreviewParam.kt similarity index 95% rename from features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinStateProvider.kt rename to features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinStatePreviewParam.kt index f50643e367..706d49ce82 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinStateProvider.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.lockscreen.impl.pin.model.PinEntry import io.element.android.features.lockscreen.impl.setup.pin.validation.SetupPinFailure -open class SetupPinStateProvider : PreviewParameterProvider { +open class SetupPinStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSetupPinState(), diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinView.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinView.kt index 508d3c1fbb..7b0f86e386 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinView.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/setup/pin/SetupPinView.kt @@ -145,7 +145,7 @@ private fun SetupPinFailure.title(): String { @Composable @PreviewsDayNight -internal fun SetupPinViewPreview(@PreviewParameter(SetupPinStateProvider::class) state: SetupPinState) { +internal fun SetupPinViewPreview(@PreviewParameter(SetupPinStatePreviewParam::class) state: SetupPinState) { ElementPreview { SetupPinView( state = state, diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockStateProvider.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockStatePreviewParam.kt similarity index 94% rename from features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockStateProvider.kt rename to features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockStatePreviewParam.kt index aef2c057a2..dcc61e83ed 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockStateProvider.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.features.lockscreen.impl.pin.model.PinEntry import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.architecture.AsyncData -open class PinUnlockStateProvider : PreviewParameterProvider { +open class PinUnlockStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aPinUnlockState(), @@ -42,7 +42,7 @@ open class PinUnlockStateProvider : PreviewParameterProvider { ) } -open class PinUnlockStateCompactProvider : PreviewParameterProvider { +open class PinUnlockStateCompactPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aPinUnlockState(), diff --git a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockView.kt b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockView.kt index 0292b29a0f..e83b106d88 100644 --- a/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockView.kt +++ b/features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/unlock/PinUnlockView.kt @@ -381,7 +381,7 @@ private fun PinUnlockFooter( @Composable @PreviewsDayNight -internal fun PinUnlockViewInAppPreview(@PreviewParameter(PinUnlockStateProvider::class) state: PinUnlockState) { +internal fun PinUnlockViewInAppPreview(@PreviewParameter(PinUnlockStatePreviewParam::class) state: PinUnlockState) { ElementPreview { PinUnlockView( state = state, @@ -393,7 +393,7 @@ internal fun PinUnlockViewInAppPreview(@PreviewParameter(PinUnlockStateProvider: @Composable @PreviewsDayNight -internal fun PinUnlockViewPreview(@PreviewParameter(PinUnlockStateProvider::class) state: PinUnlockState) { +internal fun PinUnlockViewPreview(@PreviewParameter(PinUnlockStatePreviewParam::class) state: PinUnlockState) { ElementPreview { PinUnlockView( state = state, @@ -405,7 +405,7 @@ internal fun PinUnlockViewPreview(@PreviewParameter(PinUnlockStateProvider::clas @Composable @Preview(heightDp = 480, widthDp = 800) -internal fun PinUnlockViewCompactPreview(@PreviewParameter(PinUnlockStateCompactProvider::class) state: PinUnlockState) { +internal fun PinUnlockViewCompactPreview(@PreviewParameter(PinUnlockStateCompactPreviewParam::class) state: PinUnlockState) { ElementPreview { PinUnlockView( state = state, diff --git a/features/lockscreen/impl/src/main/res/values-ar/translations.xml b/features/lockscreen/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..b277c420ea --- /dev/null +++ b/features/lockscreen/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,46 @@ + + + "المصادقة بالمقاييس الحيوية" + "إلغاء القفل باستخدام المقاييس الحيوية" + "إلغاء القفل باستخدام المقاييس الحيوية" + "تأكيد المصادقة الحيوية" + "هل نسيت رمز PIN؟" + "تغيير رمز PIN" + "السماح بإلغاء القفل باستخدام المقاييس الحيوية" + "إزالة رمز PIN" + "هل أنت متأكد من رغبتك في إزالة رمز PIN؟" + "إزالة رمز PIN؟" + "السماح بـ %1$s" + "أفضّل استخدام رمز PIN" + "وفّر بعض الوقت واستخدم %1$s لإلغاء قفل التطبيق في كل مرة" + "اختر رمز PIN" + "تأكيد رمز PIN" + "اقفل %1$s لإضافة مزيد من الأمان إلى محادثاتك. + +اختر شيئًا يسهل تذكره. إذا نسيت رمز PIN هذا، فسيتم تسجيل خروجك من التطبيق." + "لا يمكنك اختيار هذا كرمز PIN لأسباب أمنية" + "اختر رمز PIN مختلفًا" + "يُرجى إدخال رمز PIN نفسه مرتين" + "رمزا PIN غير متطابقين" + "ستحتاج إلى تسجيل الدخول مرة أخرى وإنشاء رمز PIN جديد للمتابعة" + "تتم إزالة هذا الجهاز" + + "لديك %1$d محاولات لإلغاء القفل" + "لديك %1$d محاولة لإلغاء القفل" + "لديك %1$d محاولتان لإلغاء القفل" + "لديك %1$d محاولات لإلغاء القفل" + "لديك %1$d محاولة لإلغاء القفل" + "لديك %1$d محاولة لإلغاء القفل" + + + "رمز PIN غير صحيح. لديك %1$d فرص أخرى" + "رمز PIN غير صحيح. لديك %1$d فرصة أخرى" + "رمز PIN غير صحيح. لديك %1$d فرصتان أخريان" + "رمز PIN غير صحيح. لديك %1$d فرص أخرى" + "رمز PIN غير صحيح. لديك %1$d فرصة أخرى" + "رمز PIN غير صحيح. لديك %1$d فرصة أخرى" + + "استخدام المقاييس الحيوية" + "استخدام رمز PIN" + "تجري إزالة الجهاز…" + diff --git a/features/lockscreen/impl/src/main/res/values-es/translations.xml b/features/lockscreen/impl/src/main/res/values-es/translations.xml index c0e34a3763..085c1d1cbf 100644 --- a/features/lockscreen/impl/src/main/res/values-es/translations.xml +++ b/features/lockscreen/impl/src/main/res/values-es/translations.xml @@ -23,7 +23,7 @@ Elige algo que puedas recordar. Si olvidas este PIN, se cerrará la sesión de l "Por favor ingresa el mismo PIN dos veces" "Los PINs no coinciden" "Tendrás que volver a iniciar sesión y crear un nuevo PIN para continuar" - "Se está cerrando tu sesión" + "Se está eliminando este dispositivo" "Tienes %1$d intento de desbloqueo" "Tienes %1$d intentos de desbloqueo" @@ -34,5 +34,5 @@ Elige algo que puedas recordar. Si olvidas este PIN, se cerrará la sesión de l "Usar desbloqueo biométrico" "Usar PIN" - "Cerrando sesión…" + "Eliminando dispositivo…" diff --git a/features/lockscreen/impl/src/main/res/values-pl/translations.xml b/features/lockscreen/impl/src/main/res/values-pl/translations.xml index 29691987f6..e6faf72945 100644 --- a/features/lockscreen/impl/src/main/res/values-pl/translations.xml +++ b/features/lockscreen/impl/src/main/res/values-pl/translations.xml @@ -17,7 +17,7 @@ "Potwierdź PIN" "Zablokuj %1$s, aby zwiększyć bezpieczeństwo swoich czatów. -Wybierz coś łatwego do zapamiętania. Jeśli zapomnisz ten PIN, zostaniesz wylogowany z aplikacji." +Wybierz coś łatwego do zapamiętania. Jeśli zapomnisz tego PINu, zostaniesz wylogowany z aplikacji." "Nie możesz wybrać tego PIN\'u ze względów bezpieczeństwa" "Wybierz inny kod PIN" "Wprowadź ten sam kod PIN dwa razy" diff --git a/features/login/api/src/main/kotlin/io/element/android/features/login/api/LoginIntentResolver.kt b/features/login/api/src/main/kotlin/io/element/android/features/login/api/LoginIntentResolver.kt index 79cfc35fbd..b2b7378be4 100644 --- a/features/login/api/src/main/kotlin/io/element/android/features/login/api/LoginIntentResolver.kt +++ b/features/login/api/src/main/kotlin/io/element/android/features/login/api/LoginIntentResolver.kt @@ -8,6 +8,13 @@ package io.element.android.features.login.api +/** + * Extracts the login parameters from a link, so that a deployment can hand out a URL that pre-fills the sign-in screen. + */ interface LoginIntentResolver { + /** + * @param uriString the link the app was opened with. + * @return the account provider and login hint to pre-fill, or `null` when the link is not a login link. + */ fun parse(uriString: String): LoginParams? } diff --git a/features/login/api/src/main/kotlin/io/element/android/features/login/api/accesscontrol/AccountProviderAccessControl.kt b/features/login/api/src/main/kotlin/io/element/android/features/login/api/accesscontrol/AccountProviderAccessControl.kt index fc804c14ff..0c35c1655f 100644 --- a/features/login/api/src/main/kotlin/io/element/android/features/login/api/accesscontrol/AccountProviderAccessControl.kt +++ b/features/login/api/src/main/kotlin/io/element/android/features/login/api/accesscontrol/AccountProviderAccessControl.kt @@ -8,6 +8,14 @@ package io.element.android.features.login.api.accesscontrol +/** + * Enforces the restriction an enterprise deployment can put on which account providers the user may sign in to. + */ interface AccountProviderAccessControl { + /** + * Whether sign-in to this provider is permitted; `true` on a build with no such restriction. + * + * @param accountProviderUrl the server the user is trying to use. + */ suspend fun isAllowedToConnectToAccountProvider(accountProviderUrl: String): Boolean } diff --git a/features/login/impl/build.gradle.kts b/features/login/impl/build.gradle.kts index 86a8e0e7bc..6cf8945e05 100644 --- a/features/login/impl/build.gradle.kts +++ b/features/login/impl/build.gradle.kts @@ -69,6 +69,7 @@ dependencies { implementation(projects.libraries.sessionStorage.api) implementation(projects.libraries.qrcode) implementation(projects.libraries.oauth.api) + implementation(projects.libraries.preferences.api) implementation(projects.libraries.uiUtils) implementation(projects.libraries.wellknown.api) implementation(libs.androidx.browser) @@ -80,6 +81,7 @@ dependencies { testImplementation(projects.features.login.test) testImplementation(projects.features.enterprise.test) testImplementation(projects.features.preferences.test) + testImplementation(projects.libraries.preferences.test) testImplementation(projects.libraries.matrix.test) testImplementation(projects.libraries.oauth.test) testImplementation(projects.libraries.permissions.test) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/LoginFlowNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/LoginFlowNode.kt index 978d28dfa3..bbfe7c47d8 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/LoginFlowNode.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/LoginFlowNode.kt @@ -23,7 +23,6 @@ import com.bumble.appyx.navmodel.backstack.BackStack import com.bumble.appyx.navmodel.backstack.operation.pop import com.bumble.appyx.navmodel.backstack.operation.push import com.bumble.appyx.navmodel.backstack.operation.replace -import com.bumble.appyx.navmodel.backstack.operation.singleTop import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedInject @@ -33,14 +32,11 @@ import io.element.android.features.login.api.LoginEntryPoint import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource import io.element.android.features.login.impl.classic.ElementClassicConnection import io.element.android.features.login.impl.qrcode.QrCodeLoginFlowNode -import io.element.android.features.login.impl.screens.changeaccountprovider.ChangeAccountProviderNode import io.element.android.features.login.impl.screens.chooseaccountprovider.ChooseAccountProviderNode import io.element.android.features.login.impl.screens.classic.ClassicFlowNode import io.element.android.features.login.impl.screens.confirmaccountprovider.ConfirmAccountProviderNode -import io.element.android.features.login.impl.screens.createaccount.CreateAccountNode import io.element.android.features.login.impl.screens.loginpassword.LoginPasswordNode import io.element.android.features.login.impl.screens.onboarding.OnBoardingNode -import io.element.android.features.login.impl.screens.searchaccountprovider.SearchAccountProviderNode import io.element.android.features.preferences.api.PreferencesEntryPoint import io.element.android.libraries.androidutils.browser.openUrlInChromeCustomTab import io.element.android.libraries.architecture.BackstackView @@ -130,19 +126,10 @@ class LoginFlowNode( @Parcelize data object ChooseAccountProvider : NavTarget - @Parcelize - data object ChangeAccountProvider : NavTarget - - @Parcelize - data object SearchAccountProvider : NavTarget - @Parcelize data class LoginPassword( val initialLogin: String = "", ) : NavTarget - - @Parcelize - data class CreateAccount(val url: String) : NavTarget } override fun resolve(navTarget: NavTarget, buildContext: BuildContext): Node { @@ -164,10 +151,6 @@ class LoginFlowNode( override fun navigateToOAuth(oAuthDetails: OAuthDetails) { navigateToMas(oAuthDetails) } - - override fun navigateToCreateAccount(url: String) { - backstack.push(NavTarget.CreateAccount(url)) - } } createNode(buildContext, listOf(callback)) } @@ -201,10 +184,6 @@ class LoginFlowNode( navigateToMas(oAuthDetails) } - override fun navigateToCreateAccount(url: String) { - backstack.push(NavTarget.CreateAccount(url)) - } - override fun navigateToDeveloperSettings() { backstack.push(NavTarget.AppDeveloperSettings) } @@ -247,10 +226,6 @@ class LoginFlowNode( navigateToMas(oAuthDetails) } - override fun navigateToCreateAccount(url: String) { - backstack.push(NavTarget.CreateAccount(url)) - } - override fun navigateToLoginPassword() { backstack.push(NavTarget.LoginPassword()) } @@ -274,62 +249,18 @@ class LoginFlowNode( navigateToMas(oAuthDetails) } - override fun navigateToCreateAccount(url: String) { - backstack.push(NavTarget.CreateAccount(url)) - } - override fun navigateToLoginPassword() { backstack.push(NavTarget.LoginPassword()) } - - override fun navigateToChangeAccountProvider() { - backstack.push(NavTarget.ChangeAccountProvider) - } } createNode(buildContext, plugins = listOf(inputs, callback)) } - NavTarget.ChangeAccountProvider -> { - val callback = object : ChangeAccountProviderNode.Callback { - override fun onDone() { - // Go back to the Account Provider screen - val confirmAccountProvider = backstack.elements.value.firstOrNull { - it.key.navTarget is NavTarget.ConfirmAccountProvider - }?.key?.navTarget ?: NavTarget.ConfirmAccountProvider(isAccountCreation = false) - backstack.singleTop(confirmAccountProvider) - } - - override fun navigateToSearchAccountProvider() { - backstack.push(NavTarget.SearchAccountProvider) - } - } - - createNode(buildContext, plugins = listOf(callback)) - } - NavTarget.SearchAccountProvider -> { - val callback = object : SearchAccountProviderNode.Callback { - override fun onDone() { - // Go back to the Account Provider screen - val confirmAccountProvider = backstack.elements.value.firstOrNull { - it.key.navTarget is NavTarget.ConfirmAccountProvider - }?.key?.navTarget ?: NavTarget.ConfirmAccountProvider(isAccountCreation = false) - backstack.singleTop(confirmAccountProvider) - } - } - - createNode(buildContext, plugins = listOf(callback)) - } is NavTarget.LoginPassword -> { val inputs = LoginPasswordNode.Inputs( initialLogin = navTarget.initialLogin, ) createNode(buildContext, plugins = listOf(inputs)) } - is NavTarget.CreateAccount -> { - val inputs = CreateAccountNode.Inputs( - url = navTarget.url, - ) - createNode(buildContext, listOf(inputs)) - } } } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControl.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControl.kt index db56047e15..a3a475df2f 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControl.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControl.kt @@ -11,15 +11,14 @@ package io.element.android.features.login.impl.accesscontrol import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.features.enterprise.api.IsEnterpriseBuild import io.element.android.features.login.api.accesscontrol.AccountProviderAccessControl import io.element.android.features.login.impl.changeserver.AccountProviderAccessException -import io.element.android.libraries.core.uri.ensureProtocol -import io.element.android.libraries.wellknown.api.WellknownRetriever @ContributesBinding(AppScope::class) class DefaultAccountProviderAccessControl( + private val isEnterpriseBuild: IsEnterpriseBuild, private val enterpriseService: EnterpriseService, - private val wellknownRetriever: WellknownRetriever, ) : AccountProviderAccessControl { override suspend fun isAllowedToConnectToAccountProvider(accountProviderUrl: String) = try { assertIsAllowedToConnectToAccountProvider( @@ -36,12 +35,9 @@ class DefaultAccountProviderAccessControl( title: String, accountProviderUrl: String, ) { - if (enterpriseService.isEnterpriseBuild.not()) { + if (isEnterpriseBuild().not()) { // Ensure that Element Pro is not required for this account provider - val wellKnown = wellknownRetriever.getElementWellKnown( - baseUrl = accountProviderUrl.ensureProtocol(), - ).dataOrNull() - if (wellKnown?.enforceElementPro == true) { + if (enterpriseService.isElementProEnforced(accountProviderUrl)) { throw AccountProviderAccessException.NeedElementProException( unauthorisedAccountProviderTitle = title, applicationId = ELEMENT_PRO_APPLICATION_ID, @@ -51,7 +47,7 @@ class DefaultAccountProviderAccessControl( if (enterpriseService.isAllowedToConnectToHomeserver(accountProviderUrl).not()) { throw AccountProviderAccessException.UnauthorizedAccountProviderException( unauthorisedAccountProviderTitle = title, - authorisedAccountProviderTitles = enterpriseService.defaultHomeserverList(), + authorisedAccountProviderTitles = enterpriseService.homeserverAllowList(), ) } } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSource.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSource.kt index 931959d4ea..6d85f2c5ff 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSource.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSource.kt @@ -13,27 +13,64 @@ import dev.zacsweers.metro.Inject import dev.zacsweers.metro.SingleIn import io.element.android.appconfig.AuthenticationConfig import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.features.enterprise.api.canConnectToAnyHomeserver +import io.element.android.libraries.di.annotations.AppCoroutineScope +import io.element.android.libraries.preferences.api.store.AppPreferencesStore +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch @SingleIn(AppScope::class) @Inject class AccountProviderDataSource( - enterpriseService: EnterpriseService, + private val enterpriseService: EnterpriseService, + private val appPreferencesStore: AppPreferencesStore, + @AppCoroutineScope private val coroutineScope: CoroutineScope, ) { - private val defaultAccountProvider = createAccountProvider( - url = enterpriseService.defaultHomeserverList() + // The provider used when the user has not selected one: an enterprise/MDM-configured provider, + // else matrix.org. The most recently used provider (from history) can override it, see init. + private val configuredAccountProvider = createAccountProvider( + url = enterpriseService.homeserverAllowList() .firstOrNull { it != EnterpriseService.ANY_ACCOUNT_PROVIDER } ?: AuthenticationConfig.MATRIX_ORG_URL ) - private val accountProvider: MutableStateFlow = MutableStateFlow(defaultAccountProvider) + private val accountProvider: MutableStateFlow = MutableStateFlow(configuredAccountProvider) val flow: StateFlow = accountProvider.asStateFlow() + // The account provider the user last explicitly selected (via [setAccountProvider] / [setUrl]). + // Unlike [flow], this is not recomputed by [reset], so it survives to be persisted to history on a + // successful sign-in even when the login flow is torn down in between (e.g. across an OAuth round-trip). + var lastSelectedAccountProviderUrl: String? = null + private set + + init { + // Seed the default from the last used provider, unless the user has already selected one. + coroutineScope.launch { + val default = defaultAccountProvider() + accountProvider.update { current -> if (current == configuredAccountProvider) default else current } + } + } + suspend fun reset() { - accountProvider.emit(defaultAccountProvider) + accountProvider.emit(defaultAccountProvider()) + } + + /** + * The provider to default to: the most recently used one from history when the user is free to + * connect to any provider, otherwise the enterprise/MDM-configured provider. + */ + private suspend fun defaultAccountProvider(): AccountProvider { + if (!enterpriseService.canConnectToAnyHomeserver()) { + return configuredAccountProvider + } + val lastUsedProvider = appPreferencesStore.getHomeserverHistoryFlow().first().firstOrNull() + return lastUsedProvider?.let { createAccountProvider(it) } ?: configuredAccountProvider } suspend fun setUrl(url: String) { @@ -41,6 +78,7 @@ class AccountProviderDataSource( } suspend fun setAccountProvider(data: AccountProvider) { + lastSelectedAccountProviderUrl = data.url accountProvider.emit(data) } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderOtherView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderOtherView.kt deleted file mode 100644 index 8b9b22022e..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderOtherView.kt +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.accountprovider - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.unit.dp -import io.element.android.compound.theme.ElementTheme -import io.element.android.compound.tokens.generated.CompoundIcons -import io.element.android.features.login.impl.R -import io.element.android.libraries.designsystem.atomic.atoms.RoundedIconAtom -import io.element.android.libraries.designsystem.atomic.atoms.RoundedIconAtomSize -import io.element.android.libraries.designsystem.preview.ElementPreview -import io.element.android.libraries.designsystem.preview.PreviewsDayNight -import io.element.android.libraries.designsystem.theme.components.HorizontalDivider -import io.element.android.libraries.designsystem.theme.components.Text - -/** - * https://www.figma.com/file/o9p34zmiuEpZRyvZXJZAYL/FTUE?type=design&node-id=604-60817 - */ -@Composable -fun AccountProviderOtherView( - onClick: () -> Unit, - modifier: Modifier = Modifier, -) { - Column( - modifier = modifier - .fillMaxWidth() - .clickable(role = Role.Button) { onClick() } - ) { - HorizontalDivider() - Row( - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 44.dp) - .padding(vertical = 4.dp, horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically - ) { - RoundedIconAtom( - size = RoundedIconAtomSize.Medium, - imageVector = CompoundIcons.Search(), - tint = ElementTheme.colors.iconPrimary, - ) - Text( - modifier = Modifier - .padding(start = 16.dp) - .weight(1f), - text = stringResource(R.string.screen_change_account_provider_other), - style = ElementTheme.typography.fontBodyLgMedium, - color = ElementTheme.colors.textPrimary, - ) - } - } -} - -@PreviewsDayNight -@Composable -internal fun AccountProviderOtherViewPreview() = ElementPreview { - AccountProviderOtherView( - onClick = { }, - ) -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderPreviewParam.kt similarity index 93% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderPreviewParam.kt index 745939233f..c14827d1a6 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderPreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.login.impl.accountprovider import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.appconfig.AuthenticationConfig -open class AccountProviderProvider : PreviewParameterProvider { +open class AccountProviderPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAccountProvider(), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderView.kt index fcf4dac3b1..09b423f713 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderView.kt @@ -116,7 +116,7 @@ fun AccountProviderView( @PreviewsDayNight @Composable -internal fun AccountProviderViewPreview(@PreviewParameter(AccountProviderProvider::class) item: AccountProvider) = ElementPreview { +internal fun AccountProviderViewPreview(@PreviewParameter(AccountProviderPreviewParam::class) item: AccountProvider) = ElementPreview { AccountProviderView( item = item, onClick = { } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/SaveAccountProviderToHistory.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/SaveAccountProviderToHistory.kt new file mode 100644 index 0000000000..b3b99115cc --- /dev/null +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/accountprovider/SaveAccountProviderToHistory.kt @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.login.impl.accountprovider + +import dev.zacsweers.metro.Inject +import io.element.android.libraries.preferences.api.store.AppPreferencesStore + +/** + * Persist the account provider the user just authenticated against, so that it can be offered as + * the default (see [AccountProviderDataSource]) and as an autocomplete suggestion on the next + * sign-in. To be called from the manual sign-in / account creation flows only, on success. + * + * See [AppPreferencesStore.addHomeserverToHistory]. + */ +@Inject +class SaveAccountProviderToHistory( + private val accountProviderDataSource: AccountProviderDataSource, + private val appPreferencesStore: AppPreferencesStore, +) { + suspend operator fun invoke() { + // Persist the provider the user actually selected, not the currently-exposed default: the latter can be + // reset back to the history default while the login flow is torn down across an OAuth round-trip. + val url = accountProviderDataSource.lastSelectedAccountProviderUrl + ?: accountProviderDataSource.flow.value.url + appPreferencesStore.addHomeserverToHistory(url) + } +} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenter.kt index 79f76d5fb5..b7b04beeb2 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenter.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenter.kt @@ -22,6 +22,7 @@ import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.architecture.runCatchingUpdatingState import io.element.android.libraries.matrix.api.auth.MatrixAuthenticationService +import io.element.android.libraries.matrix.api.auth.MatrixHomeServerDetails @Inject class ChangeServerPresenter( @@ -32,7 +33,7 @@ class ChangeServerPresenter( ) : Presenter { @Composable override fun present(): ChangeServerState { - val changeServerAction: MutableState> = remember { + val changeServerAction: MutableState> = remember { mutableStateOf(AsyncData.Uninitialized) } @@ -59,7 +60,7 @@ class ChangeServerPresenter( private suspend fun changeServer( data: AccountProvider, - changeServerAction: MutableState>, + changeServerAction: MutableState>, ) { suspend { defaultAccountProviderAccessControl.assertIsAllowedToConnectToAccountProvider( @@ -72,6 +73,8 @@ class ChangeServerPresenter( } // Homeserver is valid, remember user choice accountProviderDataSource.setAccountProvider(data) + // Return the resolved details so the caller can sign in without configuring the homeserver again. + details }.runCatchingUpdatingState(changeServerAction, errorTransform = ChangeServerError::from) } } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerState.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerState.kt index 6d8ce25d75..3b4f4d9dad 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerState.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerState.kt @@ -9,10 +9,13 @@ package io.element.android.features.login.impl.changeserver import io.element.android.libraries.architecture.AsyncData +import io.element.android.libraries.matrix.api.auth.MatrixHomeServerDetails import io.element.android.libraries.permissions.api.localnetwork.LocalNetworkPermissionDialog data class ChangeServerState( - val changeServerAction: AsyncData, + // On success, carries the resolved homeserver details so the caller can proceed with login without + // configuring (and re-networking) the homeserver a second time. + val changeServerAction: AsyncData, val localNetworkPermissionDialog: LocalNetworkPermissionDialog, val eventSink: (ChangeServerEvents) -> Unit ) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerStatePreviewParam.kt similarity index 89% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerStatePreviewParam.kt index 183158bceb..2654953ece 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerStatePreviewParam.kt @@ -11,9 +11,10 @@ package io.element.android.features.login.impl.changeserver import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.login.impl.error.ChangeServerError import io.element.android.libraries.architecture.AsyncData +import io.element.android.libraries.matrix.api.auth.MatrixHomeServerDetails import io.element.android.libraries.permissions.api.localnetwork.LocalNetworkPermissionDialog -open class ChangeServerStateProvider : PreviewParameterProvider { +open class ChangeServerStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aChangeServerState(), @@ -45,7 +46,7 @@ open class ChangeServerStateProvider : PreviewParameterProvider = AsyncData.Uninitialized, + changeServerAction: AsyncData = AsyncData.Uninitialized, localNetworkPermissionDialog: LocalNetworkPermissionDialog = LocalNetworkPermissionDialog.None, ) = ChangeServerState( changeServerAction = changeServerAction, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerView.kt index 30ae644a70..8e726c7fe1 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerView.kt @@ -135,7 +135,7 @@ fun ChangeServerView( @PreviewsDayNight @Composable -internal fun ChangeServerViewPreview(@PreviewParameter(ChangeServerStateProvider::class) state: ChangeServerState) = ElementPreview { +internal fun ChangeServerViewPreview(@PreviewParameter(ChangeServerStatePreviewParam::class) state: ChangeServerState) = ElementPreview { ChangeServerView( state = state, onLearnMoreClick = {}, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/di/LoginModule.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/di/LoginBindingContainer.kt similarity index 96% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/di/LoginModule.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/di/LoginBindingContainer.kt index 037acf859b..257587770f 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/di/LoginModule.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/di/LoginBindingContainer.kt @@ -20,7 +20,7 @@ import io.element.android.libraries.architecture.Presenter @ContributesTo(AppScope::class) @BindingContainer -interface LoginModule { +interface LoginBindingContainer { @Binds fun bindChangeServerPresenter(presenter: ChangeServerPresenter): Presenter diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/error/ChangeServerErrorProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/error/ChangeServerErrorPreviewParam.kt similarity index 92% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/error/ChangeServerErrorProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/error/ChangeServerErrorPreviewParam.kt index 59fb42fe0c..76c8b18409 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/error/ChangeServerErrorProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/error/ChangeServerErrorPreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.login.impl.error import androidx.compose.ui.tooling.preview.PreviewParameterProvider -class ChangeServerErrorProvider : PreviewParameterProvider { +class ChangeServerErrorPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( ChangeServerError.InvalidServer, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeEvent.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeEvent.kt index 73400890d5..945b0bc580 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeEvent.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeEvent.kt @@ -7,12 +7,18 @@ package io.element.android.features.login.impl.login +import io.element.android.libraries.matrix.api.auth.MatrixHomeServerDetails + sealed interface LoginModeEvent { data class Submit( val isAccountCreation: Boolean, val homeserverUrl: String, val resolvedHomeserverUrl: String?, val loginHint: String?, + // When the caller has already configured the homeserver (e.g. the account provider screen validated + // it first), these are its resolved details. When set, login reuses them instead of calling + // setHomeserver again, avoiding a redundant network round-trip. + val preConfiguredDetails: MatrixHomeServerDetails? = null, ) : LoginModeEvent data object ClearError : LoginModeEvent diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModePresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModePresenter.kt index 34188095b0..59d156308f 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModePresenter.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModePresenter.kt @@ -13,6 +13,7 @@ import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import dev.zacsweers.metro.Inject +import io.element.android.features.login.impl.accountprovider.SaveAccountProviderToHistory import io.element.android.features.login.impl.error.ChangeServerError import io.element.android.features.login.impl.localnetwork.LocalNetworkPermissionGate import io.element.android.features.login.impl.screens.chooseaccountprovider.ChooseAccountProviderPresenter @@ -20,7 +21,6 @@ import io.element.android.features.login.impl.screens.classic.loginwithclassic.L import io.element.android.features.login.impl.screens.confirmaccountprovider.ConfirmAccountProviderPresenter import io.element.android.features.login.impl.screens.createaccount.AccountCreationNotSupported import io.element.android.features.login.impl.screens.onboarding.OnBoardingPresenter -import io.element.android.features.login.impl.web.WebClientUrlForAuthenticationRetriever import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.architecture.runCatchingUpdatingState @@ -39,8 +39,8 @@ import io.element.android.libraries.oauth.api.OAuthActionFlow class LoginModePresenter( private val oAuthActionFlow: OAuthActionFlow, private val authenticationService: MatrixAuthenticationService, - private val webClientUrlForAuthenticationRetriever: WebClientUrlForAuthenticationRetriever, private val localNetworkPermissionGate: LocalNetworkPermissionGate, + private val saveAccountProviderToHistory: SaveAccountProviderToHistory, ) : Presenter { @Composable override fun present(): LoginModeState { @@ -75,28 +75,28 @@ class LoginModePresenter( private suspend fun performSubmit(request: LoginModeEvent.Submit, loginMode: MutableState>) { suspend { - authenticationService.setHomeserver(request.homeserverUrl).recoverCatching { - // Fallback to the well-known-resolved URL if the primary URL failed and the caller supplied one. - if (request.resolvedHomeserverUrl != null && request.resolvedHomeserverUrl != request.homeserverUrl) { - authenticationService.setHomeserver(request.resolvedHomeserverUrl).getOrThrow() - } else { - throw it - } - }.map { matrixHomeServerDetails -> - when { - matrixHomeServerDetails.supportsOAuthLogin -> { - val oAuthPrompt = if (request.isAccountCreation) OAuthPrompt.Create else OAuthPrompt.Login - LoginMode.OAuth( - authenticationService.getOAuthUrl(prompt = oAuthPrompt, loginHint = request.loginHint).getOrThrow() - ) + // Reuse the details the caller already resolved when it configured the homeserver, so we don't + // run setHomeserver (a network round-trip) again. Otherwise configure the homeserver ourselves. + val matrixHomeServerDetails = request.preConfiguredDetails + ?: authenticationService.setHomeserver(request.homeserverUrl).recoverCatching { + // Fallback to the well-known-resolved URL if the primary URL failed and the caller supplied one. + if (request.resolvedHomeserverUrl != null && request.resolvedHomeserverUrl != request.homeserverUrl) { + authenticationService.setHomeserver(request.resolvedHomeserverUrl).getOrThrow() + } else { + throw it } - request.isAccountCreation -> LoginMode.AccountCreation( - webClientUrlForAuthenticationRetriever.retrieve(request.homeserverUrl) + }.getOrThrow() + when { + matrixHomeServerDetails.supportsOAuthLogin -> { + val oAuthPrompt = if (request.isAccountCreation) OAuthPrompt.Create else OAuthPrompt.Login + LoginMode.OAuth( + authenticationService.getOAuthUrl(prompt = oAuthPrompt, loginHint = request.loginHint).getOrThrow() ) - matrixHomeServerDetails.supportsPasswordLogin -> LoginMode.PasswordLogin - else -> error("Unsupported login flow") } - }.getOrThrow() + request.isAccountCreation -> throw AccountCreationNotSupported() + matrixHomeServerDetails.supportsPasswordLogin -> LoginMode.PasswordLogin + else -> error("Unsupported authentication flow") + } }.runCatchingUpdatingState( state = loginMode, errorTransform = { @@ -120,6 +120,7 @@ class LoginModePresenter( .onSuccess { loginMode.value = AsyncData.Uninitialized } .onFailure { loginMode.value = AsyncData.Failure(it) } is OAuthAction.Success -> authenticationService.loginWithOAuth(action.url) + .onSuccess { saveAccountProviderToHistory() } .onFailure { loginMode.value = AsyncData.Failure(it) } } oAuthActionFlow.reset() diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeState.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeState.kt index 849ff31f85..86dd550ea6 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeState.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeState.kt @@ -20,5 +20,4 @@ data class LoginModeState( sealed interface LoginMode { data object PasswordLogin : LoginMode data class OAuth(val oAuthDetails: OAuthDetails) : LoginMode - data class AccountCreation(val url: String) : LoginMode } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeView.kt index 3549e17457..80784d2b13 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeView.kt @@ -34,7 +34,6 @@ fun LoginModeView( onLearnMoreClick: () -> Unit, onOAuthDetails: (OAuthDetails) -> Unit, onNeedLoginPassword: () -> Unit, - onCreateAccountContinue: (url: String) -> Unit ) { val context = LocalContext.current when (loginMode) { @@ -120,7 +119,6 @@ fun LoginModeView( when (val loginModeData = loginMode.data) { is LoginMode.OAuth -> onOAuthDetails(loginModeData.oAuthDetails) LoginMode.PasswordLogin -> onNeedLoginPassword() - is LoginMode.AccountCreation -> onCreateAccountContinue(loginModeData.url) } // Also clear the data, to let the next screen be able to go back onClearError() @@ -131,7 +129,7 @@ fun LoginModeView( @PreviewsDayNight @Composable -internal fun LoginModeViewPreview(@PreviewParameter(LoginModeViewErrorProvider::class) error: Throwable) { +internal fun LoginModeViewPreview(@PreviewParameter(LoginModeViewErrorPreviewParam::class) error: Throwable) { ElementPreview { LoginModeView( loginMode = AsyncData.Failure(error), @@ -139,7 +137,6 @@ internal fun LoginModeViewPreview(@PreviewParameter(LoginModeViewErrorProvider:: onLearnMoreClick = {}, onOAuthDetails = {}, onNeedLoginPassword = {}, - onCreateAccountContinue = {} ) } } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeViewErrorProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeViewErrorPreviewParam.kt similarity index 80% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeViewErrorProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeViewErrorPreviewParam.kt index 513d0a8a04..4706beefbb 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeViewErrorProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/login/LoginModeViewErrorPreviewParam.kt @@ -9,11 +9,11 @@ package io.element.android.features.login.impl.login import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import io.element.android.features.login.impl.error.ChangeServerErrorProvider +import io.element.android.features.login.impl.error.ChangeServerErrorPreviewParam import io.element.android.libraries.matrix.api.auth.AuthenticationException -class LoginModeViewErrorProvider : PreviewParameterProvider { +class LoginModeViewErrorPreviewParam : PreviewParameterProvider { override val values: Sequence - get() = ChangeServerErrorProvider().values + + get() = ChangeServerErrorPreviewParam().values + AuthenticationException.AccountAlreadyLoggedIn("@alice:matrix.org") } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/resolver/HomeserverData.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/resolver/HomeserverData.kt deleted file mode 100644 index d9994deb9a..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/resolver/HomeserverData.kt +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.resolver - -data class HomeserverData( - // The computed homeserver url, for which a wellknown file has been retrieved, or just a valid Url - val homeserverUrl: String, -) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/resolver/HomeserverResolver.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/resolver/HomeserverResolver.kt deleted file mode 100644 index 8c6cab79ce..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/resolver/HomeserverResolver.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.resolver - -import dev.zacsweers.metro.Inject -import io.element.android.libraries.core.coroutine.CoroutineDispatchers -import io.element.android.libraries.core.coroutine.parallelMap -import io.element.android.libraries.core.uri.ensureProtocol -import io.element.android.libraries.core.uri.isValidUrl -import io.element.android.libraries.matrix.api.auth.HomeServerLoginCompatibilityChecker -import io.element.android.libraries.permissions.api.localnetwork.LocalNetworkPermissionAdvisor -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.withContext -import timber.log.Timber -import java.util.Collections - -/** - * Resolve homeserver base on search terms. - */ -@Inject -class HomeserverResolver( - private val dispatchers: CoroutineDispatchers, - private val homeServerLoginCompatibilityChecker: HomeServerLoginCompatibilityChecker, - private val localNetworkPermissionAdvisor: LocalNetworkPermissionAdvisor, -) { - fun resolve(userInput: String): Flow> = flow { - val flowContext = currentCoroutineContext() - val trimmedUserInput = userInput.trim() - if (trimmedUserInput.length < 4) return@flow - val candidateBase = trimmedUserInput.ensureProtocol().removeSuffix("/") - val list = getUrlCandidates(candidateBase) - val currentList = Collections.synchronizedList(mutableListOf()) - // Run all the requests in parallel - withContext(dispatchers.io) { - list.parallelMap { url -> - // Skip the compatibility probe if we'd need ACCESS_LOCAL_NETWORK first — - // otherwise the probe hangs on the TCP timeout for ~30s. Emit the URL as a - // candidate directly; the actual sign-in flow triggers the permission prompt. - val shouldRequestPermissionOrIsValid = localNetworkPermissionAdvisor.shouldRequestPermissionFor(url) || - homeServerLoginCompatibilityChecker.check(url) - .onFailure { Timber.w(it, "Failed to check compatibility with homeserver $url") } - .getOrNull() - ?: return@parallelMap - - // Emit the list as soon as possible - if (shouldRequestPermissionOrIsValid) { - currentList.add(HomeserverData(homeserverUrl = url)) - withContext(flowContext) { - emit(currentList.toList()) - } - } - } - } - // If list is empty, and candidateBase is a valid an URL, do not block the user. - // A unsupported homeserver / homeserver not found error will be displayed if the user continues - if (currentList.isEmpty() && candidateBase.isValidUrl()) { - emit(listOf(HomeserverData(homeserverUrl = candidateBase))) - } - } - - private fun getUrlCandidates(data: String): List { - return buildList { - if (data.contains(".")) { - // TLD detected? - } else { - add("$data.org") - add("$data.com") - add("$data.io") - } - // Always try what the user has entered - add(data) - } - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderNode.kt deleted file mode 100644 index 018a25dc89..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderNode.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.changeaccountprovider - -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import com.bumble.appyx.core.modality.BuildContext -import com.bumble.appyx.core.node.Node -import com.bumble.appyx.core.plugin.Plugin -import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.Assisted -import dev.zacsweers.metro.AssistedInject -import io.element.android.annotations.ContributesNode -import io.element.android.features.login.impl.util.openLearnMorePage -import io.element.android.libraries.architecture.callback - -@ContributesNode(AppScope::class) -@AssistedInject -class ChangeAccountProviderNode( - @Assisted buildContext: BuildContext, - @Assisted plugins: List, - private val presenter: ChangeAccountProviderPresenter, -) : Node(buildContext, plugins = plugins) { - interface Callback : Plugin { - fun onDone() - fun navigateToSearchAccountProvider() - } - - private val callback: Callback = callback() - - @Composable - override fun View(modifier: Modifier) { - val state = presenter.present() - val context = LocalContext.current - ChangeAccountProviderView( - state = state, - modifier = modifier, - onBackClick = ::navigateUp, - onLearnMoreClick = { openLearnMorePage(context) }, - onSuccess = callback::onDone, - onOtherProviderClick = callback::navigateToSearchAccountProvider, - ) - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderPresenter.kt deleted file mode 100644 index 41605352ef..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderPresenter.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.changeaccountprovider - -import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember -import dev.zacsweers.metro.Inject -import io.element.android.appconfig.AuthenticationConfig -import io.element.android.features.enterprise.api.EnterpriseService -import io.element.android.features.enterprise.api.canConnectToAnyHomeserver -import io.element.android.features.login.impl.accountprovider.AccountProvider -import io.element.android.features.login.impl.changeserver.ChangeServerState -import io.element.android.libraries.architecture.Presenter -import io.element.android.libraries.core.uri.ensureProtocol -import kotlinx.collections.immutable.toImmutableList - -@Inject -class ChangeAccountProviderPresenter( - private val changeServerPresenter: Presenter, - private val enterpriseService: EnterpriseService, -) : Presenter { - @Composable - override fun present(): ChangeAccountProviderState { - val staticAccountProviderList = remember { - enterpriseService.defaultHomeserverList() - .filter { it != EnterpriseService.ANY_ACCOUNT_PROVIDER } - .map { it.ensureProtocol() } - .ifEmpty { listOf(AuthenticationConfig.MATRIX_ORG_URL) } - .map { url -> - AccountProvider( - url = url, - subtitle = null, - isPublic = url == AuthenticationConfig.MATRIX_ORG_URL, - isMatrixOrg = url == AuthenticationConfig.MATRIX_ORG_URL, - ) - } - .toImmutableList() - } - - val canSearchForAccountProviders = remember { - enterpriseService.canConnectToAnyHomeserver() - } - - val changeServerState = changeServerPresenter.present() - return ChangeAccountProviderState( - accountProviders = staticAccountProviderList, - canSearchForAccountProviders = canSearchForAccountProviders, - changeServerState = changeServerState, - ) - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderState.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderState.kt deleted file mode 100644 index 3068a1cb57..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderState.kt +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.changeaccountprovider - -import io.element.android.features.login.impl.accountprovider.AccountProvider -import io.element.android.features.login.impl.changeserver.ChangeServerState -import kotlinx.collections.immutable.ImmutableList - -data class ChangeAccountProviderState( - val accountProviders: ImmutableList, - val canSearchForAccountProviders: Boolean, - val changeServerState: ChangeServerState, -) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderStateProvider.kt deleted file mode 100644 index 5cec1961a4..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderStateProvider.kt +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.changeaccountprovider - -import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import io.element.android.features.login.impl.accountprovider.AccountProvider -import io.element.android.features.login.impl.accountprovider.anAccountProvider -import io.element.android.features.login.impl.changeserver.ChangeServerState -import io.element.android.features.login.impl.changeserver.aChangeServerState -import kotlinx.collections.immutable.toImmutableList - -open class ChangeAccountProviderStateProvider : PreviewParameterProvider { - override val values: Sequence - get() = sequenceOf( - aChangeAccountProviderState(), - aChangeAccountProviderState(canSearchForAccountProviders = false), - // Add other state here - ) -} - -fun aChangeAccountProviderState( - accountProviders: List = listOf( - anAccountProvider() - ), - canSearchForAccountProviders: Boolean = true, - changeServerState: ChangeServerState = aChangeServerState(), -) = ChangeAccountProviderState( - accountProviders = accountProviders.toImmutableList(), - canSearchForAccountProviders = canSearchForAccountProviders, - changeServerState = changeServerState, -) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderView.kt deleted file mode 100644 index 212bab515d..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderView.kt +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -@file:OptIn(ExperimentalMaterial3Api::class) - -package io.element.android.features.login.impl.screens.changeaccountprovider - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.consumeWindowInsets -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.tooling.preview.PreviewParameter -import androidx.compose.ui.unit.dp -import io.element.android.compound.tokens.generated.CompoundIcons -import io.element.android.features.login.impl.R -import io.element.android.features.login.impl.accountprovider.AccountProviderOtherView -import io.element.android.features.login.impl.accountprovider.AccountProviderView -import io.element.android.features.login.impl.changeserver.ChangeServerEvents -import io.element.android.features.login.impl.changeserver.ChangeServerView -import io.element.android.libraries.designsystem.atomic.molecules.IconTitleSubtitleMolecule -import io.element.android.libraries.designsystem.components.BigIcon -import io.element.android.libraries.designsystem.components.button.BackButton -import io.element.android.libraries.designsystem.preview.ElementPreview -import io.element.android.libraries.designsystem.preview.PreviewsDayNight -import io.element.android.libraries.designsystem.theme.components.Scaffold -import io.element.android.libraries.designsystem.theme.components.TopAppBar -import io.element.android.libraries.designsystem.utils.lazyColumnContentPadding -import io.element.android.libraries.designsystem.utils.scaffoldScrollableContentInsets - -/** - * https://www.figma.com/file/o9p34zmiuEpZRyvZXJZAYL/FTUE?type=design&node-id=604-60817 - */ -@Composable -fun ChangeAccountProviderView( - state: ChangeAccountProviderState, - onBackClick: () -> Unit, - onLearnMoreClick: () -> Unit, - onSuccess: () -> Unit, - onOtherProviderClick: () -> Unit, - modifier: Modifier = Modifier, -) { - Scaffold( - modifier = modifier, - topBar = { - TopAppBar( - title = {}, - navigationIcon = { BackButton(onClick = onBackClick) } - ) - }, - contentWindowInsets = scaffoldScrollableContentInsets, - ) { padding -> - Box( - modifier = Modifier - .fillMaxSize() - .imePadding() - .padding(padding) - .consumeWindowInsets(padding) - ) { - Column( - modifier = Modifier - .verticalScroll(state = rememberScrollState()) - .padding(lazyColumnContentPadding) - ) { - IconTitleSubtitleMolecule( - modifier = Modifier.padding(top = 16.dp, bottom = 32.dp, start = 16.dp, end = 16.dp), - iconStyle = BigIcon.Style.Default(CompoundIcons.HomeSolid()), - title = stringResource(id = R.string.screen_change_account_provider_title), - subTitle = stringResource(id = R.string.screen_change_account_provider_subtitle), - ) - - state.accountProviders.forEach { item -> - val alteredItem = if (item.isMatrixOrg) { - // Set the subtitle from the resource - item.copy( - subtitle = stringResource(id = R.string.screen_change_account_provider_matrix_org_subtitle), - ) - } else { - item - } - AccountProviderView( - item = alteredItem, - onClick = { - state.changeServerState.eventSink.invoke(ChangeServerEvents.ChangeServer(alteredItem)) - } - ) - } - // Other - if (state.canSearchForAccountProviders) { - AccountProviderOtherView( - onClick = onOtherProviderClick - ) - } - Spacer(Modifier.height(32.dp)) - } - ChangeServerView( - state = state.changeServerState, - onLearnMoreClick = onLearnMoreClick, - onSuccess = onSuccess, - ) - } - } -} - -@PreviewsDayNight -@Composable -internal fun ChangeAccountProviderViewPreview(@PreviewParameter(ChangeAccountProviderStateProvider::class) state: ChangeAccountProviderState) = ElementPreview { - ChangeAccountProviderView( - state = state, - onBackClick = { }, - onLearnMoreClick = { }, - onSuccess = { }, - onOtherProviderClick = { }, - ) -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderNode.kt index 5f79f197d9..6432042818 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderNode.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderNode.kt @@ -32,7 +32,6 @@ class ChooseAccountProviderNode( interface Callback : Plugin { fun navigateToLoginPassword() fun navigateToOAuth(oAuthDetails: OAuthDetails) - fun navigateToCreateAccount(url: String) } private val callback: Callback = callback() @@ -48,7 +47,6 @@ class ChooseAccountProviderNode( onOAuthDetails = callback::navigateToOAuth, onNeedLoginPassword = callback::navigateToLoginPassword, onLearnMoreClick = { openLearnMorePage(context) }, - onCreateAccountContinue = callback::navigateToCreateAccount, ) } } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderPresenter.kt index a9983a19d1..92c3ff0fff 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderPresenter.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderPresenter.kt @@ -60,7 +60,7 @@ class ChooseAccountProviderPresenter( val staticAccountProviderList = remember { // The list cannot contains ANY_ACCOUNT_PROVIDER ("*") and cannot be empty at this point - enterpriseService.defaultHomeserverList() + enterpriseService.homeserverAllowList() .map { it.ensureProtocol() } .map { url -> AccountProvider( diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderStatePreviewParam.kt similarity index 96% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderStatePreviewParam.kt index 3fea548fca..207f434b42 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.features.login.impl.login.aLoginModeState import io.element.android.libraries.architecture.AsyncData import kotlinx.collections.immutable.toImmutableList -open class ChooseAccountProviderStateProvider : PreviewParameterProvider { +open class ChooseAccountProviderStatePreviewParam : PreviewParameterProvider { private val server1 = anAccountProvider( url = "https://server1.io", subtitle = null, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderView.kt index e858789bb4..fdc69ca295 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderView.kt @@ -57,7 +57,6 @@ fun ChooseAccountProviderView( onOAuthDetails: (OAuthDetails) -> Unit, onNeedLoginPassword: () -> Unit, onLearnMoreClick: () -> Unit, - onCreateAccountContinue: (url: String) -> Unit, modifier: Modifier = Modifier, ) { val isLoading by remember(state.loginModeState.loginMode) { @@ -137,7 +136,6 @@ fun ChooseAccountProviderView( onLearnMoreClick = onLearnMoreClick, onOAuthDetails = onOAuthDetails, onNeedLoginPassword = onNeedLoginPassword, - onCreateAccountContinue = onCreateAccountContinue, ) } } @@ -154,13 +152,14 @@ fun ChooseAccountProviderView( @PreviewsDayNight @Composable -internal fun ChooseAccountProviderViewPreview(@PreviewParameter(ChooseAccountProviderStateProvider::class) state: ChooseAccountProviderState) = ElementPreview { +internal fun ChooseAccountProviderViewPreview(@PreviewParameter( + ChooseAccountProviderStatePreviewParam::class +) state: ChooseAccountProviderState) = ElementPreview { ChooseAccountProviderView( state = state, onBackClick = { }, onLearnMoreClick = { }, onOAuthDetails = { }, onNeedLoginPassword = { }, - onCreateAccountContinue = { }, ) } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/ClassicFlowNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/ClassicFlowNode.kt index cfbd86f363..160b500cf6 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/ClassicFlowNode.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/ClassicFlowNode.kt @@ -55,7 +55,6 @@ class ClassicFlowNode( fun navigateToOnBoarding(allowBackNavigation: Boolean) fun navigateToLoginPassword() fun navigateToOAuth(oAuthDetails: OAuthDetails) - fun navigateToCreateAccount(url: String) } sealed interface NavTarget : Parcelable { @@ -115,10 +114,6 @@ class ClassicFlowNode( callback.navigateToOAuth(oAuthDetails) } - override fun navigateToCreateAccount(url: String) { - callback.navigateToCreateAccount(url) - } - override fun navigateToMissingKeyBackup() { backstack.push(NavTarget.MissingKeyBackup) } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicNode.kt index d5acca38ae..ff56b0e8e8 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicNode.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicNode.kt @@ -36,7 +36,6 @@ class LoginWithClassicNode( fun navigateToOtherOptions() fun navigateToLoginPassword() fun navigateToOAuth(oAuthDetails: OAuthDetails) - fun navigateToCreateAccount(url: String) fun navigateToMissingKeyBackup() } @@ -63,7 +62,6 @@ class LoginWithClassicNode( onOAuthDetails = callback::navigateToOAuth, onNeedLoginPassword = callback::navigateToLoginPassword, onLearnMoreClick = { openLearnMorePage(context) }, - onCreateAccountContinue = callback::navigateToCreateAccount, ) } } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicStatePreviewParam.kt similarity index 94% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicStatePreviewParam.kt index 6dfc292f6f..056d3d704a 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.designsystem.preview.USER_NAME_ALICE import io.element.android.libraries.matrix.api.core.UserId -open class LoginWithClassicStateProvider : PreviewParameterProvider { +open class LoginWithClassicStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLoginWithClassicState(), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicView.kt index 75181a068e..845c8ec8ee 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicView.kt @@ -64,7 +64,6 @@ fun LoginWithClassicView( onOAuthDetails: (OAuthDetails) -> Unit, onNeedLoginPassword: () -> Unit, onLearnMoreClick: () -> Unit, - onCreateAccountContinue: (url: String) -> Unit, modifier: Modifier = Modifier, ) { val isLoading by remember(state.loginModeState.loginMode) { @@ -204,7 +203,6 @@ fun LoginWithClassicView( onLearnMoreClick = onLearnMoreClick, onOAuthDetails = onOAuthDetails, onNeedLoginPassword = onNeedLoginPassword, - onCreateAccountContinue = onCreateAccountContinue, ) LocalNetworkPermissionDialogView( dialog = state.loginModeState.localNetworkPermissionDialog, @@ -219,13 +217,12 @@ fun LoginWithClassicView( @PreviewsDayNight @Composable -internal fun LoginWithClassicViewPreview(@PreviewParameter(LoginWithClassicStateProvider::class) state: LoginWithClassicState) = ElementPreview { +internal fun LoginWithClassicViewPreview(@PreviewParameter(LoginWithClassicStatePreviewParam::class) state: LoginWithClassicState) = ElementPreview { LoginWithClassicView( state = state, onOtherOptionsClick = {}, onOAuthDetails = {}, onNeedLoginPassword = {}, onLearnMoreClick = {}, - onCreateAccountContinue = {}, ) } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupStatePreviewParam.kt similarity index 86% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupStatePreviewParam.kt index 2c6a09b3ed..08d26bcee1 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupStatePreviewParam.kt @@ -9,7 +9,7 @@ package io.element.android.features.login.impl.screens.classic.missingkeybackup import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class MissingKeyBackupStateProvider : PreviewParameterProvider { +open class MissingKeyBackupStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMissingKeyBackupState(), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupView.kt index c4c9c5f286..9297fc4a51 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/classic/missingkeybackup/MissingKeyBackupView.kt @@ -76,7 +76,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable -internal fun MissingKeyBackupViewPreview(@PreviewParameter(MissingKeyBackupStateProvider::class) state: MissingKeyBackupState) = ElementPreview { +internal fun MissingKeyBackupViewPreview(@PreviewParameter(MissingKeyBackupStatePreviewParam::class) state: MissingKeyBackupState) = ElementPreview { MissingKeyBackupView( state = state, onBackClick = {}, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderEvents.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderEvents.kt index d66606b22c..9093a8121f 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderEvents.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderEvents.kt @@ -9,6 +9,10 @@ package io.element.android.features.login.impl.screens.confirmaccountprovider sealed interface ConfirmAccountProviderEvents { - data object Continue : ConfirmAccountProviderEvents + data class UserInputChanged(val accountProvider: String) : ConfirmAccountProviderEvents + + // Carries the account provider to submit (the current field text, or the accepted autocomplete suggestion), + // captured from the view at click time so it can't lag behind fast input (e.g. keyboard autofill). + data class Continue(val accountProvider: String) : ConfirmAccountProviderEvents data object ClearError : ConfirmAccountProviderEvents } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderNode.kt index 928a493dc1..e1a2d85412 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderNode.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderNode.kt @@ -45,8 +45,6 @@ class ConfirmAccountProviderNode( interface Callback : Plugin { fun navigateToLoginPassword() fun navigateToOAuth(oAuthDetails: OAuthDetails) - fun navigateToCreateAccount(url: String) - fun navigateToChangeAccountProvider() } private val callback: Callback = callback() @@ -60,8 +58,6 @@ class ConfirmAccountProviderNode( modifier = modifier, onOAuthDetails = callback::navigateToOAuth, onNeedLoginPassword = callback::navigateToLoginPassword, - onCreateAccountContinue = callback::navigateToCreateAccount, - onChange = callback::navigateToChangeAccountProvider, onLearnMoreClick = { openLearnMorePage(context) }, ) } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenter.kt index 0111b1e7d7..5c66f8f446 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenter.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenter.kt @@ -9,21 +9,38 @@ package io.element.android.features.login.impl.screens.confirmaccountprovider import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedFactory import dev.zacsweers.metro.AssistedInject +import io.element.android.appconfig.AuthenticationConfig +import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.features.login.impl.accountprovider.AccountProvider import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.changeserver.ChangeServerEvents +import io.element.android.features.login.impl.changeserver.ChangeServerState import io.element.android.features.login.impl.login.LoginModeEvent import io.element.android.features.login.impl.login.LoginModeState import io.element.android.libraries.architecture.Presenter +import io.element.android.libraries.core.uri.ensureProtocol +import io.element.android.libraries.matrix.api.core.MatrixPatterns +import io.element.android.libraries.preferences.api.store.AppPreferencesStore @AssistedInject class ConfirmAccountProviderPresenter( @Assisted private val params: Params, private val accountProviderDataSource: AccountProviderDataSource, private val loginModePresenter: Presenter, + private val changeServerPresenter: Presenter, + private val appPreferencesStore: AppPreferencesStore, + private val enterpriseService: EnterpriseService, ) : Presenter { data class Params( val isAccountCreation: Boolean, @@ -38,26 +55,108 @@ class ConfirmAccountProviderPresenter( override fun present(): ConfirmAccountProviderState { val accountProvider by accountProviderDataSource.flow.collectAsState() val loginModeState = loginModePresenter.present() + val changeServerState = changeServerPresenter.present() + val homeserverHistory by appPreferencesStore.getHomeserverHistoryFlow().collectAsState(emptyList()) + + // The account providers offered for autocomplete: previously-used ones first, then the + // enterprise/MDM-configured allow-list, then matrix.org (always available, even before any sign-in). + // The "*" wildcard is a routing marker, not a real provider, so it is filtered out. Everything is + // rendered without the https:// scheme (added back at connection time). + val autocompleteCandidates = remember(homeserverHistory) { + (homeserverHistory + enterpriseService.homeserverAllowList() + AuthenticationConfig.MATRIX_ORG_URL) + .filter { it != EnterpriseService.ANY_ACCOUNT_PROVIDER } + .map { it.withoutScheme() } + .distinct() + } + + // Editable input, seeded from the current (history-defaulted) account provider until the user edits it. + // Displayed without the scheme, so the field shows e.g. "matrix.org" rather than "https://matrix.org". + var userInput by rememberSaveable { mutableStateOf(null) } + val accountProviderInput = userInput ?: accountProvider.url.withoutScheme() + + // Offer the first candidate that the current input is a (case-insensitive) prefix of. + val accountProviderSuggestion = remember(accountProviderInput, autocompleteCandidates) { + val input = accountProviderInput.trim() + input.takeIf { it.isNotEmpty() } + ?.let { prefix -> + autocompleteCandidates.firstOrNull { it.length > prefix.length && it.startsWith(prefix, ignoreCase = true) } + } + } + + // The account provider submitted via Continue (carried by the event, so it reflects the exact field + // text at click time); used to actually sign in once validation succeeds. + var submittedAccountProvider by remember { mutableStateOf(null) } + val latestSubmittedAccountProvider by rememberUpdatedState(submittedAccountProvider) + + // A login hint (the full Matrix user ID) captured when the user enters one, so the authentication + // server can pre-fill their identity. Null when a plain account provider was entered. + var submittedLoginHint by remember { mutableStateOf(null) } + val latestSubmittedLoginHint by rememberUpdatedState(submittedLoginHint) + + // Once the chosen account provider has been validated and persisted, proceed with the actual sign in / sign up. + // Reuse the details resolved while validating, so login does not configure (and re-network) the homeserver again. + LaunchedEffect(changeServerState.changeServerAction) { + val homeServerDetails = changeServerState.changeServerAction.dataOrNull() + if (homeServerDetails != null) { + loginModeState.eventSink( + LoginModeEvent.Submit( + isAccountCreation = params.isAccountCreation, + homeserverUrl = latestSubmittedAccountProvider.orEmpty().trim(), + resolvedHomeserverUrl = null, + loginHint = latestSubmittedLoginHint, + preConfiguredDetails = homeServerDetails, + ) + ) + } + } fun handleEvent(event: ConfirmAccountProviderEvents) { when (event) { - ConfirmAccountProviderEvents.Continue -> loginModeState.eventSink( - LoginModeEvent.Submit( - isAccountCreation = params.isAccountCreation, - homeserverUrl = accountProvider.url, - resolvedHomeserverUrl = null, - loginHint = null, + is ConfirmAccountProviderEvents.UserInputChanged -> { + userInput = event.accountProvider + } + // Validate (and persist) the chosen account provider before proceeding. This also enforces the + // account-provider access control, which the login submit does not run on its own. + is ConfirmAccountProviderEvents.Continue -> { + // Apply the accepted account provider (any accepted completion) back into the field so it + // renders the full server rather than the typed prefix, and survives the OAuth round-trip. + val accountProvider = event.accountProvider.trim() + userInput = accountProvider + // If the user entered a full Matrix user ID (e.g. "@alice:example.org"), sign in to its + // homeserver and pass the ID as a login hint so the authentication server can pre-fill it. + // Otherwise treat the input as the account provider host. Only the homeserver is ever + // persisted to history, never the user ID. + val isUserId = MatrixPatterns.isUserId(accountProvider) + // For a user ID the homeserver is the domain part (after the ':'), keeping any port. + val host = if (isUserId) accountProvider.substringAfter(":") else accountProvider + submittedLoginHint = "mxid:$accountProvider".takeIf { isUserId && !params.isAccountCreation } + // Default the scheme to https:// so entering a bare host (e.g. "matrix.org") works. + val accountProviderUrl = host.ensureProtocol() + submittedAccountProvider = accountProviderUrl + changeServerState.eventSink( + ChangeServerEvents.ChangeServer(AccountProvider(url = accountProviderUrl)) ) - ) - ConfirmAccountProviderEvents.ClearError -> loginModeState.eventSink(LoginModeEvent.ClearError) + } + ConfirmAccountProviderEvents.ClearError -> { + loginModeState.eventSink(LoginModeEvent.ClearError) + changeServerState.eventSink(ChangeServerEvents.ClearError) + } } } return ConfirmAccountProviderState( - accountProvider = accountProvider, + accountProviderInput = accountProviderInput, + accountProviderSuggestion = accountProviderSuggestion, isAccountCreation = params.isAccountCreation, loginModeState = loginModeState, + changeServerState = changeServerState, eventSink = ::handleEvent, ) } } + +/** + * The host part of an account provider URL, i.e. the value with any `https://` / `http://` scheme removed. + * Returns the input unchanged when it has no scheme (e.g. `matrix.org`). + */ +private fun String.withoutScheme(): String = substringAfter("://") diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderState.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderState.kt index 6e6deb8c2c..bf6b0cb0e7 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderState.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderState.kt @@ -8,17 +8,29 @@ package io.element.android.features.login.impl.screens.confirmaccountprovider -import io.element.android.features.login.impl.accountprovider.AccountProvider +import io.element.android.features.login.impl.changeserver.ChangeServerState import io.element.android.features.login.impl.login.LoginModeState import io.element.android.libraries.architecture.AsyncData data class ConfirmAccountProviderState( - val accountProvider: AccountProvider, + val accountProviderInput: String, + // The full account provider from history that the current input is a prefix of, offered as inline autocomplete. + val accountProviderSuggestion: String?, val isAccountCreation: Boolean, val loginModeState: LoginModeState, + val changeServerState: ChangeServerState, val eventSink: (ConfirmAccountProviderEvents) -> Unit ) { val submitEnabled: Boolean - get() = accountProvider.url.isNotEmpty() && - (loginModeState.loginMode is AsyncData.Uninitialized || loginModeState.loginMode is AsyncData.Loading) + get() = accountProviderInput.isNotBlank() && + loginModeState.loginMode is AsyncData.Uninitialized && + changeServerState.changeServerAction is AsyncData.Uninitialized + + val isLoading: Boolean + get() = loginModeState.loginMode is AsyncData.Loading || + changeServerState.changeServerAction is AsyncData.Loading + + val isShowingError: Boolean + get() = loginModeState.loginMode is AsyncData.Failure || + changeServerState.changeServerAction is AsyncData.Failure } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderStatePreviewParam.kt similarity index 66% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderStatePreviewParam.kt index f597ad6b54..ab6350bb4d 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderStatePreviewParam.kt @@ -9,17 +9,21 @@ package io.element.android.features.login.impl.screens.confirmaccountprovider import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import io.element.android.features.login.impl.accountprovider.AccountProvider -import io.element.android.features.login.impl.accountprovider.anAccountProvider +import io.element.android.features.login.impl.changeserver.ChangeServerState +import io.element.android.features.login.impl.changeserver.aChangeServerState import io.element.android.features.login.impl.login.LoginModeState import io.element.android.features.login.impl.login.aLoginModeState import io.element.android.features.login.impl.screens.createaccount.AccountCreationNotSupported import io.element.android.libraries.architecture.AsyncData -open class ConfirmAccountProviderStateProvider : PreviewParameterProvider { +open class ConfirmAccountProviderStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aConfirmAccountProviderState(), + aConfirmAccountProviderState( + accountProviderInput = "element", + accountProviderSuggestion = "element.io", + ), aConfirmAccountProviderState( isAccountCreation = true, ), @@ -31,13 +35,17 @@ open class ConfirmAccountProviderStateProvider : PreviewParameterProvider Unit = {}, ) = ConfirmAccountProviderState( - accountProvider = accountProvider, + accountProviderInput = accountProviderInput, + accountProviderSuggestion = accountProviderSuggestion, isAccountCreation = isAccountCreation, loginModeState = loginModeState, + changeServerState = changeServerState, eventSink = eventSink ) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderView.kt index 95fbff25ab..1dab5cd31c 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderView.kt @@ -8,51 +8,110 @@ package io.element.android.features.login.impl.screens.confirmaccountprovider +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable -import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.OffsetMapping +import androidx.compose.ui.text.input.TransformedText +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp +import io.element.android.compound.theme.ElementTheme import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.login.impl.R +import io.element.android.features.login.impl.changeserver.ChangeServerView import io.element.android.features.login.impl.login.LoginModeEvent import io.element.android.features.login.impl.login.LoginModeView -import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.designsystem.atomic.molecules.ButtonColumnMolecule import io.element.android.libraries.designsystem.atomic.molecules.IconTitleSubtitleMolecule import io.element.android.libraries.designsystem.atomic.pages.HeaderFooterPage import io.element.android.libraries.designsystem.components.BigIcon +import io.element.android.libraries.designsystem.components.form.textFieldState import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.designsystem.theme.components.Button -import io.element.android.libraries.designsystem.theme.components.TextButton +import io.element.android.libraries.designsystem.theme.components.Icon +import io.element.android.libraries.designsystem.theme.components.TextField import io.element.android.libraries.matrix.api.auth.OAuthDetails import io.element.android.libraries.permissions.api.localnetwork.LocalNetworkPermissionDialogView import io.element.android.libraries.testtags.TestTags import io.element.android.libraries.testtags.testTag import io.element.android.libraries.ui.strings.CommonStrings +/** + * Account provider entry screen, shared by sign in and account creation. + * Figma (Compound Android Templates): + * - Sign in: https://www.figma.com/design/pDlJZGBsri47FNTXMnEdXB/Compound-Android-Templates?node-id=41-10251 + * - Create account: https://www.figma.com/design/pDlJZGBsri47FNTXMnEdXB/Compound-Android-Templates?node-id=41-10239 + */ @Composable fun ConfirmAccountProviderView( state: ConfirmAccountProviderState, onOAuthDetails: (OAuthDetails) -> Unit, onNeedLoginPassword: () -> Unit, onLearnMoreClick: () -> Unit, - onCreateAccountContinue: (url: String) -> Unit, - onChange: () -> Unit, modifier: Modifier = Modifier, ) { - val isLoading by remember(state.loginModeState.loginMode) { - derivedStateOf { - state.loginModeState.loginMode is AsyncData.Loading - } - } val eventSink = state.eventSink + val focusManager = LocalFocusManager.current + val focusRequester = remember { FocusRequester() } + val keyboardController = LocalSoftwareKeyboardController.current + + var input by textFieldState(stateValue = state.accountProviderInput) + + // Inline autocomplete: the un-typed remainder of the suggested account provider (rendered in grey and + // accepted on Continue / Enter). Only valid while the suggestion still starts with the current input. + val suggestionSuffix = state.accountProviderSuggestion + ?.takeIf { it.length > input.length && it.startsWith(input, ignoreCase = true) } + ?.substring(input.length) + .orEmpty() + + // The Continue button lives in a footer slot that is not recomposed while the user types, so a direct + // capture of the field text (via ::submit) goes stale and can submit an empty/prefilled value. Reading + // the value through rememberUpdatedState keeps it current regardless of which composition scope reads it. + val accountProviderToSubmit by rememberUpdatedState(input + suggestionSuffix) + + fun submit() { + // Dismiss the keyboard and release focus while the account provider is being validated. + focusManager.clearFocus(force = true) + // Submit the exact field text (plus any accepted suggestion). + eventSink(ConfirmAccountProviderEvents.Continue(accountProviderToSubmit)) + } + + // Once a validation / login error has been dismissed, return focus and the keyboard to the field so + // the user can correct the account provider and retry. + var wasShowingError by remember { mutableStateOf(false) } + LaunchedEffect(state.isShowingError) { + if (wasShowingError && !state.isShowingError) { + focusRequester.requestFocus() + keyboardController?.show() + } + wasShowingError = state.isShowingError + } HeaderFooterPage( modifier = modifier, @@ -62,55 +121,113 @@ fun ConfirmAccountProviderView( iconStyle = BigIcon.Style.Default(CompoundIcons.UserProfileSolid()), title = stringResource( id = if (state.isAccountCreation) { - R.string.screen_account_provider_signup_title + R.string.screen_change_server_title_register } else { - R.string.screen_account_provider_signin_title - }, - state.accountProvider.title + R.string.screen_change_server_title_login + } ), - subTitle = stringResource( - id = if (state.isAccountCreation) { - R.string.screen_account_provider_signup_subtitle - } else { - R.string.screen_account_provider_signin_subtitle - }, - ) + subTitle = null, ) }, footer = { ButtonColumnMolecule { Button( text = stringResource(id = CommonStrings.action_continue), - showProgress = isLoading, - onClick = { eventSink.invoke(ConfirmAccountProviderEvents.Continue) }, - enabled = state.submitEnabled || isLoading, + showProgress = state.isLoading, + onClick = ::submit, + enabled = state.submitEnabled && !state.isLoading, modifier = Modifier .fillMaxWidth() .testTag(TestTags.loginContinue) ) - TextButton( - text = stringResource(id = R.string.screen_account_provider_change), - onClick = onChange, - enabled = !isLoading, - modifier = Modifier - .fillMaxWidth() - .testTag(TestTags.loginChangeServer) - ) } } ) { - LoginModeView( - loginMode = state.loginModeState.loginMode, - onClearError = { - eventSink(ConfirmAccountProviderEvents.ClearError) + val ghostColor = ElementTheme.colors.textSecondary + val ghostTransformation = remember(suggestionSuffix, ghostColor) { + GhostSuffixVisualTransformation(suggestionSuffix, ghostColor) + } + TextField( + value = input, + onValueChange = { + input = it + eventSink(ConfirmAccountProviderEvents.UserInputChanged(it)) + }, + modifier = Modifier + .fillMaxWidth() + .padding(top = 40.dp) + .focusRequester(focusRequester) + .testTag(TestTags.changeServerServer), + label = stringResource(id = R.string.screen_change_server_textfield_header), + placeholder = stringResource(id = R.string.screen_change_server_textfield_placeholder), + supportingText = stringResource( + id = if (state.isAccountCreation) { + R.string.screen_change_server_textfield_footer_register + } else { + R.string.screen_change_server_textfield_footer_login + } + ), + visualTransformation = ghostTransformation, + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Uri, + imeAction = ImeAction.Done, + ), + keyboardActions = KeyboardActions( + onDone = { + if (suggestionSuffix.isNotEmpty()) { + // A completion is showing: accept it into the field and drop focus, dismissing the + // keyboard. This shows the completed server (with no stray mid-text cursor, since the + // field is no longer focused) ready to sign in with Continue. When no completion is + // showing, Done submits directly. + val accepted = input + suggestionSuffix + input = accepted + eventSink(ConfirmAccountProviderEvents.UserInputChanged(accepted)) + focusManager.clearFocus(force = true) + } else { + submit() + } + } + ), + singleLine = true, + trailingIcon = if (input.isNotEmpty()) { + { + Box( + Modifier.clickable( + onClickLabel = stringResource(CommonStrings.action_clear), + role = Role.Button, + ) { + input = "" + eventSink(ConfirmAccountProviderEvents.UserInputChanged("")) + } + ) { + Icon( + imageVector = CompoundIcons.Close(), + contentDescription = stringResource(CommonStrings.action_clear) + ) + } + } + } else { + null }, - onLearnMoreClick = onLearnMoreClick, - onOAuthDetails = onOAuthDetails, - onNeedLoginPassword = onNeedLoginPassword, - onCreateAccountContinue = onCreateAccountContinue, ) } + // Renders the account-provider validation errors, progress and permission dialogs. + // The successful validation itself is observed by the presenter, which then proceeds with the login flow. + ChangeServerView( + state = state.changeServerState, + onLearnMoreClick = onLearnMoreClick, + onSuccess = {}, + ) + + LoginModeView( + loginMode = state.loginModeState.loginMode, + onClearError = { eventSink(ConfirmAccountProviderEvents.ClearError) }, + onLearnMoreClick = onLearnMoreClick, + onOAuthDetails = onOAuthDetails, + onNeedLoginPassword = onNeedLoginPassword, + ) + LocalNetworkPermissionDialogView( dialog = state.loginModeState.localNetworkPermissionDialog, onSubmit = { @@ -122,17 +239,38 @@ fun ConfirmAccountProviderView( ) } +/** + * Appends [suffix] (in [color]) after the user's text as a non-editable inline autocomplete hint. + * The underlying field value stays limited to what the user actually typed, so the cursor can never + * enter the suggested region. + */ +private class GhostSuffixVisualTransformation( + private val suffix: String, + private val color: Color, +) : VisualTransformation { + override fun filter(text: AnnotatedString): TransformedText { + if (suffix.isEmpty()) return TransformedText(text, OffsetMapping.Identity) + val transformed = buildAnnotatedString { + append(text) + withStyle(SpanStyle(color = color)) { append(suffix) } + } + val offsetMapping = object : OffsetMapping { + override fun originalToTransformed(offset: Int) = offset + override fun transformedToOriginal(offset: Int) = offset.coerceAtMost(text.length) + } + return TransformedText(transformed, offsetMapping) + } +} + @PreviewsDayNight @Composable internal fun ConfirmAccountProviderViewPreview( - @PreviewParameter(ConfirmAccountProviderStateProvider::class) state: ConfirmAccountProviderState + @PreviewParameter(ConfirmAccountProviderStatePreviewParam::class) state: ConfirmAccountProviderState ) = ElementPreview { ConfirmAccountProviderView( state = state, onOAuthDetails = {}, onNeedLoginPassword = {}, - onCreateAccountContinue = {}, onLearnMoreClick = {}, - onChange = {}, ) } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountEvents.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountEvents.kt deleted file mode 100644 index a51557347e..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountEvents.kt +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -sealed interface CreateAccountEvents { - data class SetPageProgress(val progress: Int) : CreateAccountEvents - data class OnMessageReceived(val message: String) : CreateAccountEvents -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountNode.kt deleted file mode 100644 index e1972e5a0f..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountNode.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import android.app.Activity -import androidx.activity.compose.LocalActivity -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import com.bumble.appyx.core.modality.BuildContext -import com.bumble.appyx.core.node.Node -import com.bumble.appyx.core.plugin.Plugin -import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.Assisted -import dev.zacsweers.metro.AssistedInject -import io.element.android.annotations.ContributesNode -import io.element.android.compound.theme.ElementTheme -import io.element.android.libraries.androidutils.browser.openUrlInChromeCustomTab -import io.element.android.libraries.architecture.NodeInputs -import io.element.android.libraries.architecture.inputs - -@ContributesNode(AppScope::class) -@AssistedInject -class CreateAccountNode( - @Assisted buildContext: BuildContext, - @Assisted plugins: List, - presenterFactory: CreateAccountPresenter.Factory, -) : Node(buildContext, plugins = plugins) { - data class Inputs( - val url: String, - ) : NodeInputs - - private val presenter = presenterFactory.create(inputs().url) - - private fun onOpenExternalUrl(activity: Activity, darkTheme: Boolean, url: String) { - activity.openUrlInChromeCustomTab(null, darkTheme, url) - } - - @Composable - override fun View(modifier: Modifier) { - val activity = requireNotNull(LocalActivity.current) - val isDark = ElementTheme.isLightTheme.not() - val state = presenter.present() - CreateAccountView( - state = state, - modifier = modifier, - onBackClick = ::navigateUp, - onOpenExternalUrl = { - onOpenExternalUrl(activity, isDark, it) - }, - ) - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountPresenter.kt deleted file mode 100644 index bf7af111f4..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountPresenter.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import androidx.compose.runtime.Composable -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import dev.zacsweers.metro.Assisted -import dev.zacsweers.metro.AssistedFactory -import dev.zacsweers.metro.AssistedInject -import io.element.android.libraries.architecture.AsyncAction -import io.element.android.libraries.architecture.Presenter -import io.element.android.libraries.core.extensions.flatMap -import io.element.android.libraries.core.extensions.runCatchingExceptions -import io.element.android.libraries.core.meta.BuildMeta -import io.element.android.libraries.matrix.api.auth.MatrixAuthenticationService -import io.element.android.libraries.matrix.api.core.SessionId -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.launch - -@AssistedInject -class CreateAccountPresenter( - @Assisted private val url: String, - private val authenticationService: MatrixAuthenticationService, - private val messageParser: MessageParser, - private val buildMeta: BuildMeta, -) : Presenter { - @AssistedFactory - interface Factory { - fun create(url: String): CreateAccountPresenter - } - - @Composable - override fun present(): CreateAccountState { - val coroutineScope = rememberCoroutineScope() - val pageProgress: MutableState = remember { mutableIntStateOf(0) } - val createAction: MutableState> = remember { mutableStateOf(AsyncAction.Uninitialized) } - - fun handleEvent(event: CreateAccountEvents) { - when (event) { - is CreateAccountEvents.SetPageProgress -> { - pageProgress.value = event.progress - } - is CreateAccountEvents.OnMessageReceived -> { - // Ignore unexpected message - if (event.message.contains("isTrusted")) return - coroutineScope.importSession(event.message, createAction) - } - } - } - - return CreateAccountState( - url = url, - pageProgress = pageProgress.value, - isDebugBuild = buildMeta.isDebuggable, - createAction = createAction.value, - eventSink = ::handleEvent, - ) - } - - private fun CoroutineScope.importSession(message: String, loggedInState: MutableState>) = launch { - loggedInState.value = AsyncAction.Loading - runCatchingExceptions { - messageParser.parse(message) - }.flatMap { externalSession -> - authenticationService.importCreatedSession(externalSession) - }.onSuccess { sessionId -> - loggedInState.value = AsyncAction.Success(sessionId) - }.onFailure { failure -> - loggedInState.value = AsyncAction.Failure(failure) - } - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountState.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountState.kt deleted file mode 100644 index de7efe573e..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountState.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import io.element.android.libraries.architecture.AsyncAction -import io.element.android.libraries.matrix.api.core.SessionId - -data class CreateAccountState( - val url: String, - val pageProgress: Int, - val createAction: AsyncAction, - val isDebugBuild: Boolean, - val eventSink: (CreateAccountEvents) -> Unit -) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountStateProvider.kt deleted file mode 100644 index 976ceae70d..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountStateProvider.kt +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import io.element.android.libraries.architecture.AsyncAction -import io.element.android.libraries.matrix.api.core.SessionId - -open class CreateAccountStateProvider : PreviewParameterProvider { - override val values: Sequence - get() = sequenceOf( - aCreateAccountState(), - aCreateAccountState(pageProgress = 33), - aCreateAccountState(createAction = AsyncAction.Loading), - aCreateAccountState(createAction = AsyncAction.Failure(RuntimeException("Failed to create account"))), - ) -} - -private fun aCreateAccountState( - pageProgress: Int = 100, - createAction: AsyncAction = AsyncAction.Uninitialized, -) = CreateAccountState( - url = "https://example.com", - isDebugBuild = true, - pageProgress = pageProgress, - createAction = createAction, - eventSink = {} -) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountView.kt deleted file mode 100644 index 051188627a..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountView.kt +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import android.annotation.SuppressLint -import android.view.ViewGroup -import android.webkit.JsResult -import android.webkit.WebChromeClient -import android.webkit.WebView -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.fadeIn -import androidx.compose.animation.fadeOut -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.consumeWindowInsets -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalInspectionMode -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.tooling.preview.PreviewParameter -import androidx.compose.ui.unit.dp -import androidx.compose.ui.viewinterop.AndroidView -import io.element.android.compound.theme.ElementTheme -import io.element.android.features.login.impl.R -import io.element.android.libraries.designsystem.components.async.AsyncActionView -import io.element.android.libraries.designsystem.components.button.BackButton -import io.element.android.libraries.designsystem.preview.ElementPreview -import io.element.android.libraries.designsystem.preview.PreviewsDayNight -import io.element.android.libraries.designsystem.theme.components.LinearProgressIndicator -import io.element.android.libraries.designsystem.theme.components.Scaffold -import io.element.android.libraries.designsystem.theme.components.Text -import io.element.android.libraries.designsystem.theme.components.TopAppBar -import io.element.android.libraries.designsystem.theme.progressIndicatorTrackColor -import timber.log.Timber - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun CreateAccountView( - state: CreateAccountState, - onBackClick: () -> Unit, - onOpenExternalUrl: (String) -> Unit, - modifier: Modifier = Modifier, -) { - Scaffold( - modifier = modifier, - topBar = { - TopAppBar( - titleStr = stringResource(R.string.screen_create_account_title), - navigationIcon = { - BackButton(onClick = onBackClick) - }, - ) - } - ) { contentPadding -> - Box( - modifier = Modifier - .padding(contentPadding) - .consumeWindowInsets(contentPadding) - .fillMaxSize() - ) { - CreateAccountWebView( - modifier = Modifier - .fillMaxSize(), - state = state, - onWebViewCreate = { webView -> - WebViewMessageInterceptor( - webView, - state.isDebugBuild, - onOpenExternalUrl = onOpenExternalUrl, - onMessage = { - state.eventSink(CreateAccountEvents.OnMessageReceived(it)) - }, - ) - } - ) - AnimatedVisibility( - visible = state.pageProgress != 100, - // Disable enter animation - enter = fadeIn(initialAlpha = 1f), - exit = fadeOut(), - ) { - LinearProgressIndicator( - modifier = Modifier - .fillMaxWidth() - .height(2.dp), - progress = { state.pageProgress / 100f }, - trackColor = ElementTheme.colors.progressIndicatorTrackColor, - ) - } - } - } - - AsyncActionView( - async = state.createAction, - onSuccess = {}, - onErrorDismiss = onBackClick, - onRetry = null - ) -} - -@Composable -private fun CreateAccountWebView( - state: CreateAccountState, - onWebViewCreate: (WebView) -> Unit, - modifier: Modifier = Modifier, -) { - if (LocalInspectionMode.current) { - Box(modifier = modifier, contentAlignment = Alignment.Center) { - Text("WebView - can't be previewed") - } - } else { - AndroidView( - modifier = modifier, - factory = { context -> - WebView(context).apply { - onWebViewCreate(this) - setup(state) - } - }, - update = { webView -> - if (webView.url != state.url) { - webView.loadUrl(state.url) - } - }, - onRelease = { webView -> - webView.destroy() - } - ) - } -} - -@SuppressLint("SetJavaScriptEnabled") -private fun WebView.setup(state: CreateAccountState) { - layoutParams = ViewGroup.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT - ) - with(settings) { - javaScriptEnabled = true - domStorageEnabled = true - } - - webChromeClient = object : WebChromeClient() { - override fun onProgressChanged(view: WebView?, newProgress: Int) { - super.onProgressChanged(view, newProgress) - state.eventSink(CreateAccountEvents.SetPageProgress(newProgress)) - } - - override fun onJsBeforeUnload(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean { - Timber.w("onJsBeforeUnload, cancelling the dialog, we will open external links in a Custom Chrome Tab") - result?.confirm() - return true - } - } -} - -@PreviewsDayNight -@Composable -internal fun CreateAccountViewPreview(@PreviewParameter(CreateAccountStateProvider::class) state: CreateAccountState) = ElementPreview { - CreateAccountView( - state = state, - onBackClick = {}, - onOpenExternalUrl = {}, - ) -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/MessageParser.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/MessageParser.kt deleted file mode 100644 index d7954373bc..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/MessageParser.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.ContributesBinding -import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource -import io.element.android.libraries.androidutils.json.JsonProvider -import io.element.android.libraries.matrix.api.auth.external.ExternalSession - -interface MessageParser { - /** - * Parse the message and return the ExternalSession object, or - * throw an exception if the message is invalid. - */ - fun parse(message: String): ExternalSession -} - -@ContributesBinding(AppScope::class) -class DefaultMessageParser( - private val accountProviderDataSource: AccountProviderDataSource, - private val json: JsonProvider, -) : MessageParser { - override fun parse(message: String): ExternalSession { - val response = json().decodeFromString(MobileRegistrationResponse.serializer(), message) - val userId = response.userId ?: error("No user ID in response") - val homeServer = response.homeServer ?: accountProviderDataSource.flow.value.url - val accessToken = response.accessToken ?: error("No access token in response") - val deviceId = response.deviceId ?: error("No device ID in response") - return ExternalSession( - userId = userId, - homeserverUrl = homeServer, - accessToken = accessToken, - deviceId = deviceId, - refreshToken = null, - ) - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/MobileRegistrationResponse.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/MobileRegistrationResponse.kt deleted file mode 100644 index 5e78b1bd37..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/MobileRegistrationResponse.kt +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -/** - * For ref: - * https://github.com/element-hq/matrix-react-sdk/pull/42/files#diff-2bbba5a742004fd4e924a639ded444279f66f7ad890cb669fbc91ac6b8638c64R56 - */ -@Serializable -data class MobileRegistrationResponse( - @SerialName("user_id") - val userId: String? = null, - @SerialName("home_server") - val homeServer: String? = null, - @SerialName("access_token") - val accessToken: String? = null, - @SerialName("device_id") - val deviceId: String? = null, -) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/WebViewMessageInterceptor.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/WebViewMessageInterceptor.kt deleted file mode 100644 index 20d503522b..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/createaccount/WebViewMessageInterceptor.kt +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import android.graphics.Bitmap -import android.webkit.JavascriptInterface -import android.webkit.WebResourceRequest -import android.webkit.WebView -import android.webkit.WebViewClient -import androidx.webkit.WebViewCompat -import androidx.webkit.WebViewFeature - -class WebViewMessageInterceptor( - webView: WebView, - private val debugLog: Boolean, - private val onOpenExternalUrl: (String) -> Unit, - private val onMessage: (String) -> Unit, -) { - companion object { - // We call both the WebMessageListener and the JavascriptInterface objects in JS with this - // 'listenerName' so they can both receive the data from the WebView when - // `${LISTENER_NAME}.postMessage(...)` is called - const val LISTENER_NAME = "elementX" - } - - init { - webView.webViewClient = object : WebViewClient() { - override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { - super.onPageStarted(view, url, favicon) - - // We inject this JS code when the page starts loading to attach a message listener to the window. - view?.evaluateJavascript( - """ - window.addEventListener( - "mobileregistrationresponse", - (event) => { - let json = JSON.stringify(event.detail) - ${"console.log('message sent: ' + json);".takeIf { debugLog }} - $LISTENER_NAME.postMessage(json); - }, - false, - ); - """.trimIndent(), - null - ) - } - - override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { - request ?: return false - // Load the URL in a Chrome Custom Tab, and return true to cancel the load - onOpenExternalUrl(request.url.toString()) - return true - } - } - - // Use WebMessageListener if supported, otherwise use JavascriptInterface - if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { - // Create a WebMessageListener, which will receive messages from the WebView and reply to them - val webMessageListener = WebViewCompat.WebMessageListener { _, message, _, _, _ -> - onMessageReceived(message.data) - } - WebViewCompat.addWebMessageListener( - webView, - LISTENER_NAME, - setOf("*"), - webMessageListener - ) - } else { - webView.addJavascriptInterface( - object { - @JavascriptInterface - fun postMessage(json: String?) { - onMessageReceived(json) - } - }, - LISTENER_NAME, - ) - } - } - - private fun onMessageReceived(json: String?) { - // Here is where we would handle the messages from the WebView, passing them to the listener - json?.let { onMessage(it) } - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenter.kt index f26f342a42..6e28bd8781 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenter.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenter.kt @@ -20,6 +20,7 @@ import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedFactory import dev.zacsweers.metro.AssistedInject import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.accountprovider.SaveAccountProviderToHistory import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.matrix.api.auth.MatrixAuthenticationService @@ -33,6 +34,7 @@ class LoginPasswordPresenter( private val initialLogin: String, private val authenticationService: MatrixAuthenticationService, private val accountProviderDataSource: AccountProviderDataSource, + private val saveAccountProviderToHistory: SaveAccountProviderToHistory, ) : Presenter { @AssistedFactory interface Factory { @@ -83,6 +85,7 @@ class LoginPasswordPresenter( loggedInState.value = AsyncData.Loading() authenticationService.login(formState.login.trim(), formState.password) .onSuccess { sessionId -> + saveAccountProviderToHistory() loggedInState.value = AsyncData.Success(sessionId) } .onFailure { failure -> diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordStatePreviewParam.kt similarity index 94% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordStatePreviewParam.kt index 2183790365..4d7201dbc8 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.features.login.impl.accountprovider.anAccountProvider import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.core.SessionId -open class LoginPasswordStateProvider : PreviewParameterProvider { +open class LoginPasswordStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLoginPasswordState(), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordView.kt index 06a1641644..a168b14cc8 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordView.kt @@ -56,6 +56,7 @@ import io.element.android.libraries.designsystem.components.BigIcon import io.element.android.libraries.designsystem.components.button.BackButton import io.element.android.libraries.designsystem.components.dialogs.ErrorDialog import io.element.android.libraries.designsystem.components.form.textFieldState +import io.element.android.libraries.designsystem.modifiers.bringIntoViewOnImeVisible import io.element.android.libraries.designsystem.modifiers.onTabOrEnterKeyFocusNext import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight @@ -191,6 +192,7 @@ private fun LoginForm( enabled = !isLoading, modifier = Modifier .fillMaxWidth() + .bringIntoViewOnImeVisible() .onTabOrEnterKeyFocusNext(focusManager) .testTag(TestTags.loginEmailUsername) .semantics { @@ -243,6 +245,7 @@ private fun LoginForm( enabled = !isLoading, modifier = Modifier .fillMaxWidth() + .bringIntoViewOnImeVisible() .onTabOrEnterKeyFocusNext(focusManager) .testTag(TestTags.loginPassword) .semantics { @@ -274,10 +277,10 @@ private fun LoginForm( } /** - * Ensure that the string does not contain any new line characters, which can happen when pasting values. + * Ensure that the string does not contain any line separator, which can happen when pasting values. */ private fun String.sanitize(): String { - return replace("\n", "") + return filterNot { it == '\n' || it == '\r' } } @Composable @@ -291,7 +294,7 @@ private fun LoginErrorDialog(error: Throwable, onDismiss: () -> Unit) { @PreviewsDayNight @Composable -internal fun LoginPasswordViewPreview(@PreviewParameter(LoginPasswordStateProvider::class) state: LoginPasswordState) = ElementPreview { +internal fun LoginPasswordViewPreview(@PreviewParameter(LoginPasswordStatePreviewParam::class) state: LoginPasswordState) = ElementPreview { LoginPasswordView( state = state, onBackClick = {}, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingNode.kt index 99f7e86fd3..244e684c5b 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingNode.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingNode.kt @@ -41,7 +41,6 @@ class OnBoardingNode( fun navigateToBugReport() fun navigateToLoginPassword() fun navigateToOAuth(oAuthDetails: OAuthDetails) - fun navigateToCreateAccount(url: String) fun navigateToDeveloperSettings() fun onDone() } @@ -74,7 +73,6 @@ class OnBoardingNode( onOAuthDetails = callback::navigateToOAuth, onNeedLoginPassword = callback::navigateToLoginPassword, onLearnMoreClick = { openLearnMorePage(context) }, - onCreateAccountContinue = callback::navigateToCreateAccount, onBackClick = callback::onDone, onDeveloperSettingsClick = callback::navigateToDeveloperSettings, ) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenter.kt index 29e4b1afe5..e9bdb5e1e9 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenter.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenter.kt @@ -60,15 +60,15 @@ class OnBoardingPresenter( override fun present(): OnBoardingState { val localCoroutineScope = rememberCoroutineScope() val forcedAccountProvider = remember { - // If defaultHomeserverList() returns a singleton list, this is the default account provider. + // If homeserverAllowList() returns a singleton list, this is the default account provider. // In this case, the user can sign in using this homeserver, or use QrCode login - enterpriseService.defaultHomeserverList().singleOrNull() + enterpriseService.homeserverAllowList().singleOrNull() } val canConnectToAnyHomeserver = remember { enterpriseService.canConnectToAnyHomeserver() } val mustChooseAccountProvider = remember { - !canConnectToAnyHomeserver && enterpriseService.defaultHomeserverList().size > 1 + !canConnectToAnyHomeserver && enterpriseService.homeserverAllowList().size > 1 } val linkAccountProvider by produceState(initialValue = null) { // Account provider from the link, if allowed by the enterprise service diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingStatePreviewParam.kt similarity index 96% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingStatePreviewParam.kt index 41e4a81818..d04f85f2a0 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.features.login.impl.login.LoginModeState import io.element.android.features.login.impl.login.aLoginModeState import io.element.android.libraries.designsystem.R -open class OnBoardingStateProvider : PreviewParameterProvider { +open class OnBoardingStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anOnBoardingState(), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingView.kt index bf96b2dbe0..78faed7543 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingView.kt @@ -71,7 +71,6 @@ fun OnBoardingView( onOAuthDetails: (OAuthDetails) -> Unit, onNeedLoginPassword: () -> Unit, onLearnMoreClick: () -> Unit, - onCreateAccountContinue: (url: String) -> Unit, onReportProblem: () -> Unit, modifier: Modifier = Modifier, ) { @@ -84,7 +83,6 @@ fun OnBoardingView( onLearnMoreClick = onLearnMoreClick, onOAuthDetails = onOAuthDetails, onNeedLoginPassword = onNeedLoginPassword, - onCreateAccountContinue = onCreateAccountContinue, ) LocalNetworkPermissionDialogView( dialog = state.loginModeState.localNetworkPermissionDialog, @@ -353,7 +351,7 @@ private fun OnBoardingButtons( @PreviewsDayNight @Composable internal fun OnBoardingViewPreview( - @PreviewParameter(OnBoardingStateProvider::class) state: OnBoardingState + @PreviewParameter(OnBoardingStatePreviewParam::class) state: OnBoardingState ) = ElementPreview { OnBoardingView( state = state, @@ -366,6 +364,5 @@ internal fun OnBoardingViewPreview( onOAuthDetails = {}, onNeedLoginPassword = {}, onLearnMoreClick = {}, - onCreateAccountContinue = {}, ) } diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationStepProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationStepPreviewParam.kt similarity index 87% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationStepProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationStepPreviewParam.kt index 17864f68a1..700c6a87b7 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationStepProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationStepPreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.login.impl.screens.qrcode.confirmation import androidx.compose.ui.tooling.preview.PreviewParameterProvider -class QrCodeConfirmationStepProvider : PreviewParameterProvider { +class QrCodeConfirmationStepPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( QrCodeConfirmationStep.DisplayCheckCode("12"), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationView.kt index 8de93bcb0f..2c29f4a667 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/confirmation/QrCodeConfirmationView.kt @@ -148,7 +148,7 @@ private fun Buttons( @PreviewsDayNight @Composable -internal fun QrCodeConfirmationViewPreview(@PreviewParameter(QrCodeConfirmationStepProvider::class) step: QrCodeConfirmationStep) { +internal fun QrCodeConfirmationViewPreview(@PreviewParameter(QrCodeConfirmationStepPreviewParam::class) step: QrCodeConfirmationStep) { ElementPreview { QrCodeConfirmationView( step = step, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/error/QrCodeErrorView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/error/QrCodeErrorView.kt index 6b5da8f300..4d58b9329a 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/error/QrCodeErrorView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/error/QrCodeErrorView.kt @@ -143,7 +143,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable -internal fun QrCodeErrorViewPreview(@PreviewParameter(QrCodeErrorScreenTypeProvider::class) errorScreenType: QrCodeErrorScreenType) { +internal fun QrCodeErrorViewPreview(@PreviewParameter(QrCodeErrorScreenTypePreviewParam::class) errorScreenType: QrCodeErrorScreenType) { ElementPreview { QrCodeErrorView( errorScreenType = errorScreenType, @@ -154,7 +154,7 @@ internal fun QrCodeErrorViewPreview(@PreviewParameter(QrCodeErrorScreenTypeProvi } } -class QrCodeErrorScreenTypeProvider : PreviewParameterProvider { +class QrCodeErrorScreenTypePreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( QrCodeErrorScreenType.Cancelled, QrCodeErrorScreenType.Declined, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroStatePreviewParam.kt similarity index 93% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroStatePreviewParam.kt index 22c7fd67f6..b9c286dc16 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroStatePreviewParam.kt @@ -13,7 +13,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.permissions.api.PermissionsState import io.element.android.libraries.permissions.api.aPermissionsState -open class QrCodeIntroStateProvider : PreviewParameterProvider { +open class QrCodeIntroStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aQrCodeIntroState(), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroView.kt index 767dc49999..08a40b63c5 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/intro/QrCodeIntroView.kt @@ -98,7 +98,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable -internal fun QrCodeIntroViewPreview(@PreviewParameter(QrCodeIntroStateProvider::class) state: QrCodeIntroState) = ElementPreview { +internal fun QrCodeIntroViewPreview(@PreviewParameter(QrCodeIntroStatePreviewParam::class) state: QrCodeIntroState) = ElementPreview { QrCodeIntroView( state = state, onBackClick = {}, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanStatePreviewParam.kt similarity index 96% rename from features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanStateProvider.kt rename to features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanStatePreviewParam.kt index 0d467efb71..19385b6df1 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanStateProvider.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.auth.qrlogin.MatrixQrCodeLoginData import io.element.android.libraries.matrix.api.auth.qrlogin.QrLoginException -open class QrCodeScanStateProvider : PreviewParameterProvider { +open class QrCodeScanStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aQrCodeScanState(), diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanView.kt index 6fa3d1b0c7..72d624a921 100644 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanView.kt +++ b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/qrcode/scan/QrCodeScanView.kt @@ -218,7 +218,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable -internal fun QrCodeScanViewPreview(@PreviewParameter(QrCodeScanStateProvider::class) state: QrCodeScanState) = ElementPreview { +internal fun QrCodeScanViewPreview(@PreviewParameter(QrCodeScanStatePreviewParam::class) state: QrCodeScanState) = ElementPreview { QrCodeScanView( state = state, onQrCodeDataReady = {}, diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderEvents.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderEvents.kt deleted file mode 100644 index 8816de3946..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderEvents.kt +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.searchaccountprovider - -sealed interface SearchAccountProviderEvents { - /** - * The user has typed something, expect to get a list of matching account provider results - * in the state. - */ - data class UserInput(val input: String) : SearchAccountProviderEvents -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderNode.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderNode.kt deleted file mode 100644 index ddbcc4c847..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderNode.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.searchaccountprovider - -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import com.bumble.appyx.core.modality.BuildContext -import com.bumble.appyx.core.node.Node -import com.bumble.appyx.core.plugin.Plugin -import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.Assisted -import dev.zacsweers.metro.AssistedInject -import io.element.android.annotations.ContributesNode -import io.element.android.features.login.impl.util.openLearnMorePage -import io.element.android.libraries.architecture.callback - -@ContributesNode(AppScope::class) -@AssistedInject -class SearchAccountProviderNode( - @Assisted buildContext: BuildContext, - @Assisted plugins: List, - private val presenter: SearchAccountProviderPresenter, -) : Node(buildContext, plugins = plugins) { - interface Callback : Plugin { - fun onDone() - } - - private val callback: Callback = callback() - - @Composable - override fun View(modifier: Modifier) { - val state = presenter.present() - val context = LocalContext.current - SearchAccountProviderView( - state = state, - modifier = modifier, - onBackClick = ::navigateUp, - onLearnMoreClick = { openLearnMorePage(context) }, - onSuccess = callback::onDone, - ) - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderPresenter.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderPresenter.kt deleted file mode 100644 index 2efe4501c6..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderPresenter.kt +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.searchaccountprovider - -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import dev.zacsweers.metro.Inject -import io.element.android.features.login.impl.changeserver.ChangeServerState -import io.element.android.features.login.impl.resolver.HomeserverData -import io.element.android.features.login.impl.resolver.HomeserverResolver -import io.element.android.libraries.architecture.AsyncData -import io.element.android.libraries.architecture.Presenter -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch - -@Inject -class SearchAccountProviderPresenter( - private val homeserverResolver: HomeserverResolver, - private val changeServerPresenter: Presenter, -) : Presenter { - @Composable - override fun present(): SearchAccountProviderState { - var userInput by rememberSaveable { - mutableStateOf("") - } - val changeServerState = changeServerPresenter.present() - - val data: MutableState>> = remember { - mutableStateOf(AsyncData.Uninitialized) - } - - LaunchedEffect(userInput) { - onUserInput(userInput, data) - } - - fun handleEvent(event: SearchAccountProviderEvents) { - when (event) { - is SearchAccountProviderEvents.UserInput -> { - userInput = event.input - } - } - } - - return SearchAccountProviderState( - userInput = userInput, - userInputResult = data.value, - changeServerState = changeServerState, - eventSink = ::handleEvent, - ) - } - - private fun CoroutineScope.onUserInput(userInput: String, data: MutableState>>) = launch { - data.value = AsyncData.Uninitialized - // Debounce - delay(500) - data.value = AsyncData.Loading() - homeserverResolver.resolve(userInput).collect { - data.value = AsyncData.Success(it) - } - if (data.value !is AsyncData.Success) { - data.value = AsyncData.Uninitialized - } - } -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderState.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderState.kt deleted file mode 100644 index dc02a997a6..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderState.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.searchaccountprovider - -import io.element.android.features.login.impl.changeserver.ChangeServerState -import io.element.android.features.login.impl.resolver.HomeserverData -import io.element.android.libraries.architecture.AsyncData - -data class SearchAccountProviderState( - val userInput: String, - val userInputResult: AsyncData>, - val changeServerState: ChangeServerState, - val eventSink: (SearchAccountProviderEvents) -> Unit -) diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderStateProvider.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderStateProvider.kt deleted file mode 100644 index 2a8512c38a..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderStateProvider.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.searchaccountprovider - -import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import io.element.android.appconfig.AuthenticationConfig -import io.element.android.features.login.impl.changeserver.aChangeServerState -import io.element.android.features.login.impl.resolver.HomeserverData -import io.element.android.libraries.architecture.AsyncData - -open class SearchAccountProviderStateProvider : PreviewParameterProvider { - override val values: Sequence - get() = sequenceOf( - aSearchAccountProviderState(), - aSearchAccountProviderState(userInputResult = AsyncData.Success(aHomeserverDataList())), - // Add other state here - ) -} - -fun aSearchAccountProviderState( - userInput: String = "", - userInputResult: AsyncData> = AsyncData.Uninitialized, -) = SearchAccountProviderState( - userInput = userInput, - userInputResult = userInputResult, - changeServerState = aChangeServerState(), - eventSink = {} -) - -fun aHomeserverDataList(): List { - return listOf( - aHomeserverData(homeserverUrl = AuthenticationConfig.MATRIX_ORG_URL), - aHomeserverData(homeserverUrl = "https://no.sliding.sync"), - aHomeserverData(homeserverUrl = "https://invalid"), - ) -} - -fun aHomeserverData( - homeserverUrl: String = AuthenticationConfig.MATRIX_ORG_URL, -): HomeserverData { - return HomeserverData(homeserverUrl = homeserverUrl) -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderView.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderView.kt deleted file mode 100644 index 8335dde112..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderView.kt +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -@file:OptIn(ExperimentalMaterial3Api::class) - -package io.element.android.features.login.impl.screens.searchaccountprovider - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.consumeWindowInsets -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Scaffold -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.FocusDirection -import androidx.compose.ui.platform.LocalFocusManager -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.tooling.preview.PreviewParameter -import androidx.compose.ui.unit.dp -import io.element.android.appconfig.AuthenticationConfig -import io.element.android.compound.tokens.generated.CompoundIcons -import io.element.android.features.login.impl.R -import io.element.android.features.login.impl.accountprovider.AccountProvider -import io.element.android.features.login.impl.accountprovider.AccountProviderView -import io.element.android.features.login.impl.changeserver.ChangeServerEvents -import io.element.android.features.login.impl.changeserver.ChangeServerView -import io.element.android.features.login.impl.resolver.HomeserverData -import io.element.android.libraries.architecture.AsyncData -import io.element.android.libraries.designsystem.atomic.molecules.IconTitleSubtitleMolecule -import io.element.android.libraries.designsystem.components.BigIcon -import io.element.android.libraries.designsystem.components.button.BackButton -import io.element.android.libraries.designsystem.components.form.textFieldState -import io.element.android.libraries.designsystem.modifiers.onTabOrEnterKeyFocusNext -import io.element.android.libraries.designsystem.preview.ElementPreview -import io.element.android.libraries.designsystem.preview.PreviewsDayNight -import io.element.android.libraries.designsystem.theme.components.CircularProgressIndicator -import io.element.android.libraries.designsystem.theme.components.Icon -import io.element.android.libraries.designsystem.theme.components.TextField -import io.element.android.libraries.designsystem.theme.components.TopAppBar -import io.element.android.libraries.testtags.TestTags -import io.element.android.libraries.testtags.testTag -import io.element.android.libraries.ui.strings.CommonStrings - -/** - * https://www.figma.com/file/o9p34zmiuEpZRyvZXJZAYL/FTUE?type=design&node-id=611-61435 - */ -@Composable -fun SearchAccountProviderView( - state: SearchAccountProviderState, - onBackClick: () -> Unit, - onLearnMoreClick: () -> Unit, - onSuccess: () -> Unit, - modifier: Modifier = Modifier, -) { - val eventSink = state.eventSink - Scaffold( - modifier = modifier, - topBar = { - TopAppBar( - title = {}, - navigationIcon = { BackButton(onClick = onBackClick) } - ) - } - ) { padding -> - Box( - modifier = Modifier - .fillMaxSize() - .imePadding() - .padding(padding) - .consumeWindowInsets(padding) - ) { - LazyColumn(modifier = Modifier.fillMaxWidth(), state = rememberLazyListState()) { - item { - IconTitleSubtitleMolecule( - modifier = Modifier.padding(top = 16.dp, bottom = 40.dp, start = 16.dp, end = 16.dp), - iconStyle = BigIcon.Style.Default(CompoundIcons.Search()), - title = stringResource(id = R.string.screen_account_provider_form_title), - subTitle = stringResource(id = R.string.screen_account_provider_form_subtitle), - ) - } - item { - // TextInput - var userInputState by textFieldState(stateValue = state.userInput) - val focusManager = LocalFocusManager.current - TextField( - value = userInputState, - // readOnly = isLoading, - modifier = Modifier - .fillMaxWidth() - .padding(start = 16.dp, end = 16.dp, bottom = 16.dp) - .onTabOrEnterKeyFocusNext(focusManager) - .testTag(TestTags.changeServerServer), - onValueChange = { - userInputState = it - eventSink(SearchAccountProviderEvents.UserInput(it)) - }, - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Uri, - imeAction = ImeAction.Done, - ), - keyboardActions = KeyboardActions(onDone = { - focusManager.moveFocus(FocusDirection.Down) - }), - singleLine = true, - trailingIcon = if (userInputState.isNotEmpty()) { - { - Box( - Modifier.clickable( - onClickLabel = stringResource(CommonStrings.action_clear), - role = Role.Button, - ) { - userInputState = "" - eventSink(SearchAccountProviderEvents.UserInput("")) - } - ) { - Icon( - imageVector = CompoundIcons.Close(), - contentDescription = stringResource(CommonStrings.action_clear) - ) - } - } - } else { - null - }, - supportingText = stringResource(id = R.string.screen_account_provider_form_notice), - ) - } - - when (state.userInputResult) { - is AsyncData.Failure -> { - // Ignore errors (let the user type more chars) - } - is AsyncData.Loading -> { - item { - Box( - modifier = Modifier - .fillMaxSize() - ) { - CircularProgressIndicator( - modifier = Modifier.align(Alignment.Center) - ) - } - } - } - is AsyncData.Success -> { - items(state.userInputResult.data) { homeserverData -> - val item = homeserverData.toAccountProvider() - AccountProviderView( - item = item, - onClick = { - state.changeServerState.eventSink.invoke(ChangeServerEvents.ChangeServer(item)) - } - ) - } - } - AsyncData.Uninitialized -> Unit - } - item { - Spacer(Modifier.height(32.dp)) - } - } - ChangeServerView( - state = state.changeServerState, - onLearnMoreClick = onLearnMoreClick, - onSuccess = onSuccess, - ) - } - } -} - -@Composable -private fun HomeserverData.toAccountProvider(): AccountProvider { - val isMatrixOrg = homeserverUrl == AuthenticationConfig.MATRIX_ORG_URL - return AccountProvider( - url = homeserverUrl, - subtitle = if (isMatrixOrg) stringResource(id = R.string.screen_change_account_provider_matrix_org_subtitle) else null, - // There is no need to know for other servers right now - isPublic = isMatrixOrg, - isMatrixOrg = isMatrixOrg, - ) -} - -@PreviewsDayNight -@Composable -internal fun SearchAccountProviderViewPreview(@PreviewParameter(SearchAccountProviderStateProvider::class) state: SearchAccountProviderState) = ElementPreview { - SearchAccountProviderView( - state = state, - onBackClick = {}, - onLearnMoreClick = {}, - onSuccess = {}, - ) -} diff --git a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/web/WebClientUrlForAuthenticationRetriever.kt b/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/web/WebClientUrlForAuthenticationRetriever.kt deleted file mode 100644 index df08cf468b..0000000000 --- a/features/login/impl/src/main/kotlin/io/element/android/features/login/impl/web/WebClientUrlForAuthenticationRetriever.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.web - -import androidx.core.net.toUri -import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.ContributesBinding -import io.element.android.appconfig.AuthenticationConfig -import io.element.android.features.login.impl.screens.createaccount.AccountCreationNotSupported -import io.element.android.libraries.wellknown.api.WellknownRetriever -import timber.log.Timber - -interface WebClientUrlForAuthenticationRetriever { - suspend fun retrieve(homeServerUrl: String): String -} - -@ContributesBinding(AppScope::class) -class DefaultWebClientUrlForAuthenticationRetriever( - private val wellknownRetriever: WellknownRetriever, -) : WebClientUrlForAuthenticationRetriever { - override suspend fun retrieve(homeServerUrl: String): String { - if (homeServerUrl != AuthenticationConfig.MATRIX_ORG_URL) { - Timber.w("Temporary account creation flow is only supported on matrix.org") - throw AccountCreationNotSupported() - } - val wellknown = wellknownRetriever.getElementWellKnown(homeServerUrl).dataOrNull() - ?: throw AccountCreationNotSupported() - val registrationHelperUrl = wellknown.registrationHelperUrl - return if (registrationHelperUrl != null) { - registrationHelperUrl.toUri() - .buildUpon() - .appendQueryParameter("hs_url", homeServerUrl) - .build() - .toString() - } else { - throw AccountCreationNotSupported() - } - } -} diff --git a/features/login/impl/src/main/res/values-ar/translations.xml b/features/login/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..181b38ec24 --- /dev/null +++ b/features/login/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,109 @@ + + + "تغيير مزوّد الحسابات" + "عنوان السيرفر" + "أدخِل عبارة بحث أو عنوان نطاق." + "ابحث عن شركة، أو مجتمع، أو سيرفر خاص." + "ابحث عن مزوّد حسابات" + "هذا المكان الذي تقطن فيه رسائلك — تماماً كاستخدامك مزوّد بريد إلكتروني للاحتفاظ برسائل البريد خاصّتك فيه." + "أنت على وشك تسجيل الدخول إلى %s" + "هذا المكان الذي تقطن فيه رسائلك — تماماً كاستخدامك مزوّد بريد إلكتروني للاحتفاظ برسائل البريد خاصّتك فيه." + "أنت على وشك إنشاء حساب في %s" + "إن Matrix.org سيرفر ضخم ومجاني في شبكة Matrix العامّة وُجِد من أجل مراسلات آمنة ولا مركزية، يُدار من قِبل مؤسسة Matrix.org." + "غير ذلك" + "استخدم مزوّد حسابات آخر كسيرفرك الخاص أو حساب عمل." + "تغيير مزوّد الحسابات" + "Google Play" + "تطبيق Element Pro مطلوب على %1$s. يرجى تنزيله من المتجر." + "Element Pro مطلوب" + "لم نستطع الوصول لهذا السيرفر. رجاءً تحقق إذا ما كنت أدخلت عنوان الـURL بشكل صحيح. إذا كان الـURL صحيحاً فراسل إدارة السيرفر خاصتك لمزيد من المساعدة." + "الخادم غير متاح بسبب مشكلة في ملف .well-known: +%1$s" + "لا يدعم موفّر الحساب المحدد ميزة Sliding Sync. يلزم ترقية الخادم لاستخدام %1$s." + "غير مسموح لـ %1$s بالاتصال بـ %2$s." + "تم إعداد هذا التطبيق للسماح بـ: %1$s." + "موفّر الحساب %1$s غير مسموح به." + "عنوان الـ URL للسيرفر" + "أدخل عنوان نطاق." + "ما عنوان السيرفر خاصتك؟" + "اختر خادمك" + "إنشاء حساب" + "هذا الحساب محذوف." + "اسم المستخدم و/أو كلمة المرور غير صحيحة" + "معرّف المستخدم هذا غير صالح. التنسيق المتوقّع: \'@user:homeserver.org\'" + "تم إعداد هذا الخادم لاستخدام رموز التحديث. وهي غير مدعومة عند استخدام تسجيل الدخول بكلمة المرور." + "لا يتيح المخدِّم المختار تسجيلَ الدخول بكلمة سرّ أو OAuth. راجع المسؤول أو اختر مخدِّماً آخر." + "أدخِل تفاصيلك" + "Matrix عبارة عن شبكة مفتوحة للاتصالات الآمنة واللا مركزية." + "أهلاً بعودتك!" + "تسجيل الدخول إلى %1$s" + "فتح Element Classic" + "افتح Element Classic على جهازك" + "انتقل إلى الإعدادات > الأمان والخصوصية" + "في إدارة مفاتيح التشفير، اختر استرداد الرسائل المشفّرة" + "اتبع التعليمات لتفعيل تخزين مفاتيحك" + "عُد إلى %1$s" + "فعّل تخزين مفاتيحك قبل المتابعة إلى %1$s" + "الإصدار %1$s" + "جارٍ التحقق من الحساب" + "تسجيل الدخول يدوياً" + "تسجيل الدخول إلى %1$s" + "تسجيل الدخول باستخدام رمز QR" + "إنشاء حساب" + "مرحبًا بعودتك" + "مرحباً بك في أسرع %1$s على الإطلاق. مزوَّد من أجل سرعةٍ وبساطة." + "مرحباً بك في %1$s. المعزَّز، من أجل سرعةٍ وبساطة." + "Be in your element" + "جارٍ إنشاء اتصال آمن" + "تعذّر إنشاء اتصال آمن بالجهاز الجديد. لا تزال أجهزتك الحالية آمنة ولا داعي للقلق بشأنها." + "ماذا الآن؟" + "حاول تسجيل الدخول مجددًا باستخدام رمز QR إذا كانت هذه مشكلة في الشبكة." + "إذا واجهت المشكلة نفسها، جرّب شبكة Wi-Fi مختلفة أو استخدم بيانات الهاتف المحمول بدلًا من Wi-Fi." + "إذا لم ينجح ذلك، سجّل الدخول يدويًا" + "الاتصال غير آمن" + "سيُطلب منك إدخال الرقمين الظاهرين على هذا الجهاز." + "أدخل الرقم أدناه على جهازك الآخر" + "سجّل الدخول إلى جهازك الآخر ثم حاول مرة أخرى، أو استخدم جهازًا آخر تم تسجيل الدخول عليه بالفعل." + "لم يتم تسجيل الدخول على الجهاز الآخر" + "تم إلغاء تسجيل الدخول على الجهاز الآخر." + "تم إلغاء طلب تسجيل الدخول" + "تم رفض تسجيل الدخول على الجهاز الآخر." + "تم رفض تسجيل الدخول" + "لست بحاجة إلى فعل أي شيء آخر." + "جهازك الآخر مسجّل الدخول بالفعل" + "انتهت صلاحية تسجيل الدخول. يرجى المحاولة مرة أخرى." + "لم يكتمل تسجيل الدخول في الوقت المحدد" + "جهازك الآخر لا يدعم تسجيل الدخول إلى %s باستخدام رمز QR. + +جرّب تسجيل الدخول يدويًا، أو امسح رمز QR ضوئيًا باستخدام جهاز آخر." + "رمز QR غير مدعوم" + "لا يدعم موفّر حسابك %1$s." + "%1$s غير مدعوم" + "جاهز للمسح الضوئي" + "افتح %1$s على جهاز سطح مكتب" + "انقر على صورتك الرمزية" + "اختر %1$s" + "“ربط جهاز جديد”" + "امسح رمز QR ضوئيًا باستخدام هذا الجهاز" + "متاح فقط إذا كان موفّر حسابك يدعم ذلك." + "افتح %1$s على جهاز آخر للحصول على رمز QR" + "استخدم رمز QR المعروض على الجهاز الآخر." + "حاول مرة أخرى" + "رمز QR غير صحيح" + "الانتقال إلى إعدادات الكاميرا" + "تحتاج إلى منح %1$s إذنًا لاستخدام كاميرا جهازك للمتابعة." + "اسمح بالوصول إلى الكاميرا لمسح رمز QR ضوئيًا" + "امسح رمز QR ضوئيًا" + "البدء من جديد" + "حدث خطأ غير متوقع. يرجى المحاولة مرة أخرى." + "في انتظار جهازك الآخر" + "قد يطلب موفّر حسابك الرمز التالي للتحقق من تسجيل الدخول." + "رمز التحقق الخاص بك" + "تغيير مزوّد الحسابات" + "سيرفر خاص بموظّفي Element." + "Matrix عبارة عن شبكة مفتوحة للاتصالات الآمنة واللا مركزية." + "هذا المكان الذي تقطن فيه رسائلك — تماماً كاستخدامك مزوّد بريد إلكتروني للاحتفاظ برسائل البريد خاصّتك فيه." + "أنت على وشك تسجيل الدخول إلى %1$s" + "اختر موفّر الحساب" + "أنت على وشك إنشاء حساب في %1$s" + diff --git a/features/login/impl/src/main/res/values-de/translations.xml b/features/login/impl/src/main/res/values-de/translations.xml index 89e4412d0f..4f04c87d34 100644 --- a/features/login/impl/src/main/res/values-de/translations.xml +++ b/features/login/impl/src/main/res/values-de/translations.xml @@ -37,7 +37,14 @@ "Matrix ist ein offenes Netzwerk für eine sichere, dezentrale Kommunikation." "Willkommen zurück!" "Anmelden bei %1$s" + "Element Classic öffnen" + "Öffne Element Classic auf deinem Gerät" + "Geh zu Einstellungen > Sicherheit & Datenschutz" + "Folge den Anweisungen, um den Schlüsselspeicher zu aktivieren." + "Zurück zu %1$s" + "Aktiviere deinen Schlüsselspeicher, bevor du mit %1$s fortfährst." "Version %1$s" + "Konto wird geprüft" "Manuell anmelden" "Anmelden bei %1$s" "Mit QR-Code anmelden" diff --git a/features/login/impl/src/main/res/values-es/translations.xml b/features/login/impl/src/main/res/values-es/translations.xml index 3b9ffbe2dd..13a93164a6 100644 --- a/features/login/impl/src/main/res/values-es/translations.xml +++ b/features/login/impl/src/main/res/values-es/translations.xml @@ -13,6 +13,9 @@ "Otro" "Usa un proveedor de cuentas diferente, como tu propio servidor privado o una cuenta de trabajo." "Cambiar proveedor de cuentas" + "Google Play" + "%1$s requiere la aplicación Element Pro. Descárgala de la tienda." + "Se requiere Element Pro" "No hemos podido acceder a este servidor base. Comprueba que has introducido correctamente la dirección. Si es correcta, ponte en contacto con el administrador de tu servidor base para obtener más ayuda." "El servidor no está disponible debido a un problema en el archivo .well-known: %1$s" @@ -22,10 +25,18 @@ "No se permite el proveedor de cuentas %1$s." "URL del servidor base" "Introduce una dirección de dominio." + "Iniciar sesión" + "Crear cuenta" "¿Cuál es la dirección de tu servidor?" + "Si tu cuenta te la proporciona tu empresa o una comunidad, cambia el proveedor de la cuenta (ejemplo: nombredeempresa.com)." + "Crea una cuenta gratuita en matrix.org. Si deseas crear una cuenta con otro proveedor, modifícala según corresponda (por ejemplo: communityname.org)." + "Proveedor de cuentas" + "ejemplo.com" "Selecciona tu servidor" + "Introduce tu proveedor de cuenta" + "Elegir proveedor de cuentas" "Crear cuenta" - "Esta cuenta ha sido desactivada." + "Esta cuenta ha sido eliminada." "Usuario y/o contraseña incorrectos" "Este no es un id de usuario válido. Formato esperado: \'@user:homeserver.org\'" "Este servidor está configurado para utilizar tokens de actualización. Estos no son compatibles cuando se utiliza el inicio de sesión basado en contraseña." @@ -34,11 +45,20 @@ "Matrix es una red abierta para una comunicación segura y descentralizada." "¡Hola de nuevo!" "Iniciar sesión en %1$s" + "Abrir Element Classic" + "Abre Element Classic en tu dispositivo" + "Ve a Ajustes > Seguridad y privacidad" + "En «Gestión de claves criptográficas», selecciona «Recuperación de mensajes cifrados»" + "Sigue las instrucciones para activar tu almacén de claves" + "Vuelve a %1$s" + "Activa tu almacén de claves antes de continuar con %1$s" "Versión %1$s" + "Comprobación de la cuenta" "Iniciar sesión manualmente" "Iniciar sesión en %1$s" "Iniciar sesión con un código QR" "Crear cuenta" + "¡Hola de nuevo!" "Bienvenido al %1$s más rápido de todos los tiempos. Diseñado para la velocidad y la simplicidad." "Bienvenido a %1$s. Vitaminado, para mayor rapidez y sencillez." "Siéntete en tu Elemento" @@ -57,6 +77,8 @@ "Solicitud de inicio de sesión cancelada" "El inicio de sesión se rechazó en el otro dispositivo." "Inicio de sesión rechazado" + "No tienes que hacer nada más." + "Tu otro dispositivo ya está conectado" "El inicio de sesión ha caducado. Inténtalo de nuevo." "El inicio de sesión no se completó a tiempo" "Tu otro dispositivo no admite el inicio de sesión en %s con un código QR. diff --git a/features/login/impl/src/main/res/values-et/translations.xml b/features/login/impl/src/main/res/values-et/translations.xml index dc37ed3e38..a27bc18e3e 100644 --- a/features/login/impl/src/main/res/values-et/translations.xml +++ b/features/login/impl/src/main/res/values-et/translations.xml @@ -25,8 +25,16 @@ "%1$s teenusepakkuja pole lubatud." "Koduserveri url" "Sisesta domeeni aadress." + "Logi sisse" + "Loo kasutajakonto" "Mis on sinu koduserveri aadress?" + "Kui sinu kasutajakonto paikneb äriühingu või kogukonna serveris, siis muuda kontoteenuse pakkujat (näiteks: minufirmanimi.ee)." + "Loo tasuta kasutajakonto matrix.org serverisse. Kui soovid luua kasutajakonto mõne teise teenusepakkuja juures, siis muuda seda vastavalt (näiteks: minukogukond.ee)." + "Teenusepakkuja" + "domeeninäidis.ee" "Vali oma server" + "Sisesta oma kasutajakonto teenusepakkuja" + "Vali kasutajakonto teenusepakkuja" "Loo kasutajakonto" "See kasutajakonto on kustutatud." "Vigane kasutajanimi ja/või salasõna" diff --git a/features/login/impl/src/main/res/values-fa/translations.xml b/features/login/impl/src/main/res/values-fa/translations.xml index 38c2c11eaa..ce0ab0da20 100644 --- a/features/login/impl/src/main/res/values-fa/translations.xml +++ b/features/login/impl/src/main/res/values-fa/translations.xml @@ -14,8 +14,14 @@ "استفاده از فراهم کنندهٔ حسابی دیگر چون کارساز خصوصی خوتان یا حسابی کاری." "تغییر فراهم کنندهٔ حساب" "پلی گپگل" + "برنامه Element Pro برای %1$s مورد نیاز است. لطفاً آن را از فروشگاه دانلود کنید." + "المنت پرو مورد نیاز است" "ما نتوانستیم به این کارساز خانگی برسیم. لطفاً بررسی کنید که URL کارساز اصلی را به درستی وارد کرده اید. اگر URL صحیح است، برای کمک بیشتر با مدیر کارساز خانگی خود تماس بگیرید." "سرور به دلیل مشکلی در فایل .well-known در دسترس نیست: %1$s" + "ارائه دهنده حساب انتخاب شده از همگام سازی کشویی پشتیبانی نمی کند. برای استفاده از %1$s، ارتقاء سرور لازم است." + "%1$s اجازه اتصال به %2$s را ندارد." + "این برنامه طوری پیکربندی شده است که اجازه موارد زیر را بدهد: %1$s." + "ارائه دهنده حساب %1$s مجاز نیست." "نشانی کارساز خانگی" "ورود نشانی دامنه." "نشانی کارسازتان چیست؟" @@ -30,11 +36,20 @@ "ماتریکس شبکه‌ای بار برای ارتباطات نامتمرکز و امن است." "خوش برگشتید!" "ورود به %1$s" + "باز کردن Element کلاسیک" + "Element Classic را روی دستگاه خود باز کنید" + "به تنظیمات > امنیت و حریم خصوصی بروید" + "در مدیریت کلیدهای رمزنگاری، بازیابی پیام‌های رمزگذاری‌شده را انتخاب کنید." + "برای فعال کردن فضای ذخیره‌سازی کلید، دستورالعمل‌ها را دنبال کنید" + "به %1$s برگردید" + "قبل از ادامه به %1$s، فضای ذخیره‌سازی کلید خود را فعال کنید" "نگارش %1$s" + "درحال بررسی حساب…" "ورود دستی" "ورود به %1$s" "ورود با کد QR" "ایجاد حساب" + "خوش برگشتید" "به سریع‌ترین %1$s خوش آمدید. بازطرّاحی شده برای سرعت و سادگی." "به %1$s خوش آمدید. بازطرّاحی شده برای سرعت و سادگی." "در المنتتان باشید" @@ -53,6 +68,8 @@ "درخواست ورد لغو شد" "ورود به دست افزارهٔ دیگر رد شد." "ورود رد شد" + "لازم نیست کار دیگری انجام دهید." + "دستگاه دیگر شما قبلاً وارد سیستم شده است" "ورود منقضی شد. لطفاً دوباره تلاش کنید." "ورود در زمان معیّن کامل نشد" "افزارهٔ دیگرتان از ورود به %s با کد پاس پشتیبانی نمی‌کند. @@ -67,6 +84,7 @@ "گزینش %1$s" "«پیوند افزارهٔ جدید»" "پویش کد پاس با این افزاره" + "فقط در صورتی موجود است که ارائه دهنده حساب شما از آن پشتیبانی کند." "گشودن %1$s روی افزاره‌ای دیگر برای گرفتن کد پاس" "استفاده از کد پاس نشان داده روی افزارهٔ دیگر." "تلاش دوباره" @@ -85,5 +103,6 @@ "ماتریکس شبکه‌ای بار برای ارتباطات نامتمرکز و امن است." "جایی که گفت‌وگوهایتان خواهند زیست — درست مثل استفاده‌تان از فراهم کنندهٔ رایانامه‌ای برای نگه داشتن رایانامه‌هایتان." "دارید به %1$s وارد می‌شوید" + "ارائه دهنده حساب را انتخاب کنید" "دارید روی %1$s حساب می‌سازید" diff --git a/features/login/impl/src/main/res/values-fi/translations.xml b/features/login/impl/src/main/res/values-fi/translations.xml index 8561bcfce3..493ddee2f8 100644 --- a/features/login/impl/src/main/res/values-fi/translations.xml +++ b/features/login/impl/src/main/res/values-fi/translations.xml @@ -25,8 +25,16 @@ "Palveluntarjoaja %1$s ei ole sallittu." "Kotipalvelimen osoite" "Anna verkkotunnuksen osoite." + "Kirjaudu sisään" + "Luo tili" "Mikä on palvelimesi osoite?" + "Jos tilisi on yrityksesi tai yhteisön tarjoama, vaihda palveluntarjoaja (esimerkki: companyname.com)." + "Luo tili matrix.org -palvelimelle ilmaiseksi. Jos haluat luoda tilin eri palveluntarjoajan kautta, muuta sitä vastaavasti (esimerkiksi: communityname.org)." + "Palveluntarjoaja" + "example.com" "Valitse palvelimesi" + "Anna palveluntarjoajasi" + "Valitse palveluntarjoaja" "Luo tili" "Tämä tili on poistettu." "Väärä käyttäjänimi ja/tai salasana" diff --git a/features/login/impl/src/main/res/values-fr/translations.xml b/features/login/impl/src/main/res/values-fr/translations.xml index 504517aad7..0af658d34f 100644 --- a/features/login/impl/src/main/res/values-fr/translations.xml +++ b/features/login/impl/src/main/res/values-fr/translations.xml @@ -25,8 +25,16 @@ "Le fournisseur de compte %1$s n’est pas autorisé." "URL du serveur d’accueil" "Saisissez une adresse de domaine." + "Se connecter" + "Créer un compte" "Quelle est l’adresse de votre serveur ?" + "Si votre fournisseur de compte est fourni par votre entreprise ou une communauté, veuillez le saisir ici (exemple : monentreprise.com)." + "Créez un compte sur matrix.org gratuitement. Si vous souhaitez créer un compte auprès d’un autre fournisseur, veuillez modifier l’adresse ici (exemple : monassociation.org)." + "Fournisseur de compte" + "exemple.com" "Choisissez votre serveur" + "Saisissez votre fournisseur de compte" + "Choisissez un fournisseur de compte" "Créer un compte" "Ce compte a été supprimé." "Nom d’utilisateur et/ou mot de passe incorrects" diff --git a/features/login/impl/src/main/res/values-in/translations.xml b/features/login/impl/src/main/res/values-in/translations.xml index 1d29c5b619..34ba1bd0ed 100644 --- a/features/login/impl/src/main/res/values-in/translations.xml +++ b/features/login/impl/src/main/res/values-in/translations.xml @@ -25,8 +25,16 @@ "Penyedia akun %1$s tidak diizinkan." "URL Homeserver" "Masukkan alamat domain." + "Login" + "Buat akun" "Apa alamat server Anda?" + "Jika akun Anda disediakan oleh perusahaan atau komunitas Anda, maka ubah penyedia akun (contoh: companyname.com)." + "Buat akun di matrix.org secara gratis. Jika anda ingin membuat akun dengan penyedia lain, ubah sesuai kebutuhan (contoh: communityname.org)." + "Penyedia akun" + "contoh.com" "Pilih server Anda" + "Masukkan penyedia akun Anda" + "Pilih penyedia akun" "Buat akun" "Akun ini telah dinonaktifkan." "Nama pengguna dan/atau kata sandi salah" diff --git a/features/login/impl/src/main/res/values-ja/translations.xml b/features/login/impl/src/main/res/values-ja/translations.xml index 42698e27dc..b4d6f16721 100644 --- a/features/login/impl/src/main/res/values-ja/translations.xml +++ b/features/login/impl/src/main/res/values-ja/translations.xml @@ -24,8 +24,16 @@ "アカウント提供元 %1$s は許可されていません。" "ホームサーバーURL" "ドメイン名を入力してください" + "サインイン" + "アカウントを作成" "サーバーのアドレスは何ですか?" + "アカウントが会社やコミュニティから発行されている場合は、アカウント提供元を変更してください (例: kaisha-mei.com)。" + "matrix.org 上に無料でアカウントを作成できます。異なるアカウント提供元上にアカウントを作成したい場合は、それにならって変更してください (例: dantai-mei.org)。" + "アカウント提供元" + "example.com" "サーバーを選択" + "アカウント提供元を入力" + "アカウント提供元を選択" "アカウントを作成" "アカウントは削除されました。" "ユーザー名またはパスワードが違います" diff --git a/features/login/impl/src/main/res/values-pl/translations.xml b/features/login/impl/src/main/res/values-pl/translations.xml index 634d856cdf..81d8570e32 100644 --- a/features/login/impl/src/main/res/values-pl/translations.xml +++ b/features/login/impl/src/main/res/values-pl/translations.xml @@ -25,8 +25,16 @@ "Dostawca konta %1$s jest niedozwolony." "URL serwera domowego" "Wprowadź adres domeny." + "Zaloguj" + "Utwórz konto" "Jaki jest adres Twojego serwera?" + "Jeśli uzyskałeś konto od firmy lub społeczności, wprowadź dostawcę konta (na przykład: nazwafirmy.com)" + "Załóż darmowe konto na matrix.org. Jeśli chcesz założyć konto u innego dostawcy wprowadź własny adres (na przykład: nazwaspołeczności.org)." + "Dostawca konta" + "przykład.com" "Wybierz swój serwer" + "Wprowadź dostawcę swojego konta" + "Wybierz dostawcę konta" "Utwórz konto" "To konto zostało usunięte." "Nieprawidłowa nazwa użytkownika i/lub hasło" diff --git a/features/login/impl/src/main/res/values-ro/translations.xml b/features/login/impl/src/main/res/values-ro/translations.xml index b44242abf8..6835c0a15d 100644 --- a/features/login/impl/src/main/res/values-ro/translations.xml +++ b/features/login/impl/src/main/res/values-ro/translations.xml @@ -25,8 +25,16 @@ "Furnizorul de cont %1$s nu este permis." "Adresa URL a homeserver-ului" "Introduceți o adresă de domeniu." + "Autentificare" + "Creați un cont" "Care este adresa serverului dumneavoastră?" + "Dacă contul este furnizat de compania dumneavoastră sau de o comunitate, schimbați furnizorul contului (exemplu: numecompanie.com)." + "Creați un cont gratuit pe matrix.org. Dacă doriți să creați un cont la un alt furnizor, schimbați-l în consecință (exemplu: numecomunitate.org)." + "Furnizor de cont" + "exemplu.ro" "Selectați serverul dumneavoastra" + "Introduceți furnizorul contului dumneavoastră" + "Alegeți un furnizor de cont" "Creați un cont" "Acest cont a fost șters." "Utilizator și/sau parolă incorecte" diff --git a/features/login/impl/src/main/res/values-sv/translations.xml b/features/login/impl/src/main/res/values-sv/translations.xml index 396f2025b7..fe2d443ce3 100644 --- a/features/login/impl/src/main/res/values-sv/translations.xml +++ b/features/login/impl/src/main/res/values-sv/translations.xml @@ -28,7 +28,7 @@ "Vad är adressen till din server?" "Välj din server" "Skapa konto" - "Detta konto har avaktiverats." + "Detta konto har raderats." "Felaktigt användarnamn och/eller lösenord" "Detta är inte en giltig användaridentifierare. Förväntat format: \'@användare:hemserver.org\'" "Den här servern är konfigurerad för att använda uppdateringstokens. Dessa stöds inte när du använder lösenordsbaserad inloggning." diff --git a/features/login/impl/src/main/res/values-uk/translations.xml b/features/login/impl/src/main/res/values-uk/translations.xml index 60959c80d4..918caf5530 100644 --- a/features/login/impl/src/main/res/values-uk/translations.xml +++ b/features/login/impl/src/main/res/values-uk/translations.xml @@ -25,8 +25,16 @@ "Постачальник облікового запису %1$s не дозволений." "URL-адреса домашнього сервера" "Введіть адресу домену." + "Увійти" + "Створити обліковий запис" "Яка адреса вашого сервера?" + "Якщо ваш обліковий запис надано вашою компанією або спільнотою, змініть постачальника облікового запису (наприклад: companyname.com)." + "Створіть обліковий запис на matrix.org безплатно. Якщо ви хочете створити обліковий запис у іншого постачальника, змініть його відповідно (наприклад: communityname.org)." + "Постачальник облікового запису" + "example.com" "Виберіть свій сервер" + "Вкажіть постачальника вашого облікового запису" + "Оберіть постачальника облікового запису" "Створити обліковий запис" "Цей обліковий запис було видалено." "Неправильне ім\'я користувача та/або пароль" diff --git a/features/login/impl/src/main/res/values-zh-rTW/translations.xml b/features/login/impl/src/main/res/values-zh-rTW/translations.xml index c4d16f5928..76477eb36e 100644 --- a/features/login/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/login/impl/src/main/res/values-zh-rTW/translations.xml @@ -11,7 +11,7 @@ "您即將在 %s 建立帳號" "Matrix.org 由 Matrix.org 基金會營運,是用於安全、去中心化通訊的公共 Matrix 網路上的大型免費伺服器。" "其他" - "使用不同的帳戶提供者,例如您自己的伺服器或工作帳號。" + "使用不同的帳號提供者,例如您自己的伺服器或工作帳號。" "更改帳號提供者" "Google Play" "%1$s 需要 Element Pro 應用程式。請從商店下載。" @@ -28,7 +28,7 @@ "您的伺服器地址?" "選擇您的伺服器" "建立帳號" - "這個帳號已被停用。" + "此帳號已被刪除。" "不正確的使用者名稱或密碼" "此非有效的使用者識別字串。預期的格式:‘@user:homeserver.org’" "此伺服器已設定為使用重新整理權杖。使用以密碼為基礎的登入方式時,不支援這些功能。" diff --git a/features/login/impl/src/main/res/values-zh/translations.xml b/features/login/impl/src/main/res/values-zh/translations.xml index 16afe7d5bd..85de302dc1 100644 --- a/features/login/impl/src/main/res/values-zh/translations.xml +++ b/features/login/impl/src/main/res/values-zh/translations.xml @@ -25,8 +25,16 @@ "账户提供者 %1$s 不被允许。" "主服务器 URL" "输入域名地址。" + "登录" + "创建账户" "你的服务器地址是什么?" + "如果你的账户由你的公司或社区提供,则应更改账户提供者(例如:companyname.com)。" + "在 matrix.org 创建免费账户。如果你想使用其它服务提供者创建账户,请相应地更改域名(例如:communityname.org)。" + "账户提供者" + "example.com" "选择服务器" + "输入你的账户提供者" + "选择账户提供者" "创建账户" "此账户已被删除。" "用户名与(或)密码不正确" diff --git a/features/login/impl/src/main/res/values/localazy.xml b/features/login/impl/src/main/res/values/localazy.xml index 10fb6ef04a..7e798081f5 100644 --- a/features/login/impl/src/main/res/values/localazy.xml +++ b/features/login/impl/src/main/res/values/localazy.xml @@ -25,8 +25,16 @@ "Account provider %1$s not allowed." "Homeserver URL" "Enter a domain address." + "Sign in" + "Create account" "What is the address of your server?" + "If your account is provided by your company or a community, then change the account provider (example: companyname.com)." + "Create an account on matrix.org for free. If you want to create an account with a different provider, then change it accordingly (example: communityname.org)." + "Account provider" + "example.com" "Select your server" + "Enter your account provider" + "Choose an account provider" "Create account" "This account has been deleted." "Incorrect username and/or password" diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/DefaultLoginEntryPointTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/DefaultLoginEntryPointTest.kt index a05194d008..8a0bf4c307 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/DefaultLoginEntryPointTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/DefaultLoginEntryPointTest.kt @@ -12,12 +12,11 @@ import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.bumble.appyx.core.modality.BuildContext import com.bumble.appyx.testing.junit4.util.MainDispatcherRule import com.google.common.truth.Truth.assertThat -import io.element.android.features.enterprise.test.FakeEnterpriseService import io.element.android.features.login.api.LoginEntryPoint -import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.accountprovider.anAccountProviderDataSource import io.element.android.features.login.impl.classic.FakeElementClassicConnection import io.element.android.features.preferences.test.FakePreferencesEntryPoint -import io.element.android.libraries.oauth.test.customtab.FakeOAuthActionFlow +import io.element.android.libraries.oauth.test.FakeOAuthActionFlow import io.element.android.tests.testutils.lambda.lambdaError import io.element.android.tests.testutils.node.TestParentNode import kotlinx.coroutines.test.runTest @@ -38,7 +37,7 @@ class DefaultLoginEntryPointTest { LoginFlowNode( buildContext = buildContext, plugins = plugins, - accountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()), + accountProviderDataSource = anAccountProviderDataSource(), oAuthActionFlow = FakeOAuthActionFlow(), appCoroutineScope = backgroundScope, elementClassicConnection = FakeElementClassicConnection(), diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControlTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControlTest.kt index e3cf1c0ea7..fbfae984fc 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControlTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accesscontrol/DefaultAccountProviderAccessControlTest.kt @@ -11,13 +11,9 @@ package io.element.android.features.login.impl.accesscontrol import com.google.common.truth.Truth.assertThat import io.element.android.features.enterprise.test.FakeEnterpriseService import io.element.android.features.login.impl.changeserver.AccountProviderAccessException -import io.element.android.features.wellknown.test.FakeWellknownRetriever -import io.element.android.features.wellknown.test.anElementWellKnown import io.element.android.libraries.matrix.test.AN_ACCOUNT_PROVIDER import io.element.android.libraries.matrix.test.AN_ACCOUNT_PROVIDER_2 import io.element.android.libraries.matrix.test.AN_ACCOUNT_PROVIDER_URL -import io.element.android.libraries.wellknown.api.ElementWellKnown -import io.element.android.libraries.wellknown.api.WellknownRetrieverResult import kotlinx.coroutines.test.runTest import org.junit.Assert.assertThrows import org.junit.Test @@ -28,9 +24,7 @@ class DefaultAccountProviderAccessControlTest { val accessControl = createDefaultAccountProviderAccessControl( isEnterpriseBuild = false, isAllowedToConnectToHomeserver = true, - elementWellKnown = anElementWellKnown( - enforceElementPro = true, - ), + enterpriseService = FakeEnterpriseService(isElementProEnforcedResult = { true }), ) accessControl.expectNeedElementProException() } @@ -41,9 +35,7 @@ class DefaultAccountProviderAccessControlTest { isEnterpriseBuild = false, // false here. isAllowedToConnectToHomeserver = false, - elementWellKnown = anElementWellKnown( - enforceElementPro = true, - ), + enterpriseService = FakeEnterpriseService(isElementProEnforcedResult = { true }), ) accessControl.expectNeedElementProException() } @@ -53,8 +45,9 @@ class DefaultAccountProviderAccessControlTest { val accessControl = createDefaultAccountProviderAccessControl( isEnterpriseBuild = false, isAllowedToConnectToHomeserver = true, - elementWellKnown = anElementWellKnown( - enforceElementPro = false, + enterpriseService = FakeEnterpriseService( + isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false } ), ) accessControl.expectAllowed() @@ -65,19 +58,15 @@ class DefaultAccountProviderAccessControlTest { val accessControl = createDefaultAccountProviderAccessControl( isEnterpriseBuild = false, isAllowedToConnectToHomeserver = true, - elementWellKnown = anElementWellKnown( - enforceElementPro = null, - ), ) accessControl.expectAllowed() } @Test - fun `foss build should allow using account provider twith missing wellknown`() = runTest { + fun `foss build should allow using account provider with missing wellknown`() = runTest { val accessControl = createDefaultAccountProviderAccessControl( isEnterpriseBuild = false, isAllowedToConnectToHomeserver = true, - elementWellKnown = null, ) accessControl.expectAllowed() } @@ -88,8 +77,10 @@ class DefaultAccountProviderAccessControlTest { isEnterpriseBuild = false, isAllowedToConnectToHomeserver = false, allowedAccountProviders = listOf(AN_ACCOUNT_PROVIDER_2), - elementWellKnown = anElementWellKnown( - enforceElementPro = false, + enterpriseService = FakeEnterpriseService( + isAllowedToConnectToHomeserverResult = { false }, + isElementProEnforcedResult = { false }, + defaultHomeserverListResult = { listOf(AN_ACCOUNT_PROVIDER_2) }, ), ) accessControl.expectUnauthorizedAccountProviderException() @@ -100,8 +91,9 @@ class DefaultAccountProviderAccessControlTest { val accessControl = createDefaultAccountProviderAccessControl( isEnterpriseBuild = true, isAllowedToConnectToHomeserver = true, - elementWellKnown = anElementWellKnown( - enforceElementPro = true, + enterpriseService = FakeEnterpriseService( + isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { true }, ), ) accessControl.expectAllowed() @@ -112,8 +104,9 @@ class DefaultAccountProviderAccessControlTest { val accessControl = createDefaultAccountProviderAccessControl( isEnterpriseBuild = true, isAllowedToConnectToHomeserver = true, - elementWellKnown = anElementWellKnown( - enforceElementPro = false, + enterpriseService = FakeEnterpriseService( + isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false }, ), ) accessControl.expectAllowed() @@ -125,8 +118,10 @@ class DefaultAccountProviderAccessControlTest { isEnterpriseBuild = true, isAllowedToConnectToHomeserver = false, allowedAccountProviders = listOf(AN_ACCOUNT_PROVIDER_2), - elementWellKnown = anElementWellKnown( - enforceElementPro = true, + enterpriseService = FakeEnterpriseService( + isAllowedToConnectToHomeserverResult = { false }, + isElementProEnforcedResult = { true }, + defaultHomeserverListResult = { listOf(AN_ACCOUNT_PROVIDER_2) }, ), ) accessControl.expectUnauthorizedAccountProviderException() @@ -138,8 +133,10 @@ class DefaultAccountProviderAccessControlTest { isEnterpriseBuild = true, isAllowedToConnectToHomeserver = false, allowedAccountProviders = listOf(AN_ACCOUNT_PROVIDER_2), - elementWellKnown = anElementWellKnown( - enforceElementPro = false, + enterpriseService = FakeEnterpriseService( + isAllowedToConnectToHomeserverResult = { false }, + isElementProEnforcedResult = { false }, + defaultHomeserverListResult = { listOf(AN_ACCOUNT_PROVIDER_2) }, ), ) accessControl.expectUnauthorizedAccountProviderException() @@ -149,22 +146,14 @@ class DefaultAccountProviderAccessControlTest { isEnterpriseBuild: Boolean = false, isAllowedToConnectToHomeserver: Boolean = false, allowedAccountProviders: List = emptyList(), - elementWellKnown: ElementWellKnown? = null, - ) = DefaultAccountProviderAccessControl( - enterpriseService = FakeEnterpriseService( - isEnterpriseBuild = isEnterpriseBuild, + enterpriseService: FakeEnterpriseService = FakeEnterpriseService( isAllowedToConnectToHomeserverResult = { isAllowedToConnectToHomeserver }, defaultHomeserverListResult = { allowedAccountProviders }, - ), - wellknownRetriever = FakeWellknownRetriever( - getElementWellKnownResult = { - if (elementWellKnown == null) { - WellknownRetrieverResult.NotFound - } else { - WellknownRetrieverResult.Success(elementWellKnown) - } - }, - ), + isElementProEnforcedResult = { false }, + ) + ) = DefaultAccountProviderAccessControl( + isEnterpriseBuild = { isEnterpriseBuild }, + enterpriseService = enterpriseService, ) private fun DefaultAccountProviderAccessControl.expectNeedElementProException() { diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSourceFixture.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSourceFixture.kt new file mode 100644 index 0000000000..25bc67144b --- /dev/null +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSourceFixture.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.login.impl.accountprovider + +import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.features.enterprise.test.FakeEnterpriseService +import io.element.android.libraries.preferences.api.store.AppPreferencesStore +import io.element.android.libraries.preferences.test.InMemoryAppPreferencesStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers + +fun anAccountProviderDataSource( + enterpriseService: EnterpriseService = FakeEnterpriseService(), + appPreferencesStore: AppPreferencesStore = InMemoryAppPreferencesStore(), + coroutineScope: CoroutineScope = CoroutineScope(Dispatchers.Unconfined), +) = AccountProviderDataSource( + enterpriseService = enterpriseService, + appPreferencesStore = appPreferencesStore, + coroutineScope = coroutineScope, +) diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSourceTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSourceTest.kt index f86df13335..30e25c8c3e 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSourceTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/AccountProviderDataSourceTest.kt @@ -13,6 +13,7 @@ import com.google.common.truth.Truth.assertThat import io.element.android.appconfig.AuthenticationConfig import io.element.android.features.enterprise.api.EnterpriseService import io.element.android.features.enterprise.test.FakeEnterpriseService +import io.element.android.libraries.preferences.test.InMemoryAppPreferencesStore import io.element.android.tests.testutils.WarmUpRule import kotlinx.coroutines.test.runTest import org.junit.Rule @@ -24,7 +25,7 @@ class AccountProviderDataSourceTest { @Test fun `present - initial state`() = runTest { - val sut = AccountProviderDataSource(FakeEnterpriseService()) + val sut = anAccountProviderDataSource() sut.flow.test { val initialState = awaitItem() assertThat(initialState).isEqualTo( @@ -41,10 +42,10 @@ class AccountProviderDataSourceTest { @Test fun `present - initial state - matrix org`() = runTest { - val sut = AccountProviderDataSource( - FakeEnterpriseService( + val sut = anAccountProviderDataSource( + enterpriseService = FakeEnterpriseService( defaultHomeserverListResult = { listOf(AuthenticationConfig.MATRIX_ORG_URL) } - ) + ), ) sut.flow.test { val initialState = awaitItem() @@ -62,10 +63,10 @@ class AccountProviderDataSourceTest { @Test fun `present - ensure that default homeserver is not star char`() = runTest { - val sut = AccountProviderDataSource( - FakeEnterpriseService( + val sut = anAccountProviderDataSource( + enterpriseService = FakeEnterpriseService( defaultHomeserverListResult = { listOf(EnterpriseService.ANY_ACCOUNT_PROVIDER, AuthenticationConfig.MATRIX_ORG_URL) } - ) + ), ) sut.flow.test { val initialState = awaitItem() @@ -83,7 +84,7 @@ class AccountProviderDataSourceTest { @Test fun `present - user change and reset`() = runTest { - val sut = AccountProviderDataSource(FakeEnterpriseService()) + val sut = anAccountProviderDataSource() sut.flow.test { val initialState = awaitItem() assertThat(initialState.url).isEqualTo(AuthenticationConfig.MATRIX_ORG_URL) @@ -106,7 +107,7 @@ class AccountProviderDataSourceTest { @Test fun `present - set url and reset`() = runTest { - val sut = AccountProviderDataSource(FakeEnterpriseService()) + val sut = anAccountProviderDataSource() sut.flow.test { val initialState = awaitItem() assertThat(initialState.url).isEqualTo(AuthenticationConfig.MATRIX_ORG_URL) @@ -126,4 +127,47 @@ class AccountProviderDataSourceTest { assertThat(resetState.url).isEqualTo(AuthenticationConfig.MATRIX_ORG_URL) } } + + @Test + fun `present - defaults to the most recently used provider from history`() = runTest { + val sut = anAccountProviderDataSource( + appPreferencesStore = InMemoryAppPreferencesStore( + homeserverHistory = listOf("https://example.com", "https://matrix.org"), + ), + ) + sut.flow.test { + assertThat(awaitItem().url).isEqualTo("https://example.com") + } + } + + @Test + fun `present - history is ignored when the account provider is enforced`() = runTest { + val sut = anAccountProviderDataSource( + enterpriseService = FakeEnterpriseService( + defaultHomeserverListResult = { listOf("https://enforced.org") } + ), + appPreferencesStore = InMemoryAppPreferencesStore( + homeserverHistory = listOf("https://example.com"), + ), + ) + sut.flow.test { + assertThat(awaitItem().url).isEqualTo("https://enforced.org") + } + } + + @Test + fun `present - reset returns to the most recently used provider from history`() = runTest { + val sut = anAccountProviderDataSource( + appPreferencesStore = InMemoryAppPreferencesStore( + homeserverHistory = listOf("https://example.com"), + ), + ) + sut.flow.test { + assertThat(awaitItem().url).isEqualTo("https://example.com") + sut.setUrl("https://other.com") + assertThat(awaitItem().url).isEqualTo("https://other.com") + sut.reset() + assertThat(awaitItem().url).isEqualTo("https://example.com") + } + } } diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/SaveAccountProviderToHistoryTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/SaveAccountProviderToHistoryTest.kt new file mode 100644 index 0000000000..0af8188f3f --- /dev/null +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/accountprovider/SaveAccountProviderToHistoryTest.kt @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.login.impl.accountprovider + +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.preferences.test.InMemoryAppPreferencesStore +import io.element.android.tests.testutils.WarmUpRule +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.Test + +class SaveAccountProviderToHistoryTest { + @get:Rule + val warmUpRule = WarmUpRule() + + @Test + fun `invoke saves the current account provider url to history`() = runTest { + val appPreferencesStore = InMemoryAppPreferencesStore() + val accountProviderDataSource = anAccountProviderDataSource() + accountProviderDataSource.setUrl("https://example.com") + val sut = SaveAccountProviderToHistory(accountProviderDataSource, appPreferencesStore) + + sut() + + assertThat(appPreferencesStore.getHomeserverHistoryFlow().first()) + .containsExactly("https://example.com") + } + + @Test + fun `invoke saves the selected provider even after the exposed default has been reset`() = runTest { + val appPreferencesStore = InMemoryAppPreferencesStore() + val accountProviderDataSource = anAccountProviderDataSource(appPreferencesStore = appPreferencesStore) + accountProviderDataSource.setUrl("https://example.com") + // Simulate the login flow being torn down (e.g. across an OAuth round-trip), which reverts the + // exposed default; the user's selection must still be the one saved to history. + accountProviderDataSource.reset() + val sut = SaveAccountProviderToHistory(accountProviderDataSource, appPreferencesStore) + + sut() + + assertThat(appPreferencesStore.getHomeserverHistoryFlow().first()) + .containsExactly("https://example.com") + } +} diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenterTest.kt index 5d9040adac..ad997111e2 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenterTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/changeserver/ChangeServerPresenterTest.kt @@ -14,12 +14,10 @@ import io.element.android.features.enterprise.test.FakeEnterpriseService import io.element.android.features.login.impl.accesscontrol.DefaultAccountProviderAccessControl import io.element.android.features.login.impl.accountprovider.AccountProvider import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.accountprovider.anAccountProviderDataSource import io.element.android.features.login.impl.error.ChangeServerError import io.element.android.features.login.impl.localnetwork.LocalNetworkPermissionGate -import io.element.android.features.wellknown.test.FakeWellknownRetriever -import io.element.android.features.wellknown.test.anElementWellKnown import io.element.android.libraries.architecture.AsyncData -import io.element.android.libraries.core.uri.ensureProtocol import io.element.android.libraries.matrix.test.AN_EXCEPTION import io.element.android.libraries.matrix.test.A_HOMESERVER_URL import io.element.android.libraries.matrix.test.auth.FakeMatrixAuthenticationService @@ -28,9 +26,6 @@ import io.element.android.libraries.permissions.api.localnetwork.LocalNetworkPer import io.element.android.libraries.permissions.test.FakeLocalNetworkPermissionAdvisor import io.element.android.libraries.permissions.test.FakePermissionsPresenter import io.element.android.libraries.permissions.test.FakePermissionsPresenterFactory -import io.element.android.libraries.wellknown.api.ElementWellKnown -import io.element.android.libraries.wellknown.api.WellknownRetriever -import io.element.android.libraries.wellknown.api.WellknownRetrieverResult import io.element.android.tests.testutils.WarmUpRule import io.element.android.tests.testutils.lambda.lambdaRecorder import io.element.android.tests.testutils.lambda.value @@ -63,6 +58,7 @@ class ChangeServerPresenterTest { authenticationService = authenticationService, enterpriseService = FakeEnterpriseService( isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false }, ), ).test { val initialState = awaitItem() @@ -71,7 +67,7 @@ class ChangeServerPresenterTest { val loadingState = awaitItem() assertThat(loadingState.changeServerAction).isInstanceOf(AsyncData.Loading::class.java) val successState = awaitItem() - assertThat(successState.changeServerAction).isEqualTo(AsyncData.Success(Unit)) + assertThat(successState.changeServerAction).isEqualTo(AsyncData.Success(aMatrixHomeServerDetails(supportsOAuthLogin = true))) } } @@ -85,6 +81,7 @@ class ChangeServerPresenterTest { createPresenter( enterpriseService = FakeEnterpriseService( isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false }, ), authenticationService = authenticationService, ).test { @@ -112,6 +109,7 @@ class ChangeServerPresenterTest { createPresenter( enterpriseService = FakeEnterpriseService( isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false }, ), authenticationService = authenticationService, ).test { @@ -135,6 +133,7 @@ class ChangeServerPresenterTest { enterpriseService = FakeEnterpriseService( isAllowedToConnectToHomeserverResult = isAllowedToConnectToHomeserverResult, defaultHomeserverListResult = { listOf("element.io") }, + isElementProEnforcedResult = { false }, ), ).test { val initialState = awaitItem() @@ -158,24 +157,19 @@ class ChangeServerPresenterTest { @Test fun `present - change server element pro required error`() = runTest { - val getElementWellKnownResult = lambdaRecorder> { - WellknownRetrieverResult.Success( - anElementWellKnown( - enforceElementPro = true, - ) - ) - } + val isEnterpriseBuildLambda = lambdaRecorder { false } createPresenter( - wellknownRetriever = FakeWellknownRetriever( - getElementWellKnownResult = getElementWellKnownResult, - ), + isEnterpriseBuild = isEnterpriseBuildLambda, + enterpriseService = FakeEnterpriseService( + isElementProEnforcedResult = { true }, + ) ).test { val initialState = awaitItem() assertThat(initialState.changeServerAction).isEqualTo(AsyncData.Uninitialized) val anAccountProvider = AccountProvider(url = A_HOMESERVER_URL) initialState.eventSink.invoke(ChangeServerEvents.ChangeServer(anAccountProvider)) - val loadingState = awaitItem() - assertThat(loadingState.changeServerAction).isInstanceOf(AsyncData.Loading::class.java) + // Skip loading state + skipItems(1) val failureState = awaitItem() assertThat( (failureState.changeServerAction.errorOrNull() as ChangeServerError.NeedElementPro).unauthorisedAccountProviderTitle @@ -183,9 +177,7 @@ class ChangeServerPresenterTest { assertThat( (failureState.changeServerAction.errorOrNull() as ChangeServerError.NeedElementPro).applicationId ).isEqualTo("io.element.enterprise") - getElementWellKnownResult.assertions() - .isCalledOnce() - .with(value(A_HOMESERVER_URL.ensureProtocol())) + isEnterpriseBuildLambda.assertions().isCalledOnce() } } @@ -239,7 +231,7 @@ class ChangeServerPresenterTest { val permissionsPresenter = FakePermissionsPresenter() createPresenter( authenticationService = authenticationService, - enterpriseService = FakeEnterpriseService(isAllowedToConnectToHomeserverResult = { true }), + enterpriseService = FakeEnterpriseService(isAllowedToConnectToHomeserverResult = { true }, isElementProEnforcedResult = { false }), localNetworkPermissionAdvisor = FakeLocalNetworkPermissionAdvisor(shouldPrompt = true), permissionsPresenter = permissionsPresenter, ).test { @@ -253,23 +245,23 @@ class ChangeServerPresenterTest { while (finalState.changeServerAction !is AsyncData.Success) { finalState = awaitItem() } - assertThat(finalState.changeServerAction).isEqualTo(AsyncData.Success(Unit)) + assertThat(finalState.changeServerAction).isEqualTo(AsyncData.Success(aMatrixHomeServerDetails(supportsOAuthLogin = true))) } } private fun createPresenter( authenticationService: FakeMatrixAuthenticationService = FakeMatrixAuthenticationService(), - accountProviderDataSource: AccountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()), + accountProviderDataSource: AccountProviderDataSource = anAccountProviderDataSource(), enterpriseService: EnterpriseService = FakeEnterpriseService(), - wellknownRetriever: WellknownRetriever = FakeWellknownRetriever(), localNetworkPermissionAdvisor: FakeLocalNetworkPermissionAdvisor = FakeLocalNetworkPermissionAdvisor(), permissionsPresenter: FakePermissionsPresenter = FakePermissionsPresenter(), + isEnterpriseBuild: () -> Boolean = { false }, ) = ChangeServerPresenter( authenticationService = authenticationService, accountProviderDataSource = accountProviderDataSource, defaultAccountProviderAccessControl = DefaultAccountProviderAccessControl( enterpriseService = enterpriseService, - wellknownRetriever = wellknownRetriever, + isEnterpriseBuild = isEnterpriseBuild, ), localNetworkPermissionGate = LocalNetworkPermissionGate( advisor = localNetworkPermissionAdvisor, diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderPresenterTest.kt deleted file mode 100644 index 7d81f05c0c..0000000000 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/changeaccountprovider/ChangeAccountProviderPresenterTest.kt +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.changeaccountprovider - -import com.google.common.truth.Truth.assertThat -import io.element.android.features.enterprise.api.EnterpriseService -import io.element.android.features.enterprise.test.FakeEnterpriseService -import io.element.android.features.login.impl.accountprovider.AccountProvider -import io.element.android.features.login.impl.changeserver.aChangeServerState -import io.element.android.libraries.matrix.test.AN_ACCOUNT_PROVIDER -import io.element.android.libraries.matrix.test.AN_ACCOUNT_PROVIDER_2 -import io.element.android.tests.testutils.WarmUpRule -import io.element.android.tests.testutils.test -import kotlinx.coroutines.test.runTest -import org.junit.Rule -import org.junit.Test - -class ChangeAccountProviderPresenterTest { - @get:Rule - val warmUpRule = WarmUpRule() - - @Test - fun `present - initial state`() = runTest { - val presenter = ChangeAccountProviderPresenter( - changeServerPresenter = { aChangeServerState() }, - enterpriseService = FakeEnterpriseService( - defaultHomeserverListResult = { emptyList() } - ), - ) - presenter.test { - val initialState = awaitItem() - assertThat(initialState.accountProviders).isEqualTo( - listOf( - AccountProvider( - url = "https://matrix.org", - title = "matrix.org", - subtitle = null, - isPublic = true, - isMatrixOrg = true, - ) - ) - ) - assertThat(initialState.canSearchForAccountProviders).isTrue() - } - } - - @Test - fun `present - fixed list of account providers`() = runTest { - val presenter = ChangeAccountProviderPresenter( - changeServerPresenter = { aChangeServerState() }, - enterpriseService = FakeEnterpriseService( - defaultHomeserverListResult = { - listOf(AN_ACCOUNT_PROVIDER, AN_ACCOUNT_PROVIDER_2) - } - ), - ) - presenter.test { - val initialState = awaitItem() - assertThat(initialState.accountProviders).isEqualTo( - listOf( - AccountProvider( - url = "https://matrix.org", - title = "matrix.org", - subtitle = null, - isPublic = true, - isMatrixOrg = true, - ), - AccountProvider( - url = "https://element.io", - title = "element.io", - subtitle = null, - isPublic = false, - isMatrixOrg = false, - ) - ) - ) - assertThat(initialState.canSearchForAccountProviders).isFalse() - } - } - - @Test - fun `present - opened list of account providers`() = runTest { - val presenter = ChangeAccountProviderPresenter( - changeServerPresenter = { aChangeServerState() }, - enterpriseService = FakeEnterpriseService( - defaultHomeserverListResult = { - listOf(AN_ACCOUNT_PROVIDER, EnterpriseService.ANY_ACCOUNT_PROVIDER) - } - ), - ) - presenter.test { - val initialState = awaitItem() - assertThat(initialState.accountProviders).isEqualTo( - listOf( - AccountProvider( - url = "https://matrix.org", - title = "matrix.org", - subtitle = null, - isPublic = true, - isMatrixOrg = true, - ) - ) - ) - assertThat(initialState.canSearchForAccountProviders).isTrue() - } - } -} diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderViewTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderViewTest.kt index f1ce703d1c..cd64638563 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderViewTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/chooseaccountprovider/ChooseAccountProviderViewTest.kt @@ -84,7 +84,6 @@ class ChooseAccountProviderViewTest : RobolectricTest() { onOAuthDetails: (OAuthDetails) -> Unit = EnsureNeverCalledWithParam(), onNeedLoginPassword: () -> Unit = EnsureNeverCalled(), onLearnMoreClick: () -> Unit = EnsureNeverCalled(), - onCreateAccountContinue: (url: String) -> Unit = EnsureNeverCalledWithParam(), ) { setContent { ChooseAccountProviderView( @@ -93,7 +92,6 @@ class ChooseAccountProviderViewTest : RobolectricTest() { onOAuthDetails = onOAuthDetails, onNeedLoginPassword = onNeedLoginPassword, onLearnMoreClick = onLearnMoreClick, - onCreateAccountContinue = onCreateAccountContinue, ) } } diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicPresenterTest.kt index 8d56386fa4..d4a1a74d99 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicPresenterTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/classic/loginwithclassic/LoginWithClassicPresenterTest.kt @@ -8,8 +8,8 @@ package io.element.android.features.login.impl.screens.classic.loginwithclassic import com.google.common.truth.Truth.assertThat -import io.element.android.features.enterprise.test.FakeEnterpriseService import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.accountprovider.anAccountProviderDataSource import io.element.android.features.login.impl.classic.ElementClassicConnection import io.element.android.features.login.impl.classic.ElementClassicConnectionState import io.element.android.features.login.impl.classic.FakeElementClassicConnection @@ -249,7 +249,7 @@ private fun createPresenter( navigator: LoginWithClassicNavigator = FakeLoginWithClassicNavigator(), loginModePresenter: LoginModePresenter = createLoginModePresenter(), elementClassicConnection: ElementClassicConnection = FakeElementClassicConnection(), - accountProviderDataSource: AccountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()), + accountProviderDataSource: AccountProviderDataSource = anAccountProviderDataSource(), isEnterpriseBuild: Boolean = false, ) = LoginWithClassicPresenter( userId = userId, diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenterTest.kt index c20896870b..641eea1563 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenterTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/confirmaccountprovider/ConfirmAccountProviderPresenterTest.kt @@ -8,15 +8,19 @@ package io.element.android.features.login.impl.screens.confirmaccountprovider +import app.cash.turbine.ReceiveTurbine import com.google.common.truth.Truth.assertThat import io.element.android.appconfig.AuthenticationConfig +import io.element.android.features.enterprise.api.EnterpriseService import io.element.android.features.enterprise.test.FakeEnterpriseService +import io.element.android.features.login.impl.accesscontrol.DefaultAccountProviderAccessControl import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.accountprovider.anAccountProviderDataSource +import io.element.android.features.login.impl.changeserver.ChangeServerPresenter +import io.element.android.features.login.impl.localnetwork.LocalNetworkPermissionGate import io.element.android.features.login.impl.login.LoginMode import io.element.android.features.login.impl.screens.createaccount.AccountCreationNotSupported import io.element.android.features.login.impl.screens.onboarding.createLoginModePresenter -import io.element.android.features.login.impl.web.FakeWebClientUrlForAuthenticationRetriever -import io.element.android.features.login.impl.web.WebClientUrlForAuthenticationRetriever import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.auth.MatrixAuthenticationService import io.element.android.libraries.matrix.test.AN_EXCEPTION @@ -24,7 +28,12 @@ import io.element.android.libraries.matrix.test.auth.FakeMatrixAuthenticationSer import io.element.android.libraries.matrix.test.auth.aMatrixHomeServerDetails import io.element.android.libraries.oauth.api.OAuthAction import io.element.android.libraries.oauth.api.OAuthActionFlow -import io.element.android.libraries.oauth.test.customtab.FakeOAuthActionFlow +import io.element.android.libraries.oauth.test.FakeOAuthActionFlow +import io.element.android.libraries.permissions.test.FakeLocalNetworkPermissionAdvisor +import io.element.android.libraries.permissions.test.FakePermissionsPresenter +import io.element.android.libraries.permissions.test.FakePermissionsPresenterFactory +import io.element.android.libraries.preferences.api.store.AppPreferencesStore +import io.element.android.libraries.preferences.test.InMemoryAppPreferencesStore import io.element.android.tests.testutils.WarmUpRule import io.element.android.tests.testutils.test import kotlinx.coroutines.test.runTest @@ -42,7 +51,7 @@ class ConfirmAccountProviderPresenterTest { val initialState = awaitItem() assertThat(initialState.isAccountCreation).isFalse() assertThat(initialState.submitEnabled).isTrue() - assertThat(initialState.accountProvider.url).isEqualTo(AuthenticationConfig.MATRIX_ORG_URL) + assertThat(initialState.accountProviderInput).isEqualTo("matrix.org") assertThat(initialState.loginModeState.loginMode).isEqualTo(AsyncData.Uninitialized) } } @@ -59,14 +68,10 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - val loadingState = awaitItem() - assertThat(loadingState.submitEnabled).isTrue() - assertThat(loadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) - val successState = awaitItem() - assertThat(successState.submitEnabled).isFalse() - assertThat(successState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + val successState = awaitLoginMode { it is AsyncData.Success } assertThat(successState.loginModeState.loginMode.dataOrNull()).isEqualTo(LoginMode.PasswordLogin) + cancelAndIgnoreRemainingEvents() } } @@ -82,14 +87,10 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - val loadingState = awaitItem() - assertThat(loadingState.submitEnabled).isTrue() - assertThat(loadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) - val successState = awaitItem() - assertThat(successState.submitEnabled).isFalse() - assertThat(successState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + val successState = awaitLoginMode { it is AsyncData.Success } assertThat(successState.loginModeState.loginMode.dataOrNull()).isInstanceOf(LoginMode.OAuth::class.java) + cancelAndIgnoreRemainingEvents() } } @@ -107,18 +108,14 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - val loadingState = awaitItem() - assertThat(loadingState.submitEnabled).isTrue() - assertThat(loadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) - val successState = awaitItem() - assertThat(successState.submitEnabled).isFalse() - assertThat(successState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + val successState = awaitLoginMode { it is AsyncData.Success } assertThat(successState.loginModeState.loginMode.dataOrNull()).isInstanceOf(LoginMode.OAuth::class.java) authenticationService.givenOAuthCancelError(AN_EXCEPTION) defaultOAuthActionFlow.post(OAuthAction.GoBack()) - val cancelFailureState = awaitItem() + val cancelFailureState = awaitLoginMode { it is AsyncData.Failure } assertThat(cancelFailureState.loginModeState.loginMode).isInstanceOf(AsyncData.Failure::class.java) + cancelAndIgnoreRemainingEvents() } } @@ -136,17 +133,13 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - val loadingState = awaitItem() - assertThat(loadingState.submitEnabled).isTrue() - assertThat(loadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) - val successState = awaitItem() - assertThat(successState.submitEnabled).isFalse() - assertThat(successState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + val successState = awaitLoginMode { it is AsyncData.Success } assertThat(successState.loginModeState.loginMode.dataOrNull()).isInstanceOf(LoginMode.OAuth::class.java) defaultOAuthActionFlow.post(OAuthAction.GoBack()) - val cancelFinalState = awaitItem() + val cancelFinalState = awaitLoginMode { it is AsyncData.Uninitialized } assertThat(cancelFinalState.loginModeState.loginMode).isInstanceOf(AsyncData.Uninitialized::class.java) + cancelAndIgnoreRemainingEvents() } } @@ -164,13 +157,12 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - val loadingState = awaitItem() - assertThat(loadingState.submitEnabled).isTrue() - assertThat(loadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + awaitLoginMode { it is AsyncData.Loading } defaultOAuthActionFlow.post(OAuthAction.GoBack(toUnblock = true)) - val cancelFinalState = awaitItem() + val cancelFinalState = awaitLoginMode { it is AsyncData.Uninitialized } assertThat(cancelFinalState.loginModeState.loginMode).isInstanceOf(AsyncData.Uninitialized::class.java) + cancelAndIgnoreRemainingEvents() } } @@ -188,20 +180,14 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - val loadingState = awaitItem() - assertThat(loadingState.submitEnabled).isTrue() - assertThat(loadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) - val successState = awaitItem() - assertThat(successState.submitEnabled).isFalse() - assertThat(successState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + val successState = awaitLoginMode { it is AsyncData.Success } assertThat(successState.loginModeState.loginMode.dataOrNull()).isInstanceOf(LoginMode.OAuth::class.java) authenticationService.givenLoginError(AN_EXCEPTION) defaultOAuthActionFlow.post(OAuthAction.Success("aUrl")) - val cancelLoadingState = awaitItem() - assertThat(cancelLoadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) - val cancelFailureState = awaitItem() + val cancelFailureState = awaitLoginMode { it is AsyncData.Failure } assertThat(cancelFailureState.loginModeState.loginMode).isInstanceOf(AsyncData.Failure::class.java) + cancelAndIgnoreRemainingEvents() } } @@ -219,17 +205,13 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - val loadingState = awaitItem() - assertThat(loadingState.submitEnabled).isTrue() - assertThat(loadingState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) - val successState = awaitItem() - assertThat(successState.submitEnabled).isFalse() - assertThat(successState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + val successState = awaitLoginMode { it is AsyncData.Success } assertThat(successState.loginModeState.loginMode.dataOrNull()).isInstanceOf(LoginMode.OAuth::class.java) defaultOidcActionFlow.post(OAuthAction.Success("aUrl")) - val successSuccessState = awaitItem() + val successSuccessState = awaitLoginMode { it is AsyncData.Loading } assertThat(successSuccessState.loginModeState.loginMode).isInstanceOf(AsyncData.Loading::class.java) + cancelAndIgnoreRemainingEvents() } } @@ -245,11 +227,11 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue) - skipItems(1) // Loading - val failureState = awaitItem() - assertThat(failureState.submitEnabled).isFalse() - assertThat(failureState.loginModeState.loginMode).isInstanceOf(AsyncData.Failure::class.java) + initialState.eventSink.invoke(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + // The account provider validation fails, so the login is never attempted. + val failureState = awaitState { it.changeServerState.changeServerAction is AsyncData.Failure } + assertThat(failureState.loginModeState.loginMode).isEqualTo(AsyncData.Uninitialized) + cancelAndIgnoreRemainingEvents() } } @@ -266,47 +248,41 @@ class ConfirmAccountProviderPresenterTest { presenter.test { val initialState = awaitItem() - // Submit will return an error - initialState.eventSink(ConfirmAccountProviderEvents.Continue) - - skipItems(1) // Loading + // Submit will return an error while validating the account provider + initialState.eventSink(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) // Check an error was returned - val submittedState = awaitItem() - assertThat(submittedState.loginModeState.loginMode).isInstanceOf(AsyncData.Failure::class.java) + val submittedState = awaitState { it.changeServerState.changeServerAction is AsyncData.Failure } // Assert the error is then cleared submittedState.eventSink(ConfirmAccountProviderEvents.ClearError) - val clearedState = awaitItem() + val clearedState = awaitState { it.changeServerState.changeServerAction is AsyncData.Uninitialized } assertThat(clearedState.loginModeState.loginMode).isEqualTo(AsyncData.Uninitialized) } } @Test - fun `present - confirm account creation without oidc and without url generates an error`() = runTest { + fun `present - confirm account creation without oidc generates an error`() = runTest { val authenticationService = FakeMatrixAuthenticationService( setHomeserverResult = { - Result.success(aMatrixHomeServerDetails()) + Result.success(aMatrixHomeServerDetails(supportsPasswordLogin = true)) }, ) val presenter = createConfirmAccountProviderPresenter( params = ConfirmAccountProviderPresenter.Params(isAccountCreation = true), matrixAuthenticationService = authenticationService, - webClientUrlForAuthenticationRetriever = FakeWebClientUrlForAuthenticationRetriever { - throw AccountCreationNotSupported() - }, ) presenter.test { val initialState = awaitItem() - initialState.eventSink(ConfirmAccountProviderEvents.Continue) - skipItems(1) // Loading + initialState.eventSink(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) // Check an error was returned - val submittedState = awaitItem() + val submittedState = awaitLoginMode { it is AsyncData.Failure } assertThat(submittedState.loginModeState.loginMode.errorOrNull()).isInstanceOf(AccountCreationNotSupported::class.java) // Assert the error is then cleared submittedState.eventSink(ConfirmAccountProviderEvents.ClearError) - val clearedState = awaitItem() + val clearedState = awaitLoginMode { it is AsyncData.Uninitialized } assertThat(clearedState.loginModeState.loginMode).isEqualTo(AsyncData.Uninitialized) + cancelAndIgnoreRemainingEvents() } } @@ -323,72 +299,286 @@ class ConfirmAccountProviderPresenterTest { ) presenter.test { val initialState = awaitItem() - initialState.eventSink(ConfirmAccountProviderEvents.Continue) - skipItems(1) // Loading - val submittedState = awaitItem() - assertThat(submittedState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) + initialState.eventSink(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + val submittedState = awaitLoginMode { it is AsyncData.Success } assertThat(submittedState.loginModeState.loginMode.dataOrNull()).isInstanceOf(LoginMode.OAuth::class.java) + cancelAndIgnoreRemainingEvents() } } @Test - fun `present - confirm account creation with OAuth and url continues with OAuth`() = runTest { - val aUrl = "aUrl" + fun `present - offers an autocomplete suggestion from the account provider history`() = runTest { + val presenter = createConfirmAccountProviderPresenter( + appPreferencesStore = InMemoryAppPreferencesStore( + homeserverHistory = listOf("https://randomcommunity.org"), + ), + ) + presenter.test { + val initialState = awaitItem() + assertThat(initialState.accountProviderSuggestion).isNull() + initialState.eventSink(ConfirmAccountProviderEvents.UserInputChanged("random")) + val suggestionState = awaitState { it.accountProviderInput == "random" } + // Completion is offered without the https:// scheme, even though history stores the full URL. + assertThat(suggestionState.accountProviderSuggestion).isEqualTo("randomcommunity.org") + } + } + + @Test + fun `present - continue accepts the autocomplete suggestion rather than the typed prefix`() = runTest { + val submittedUrls = mutableListOf() val authenticationService = FakeMatrixAuthenticationService( - setHomeserverResult = { + setHomeserverResult = { url -> + submittedUrls.add(url) + Result.success(aMatrixHomeServerDetails(supportsPasswordLogin = true)) + }, + ) + val presenter = createConfirmAccountProviderPresenter( + matrixAuthenticationService = authenticationService, + appPreferencesStore = InMemoryAppPreferencesStore( + homeserverHistory = listOf("https://randomcommunity.org"), + ), + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.UserInputChanged("random")) + val suggestionState = awaitState { it.accountProviderSuggestion != null } + suggestionState.eventSink(ConfirmAccountProviderEvents.Continue("randomcommunity.org")) + awaitLoginMode { it is AsyncData.Success } + assertThat(submittedUrls.first()).isEqualTo("https://randomcommunity.org") + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - continue applies the completed account provider back into the field`() = runTest { + val authenticationService = FakeMatrixAuthenticationService( + setHomeserverResult = { Result.success(aMatrixHomeServerDetails(supportsPasswordLogin = true)) }, + ) + val presenter = createConfirmAccountProviderPresenter( + matrixAuthenticationService = authenticationService, + appPreferencesStore = InMemoryAppPreferencesStore(homeserverHistory = listOf("https://randomcommunity.org")), + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.UserInputChanged("random")) + val suggestionState = awaitState { it.accountProviderSuggestion != null } + suggestionState.eventSink(ConfirmAccountProviderEvents.Continue("randomcommunity.org")) + // The field now renders the full accepted server rather than the typed prefix. + val appliedState = awaitState { it.accountProviderInput == "randomcommunity.org" } + assertThat(appliedState.accountProviderInput).isEqualTo("randomcommunity.org") + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - offers the enterprise allow-list servers as autocomplete suggestions`() = runTest { + val presenter = createConfirmAccountProviderPresenter( + appPreferencesStore = InMemoryAppPreferencesStore(homeserverHistory = emptyList()), + enterpriseService = FakeEnterpriseService( + // Preferred servers plus the "*" (any) wildcard: the wildcard is filtered out, the rest complete. + defaultHomeserverListResult = { listOf("https://element.io", EnterpriseService.ANY_ACCOUNT_PROVIDER) }, + ), + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.UserInputChanged("ele")) + val suggestionState = awaitState { it.accountProviderInput == "ele" } + assertThat(suggestionState.accountProviderSuggestion).isEqualTo("element.io") + } + } + + @Test + fun `present - offers matrix_org without the scheme as an autocomplete suggestion`() = runTest { + val presenter = createConfirmAccountProviderPresenter( + appPreferencesStore = InMemoryAppPreferencesStore(homeserverHistory = emptyList()), + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.UserInputChanged("matr")) + val suggestionState = awaitState { it.accountProviderInput == "matr" } + assertThat(suggestionState.accountProviderSuggestion).isEqualTo("matrix.org") + } + } + + @Test + fun `present - does not autocomplete a scheme-prefixed input`() = runTest { + // Candidates are bare hosts, so a scheme-prefixed input never completes them - the user completes by + // typing the bare host. This also avoids ever suggesting an insecure http scheme. + val presenter = createConfirmAccountProviderPresenter( + appPreferencesStore = InMemoryAppPreferencesStore(homeserverHistory = emptyList()), + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.UserInputChanged("https://mat")) + assertThat(awaitState { it.accountProviderInput == "https://mat" }.accountProviderSuggestion).isNull() + initialState.eventSink(ConfirmAccountProviderEvents.UserInputChanged("http://mat")) + assertThat(awaitState { it.accountProviderInput == "http://mat" }.accountProviderSuggestion).isNull() + } + } + + @Test + fun `present - continue prepends https to a bare account provider`() = runTest { + val submittedUrls = mutableListOf() + val authenticationService = FakeMatrixAuthenticationService( + setHomeserverResult = { url -> + submittedUrls.add(url) Result.success(aMatrixHomeServerDetails(supportsOAuthLogin = true)) }, ) val presenter = createConfirmAccountProviderPresenter( - params = ConfirmAccountProviderPresenter.Params(isAccountCreation = true), matrixAuthenticationService = authenticationService, - webClientUrlForAuthenticationRetriever = FakeWebClientUrlForAuthenticationRetriever { aUrl }, ) presenter.test { val initialState = awaitItem() - initialState.eventSink(ConfirmAccountProviderEvents.Continue) - skipItems(1) // Loading - val submittedState = awaitItem() - assertThat(submittedState.loginModeState.loginMode).isInstanceOf(AsyncData.Success::class.java) - assertThat(submittedState.loginModeState.loginMode.dataOrNull()).isInstanceOf(LoginMode.OAuth::class.java) + initialState.eventSink(ConfirmAccountProviderEvents.Continue("matrix.org")) + awaitLoginMode { it is AsyncData.Success } + assertThat(submittedUrls.first()).isEqualTo(AuthenticationConfig.MATRIX_ORG_URL) + cancelAndIgnoreRemainingEvents() } } @Test - fun `present - confirm account creation without OAuth and with url continuing with url`() = runTest { - val aUrl = "aUrl" + fun `present - continue configures the homeserver only once`() = runTest { + // The consolidated Continue flow validates the account provider and then signs in. Login reuses the + // details resolved during validation, so setHomeserver runs exactly once rather than once per phase. + val submittedUrls = mutableListOf() val authenticationService = FakeMatrixAuthenticationService( - setHomeserverResult = { - Result.success(aMatrixHomeServerDetails()) + setHomeserverResult = { url -> + submittedUrls.add(url) + Result.success(aMatrixHomeServerDetails(supportsOAuthLogin = true)) }, ) + val presenter = createConfirmAccountProviderPresenter( + matrixAuthenticationService = authenticationService, + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.Continue(AuthenticationConfig.MATRIX_ORG_URL)) + awaitLoginMode { it is AsyncData.Success } + assertThat(submittedUrls).containsExactly(AuthenticationConfig.MATRIX_ORG_URL) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - continue with a full matrix id signs in to its homeserver and passes a login hint`() = runTest { + val submittedUrls = mutableListOf() + val authenticationService = FakeMatrixAuthenticationService( + setHomeserverResult = { url -> + submittedUrls.add(url) + Result.success(aMatrixHomeServerDetails(supportsOAuthLogin = true)) + }, + ) + val presenter = createConfirmAccountProviderPresenter(matrixAuthenticationService = authenticationService) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.Continue("@alice:example.org")) + awaitLoginMode { it is AsyncData.Success } + assertThat(submittedUrls.first()).isEqualTo("https://example.org") + assertThat(authenticationService.getOAuthUrlLoginHint).isEqualTo("mxid:@alice:example.org") + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - continue with a matrix id keeps the port in the homeserver`() = runTest { + val submittedUrls = mutableListOf() + val authenticationService = FakeMatrixAuthenticationService( + setHomeserverResult = { url -> + submittedUrls.add(url) + Result.success(aMatrixHomeServerDetails(supportsOAuthLogin = true)) + }, + ) + val presenter = createConfirmAccountProviderPresenter(matrixAuthenticationService = authenticationService) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.Continue("@alice:example.org:8448")) + awaitLoginMode { it is AsyncData.Success } + assertThat(submittedUrls.first()).isEqualTo("https://example.org:8448") + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - continue with a plain account provider passes no login hint`() = runTest { + val authenticationService = FakeMatrixAuthenticationService( + setHomeserverResult = { Result.success(aMatrixHomeServerDetails(supportsOAuthLogin = true)) }, + ) + val presenter = createConfirmAccountProviderPresenter(matrixAuthenticationService = authenticationService) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(ConfirmAccountProviderEvents.Continue("matrix.org")) + awaitLoginMode { it is AsyncData.Success } + assertThat(authenticationService.getOAuthUrlLoginHint).isNull() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - continue with a matrix id during account creation passes no login hint`() = runTest { + val authenticationService = FakeMatrixAuthenticationService( + setHomeserverResult = { Result.success(aMatrixHomeServerDetails(supportsOAuthLogin = true)) }, + ) val presenter = createConfirmAccountProviderPresenter( params = ConfirmAccountProviderPresenter.Params(isAccountCreation = true), matrixAuthenticationService = authenticationService, - webClientUrlForAuthenticationRetriever = FakeWebClientUrlForAuthenticationRetriever { aUrl }, ) presenter.test { val initialState = awaitItem() - initialState.eventSink(ConfirmAccountProviderEvents.Continue) - skipItems(1) // Loading - val submittedState = awaitItem() - assertThat(submittedState.loginModeState.loginMode.dataOrNull()).isEqualTo(LoginMode.AccountCreation(aUrl)) + initialState.eventSink(ConfirmAccountProviderEvents.Continue("@alice:example.org")) + awaitLoginMode { it is AsyncData.Success } + assertThat(authenticationService.getOAuthUrlLoginHint).isNull() + cancelAndIgnoreRemainingEvents() + } + } + + /** + * Awaits until the emitted state's login mode matches [predicate], skipping the intermediate + * account-provider validation states, and returns that state. + */ + private suspend fun ReceiveTurbine.awaitLoginMode( + predicate: (AsyncData) -> Boolean, + ): ConfirmAccountProviderState = awaitState { predicate(it.loginModeState.loginMode) } + + private suspend fun ReceiveTurbine.awaitState( + predicate: (ConfirmAccountProviderState) -> Boolean, + ): ConfirmAccountProviderState { + while (true) { + val item = awaitItem() + if (predicate(item)) return item } } private fun createConfirmAccountProviderPresenter( params: ConfirmAccountProviderPresenter.Params = ConfirmAccountProviderPresenter.Params(isAccountCreation = false), - accountProviderDataSource: AccountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()), + accountProviderDataSource: AccountProviderDataSource = anAccountProviderDataSource(), matrixAuthenticationService: MatrixAuthenticationService = FakeMatrixAuthenticationService(), defaultOAuthActionFlow: OAuthActionFlow = FakeOAuthActionFlow(), - webClientUrlForAuthenticationRetriever: WebClientUrlForAuthenticationRetriever = FakeWebClientUrlForAuthenticationRetriever(), + appPreferencesStore: AppPreferencesStore = InMemoryAppPreferencesStore(), + enterpriseService: EnterpriseService = FakeEnterpriseService(), ) = ConfirmAccountProviderPresenter( params = params, accountProviderDataSource = accountProviderDataSource, + appPreferencesStore = appPreferencesStore, + enterpriseService = enterpriseService, loginModePresenter = createLoginModePresenter( authenticationService = matrixAuthenticationService, oAuthActionFlow = defaultOAuthActionFlow, - webClientUrlForAuthenticationRetriever = webClientUrlForAuthenticationRetriever, + ), + changeServerPresenter = ChangeServerPresenter( + authenticationService = matrixAuthenticationService, + accountProviderDataSource = accountProviderDataSource, + defaultAccountProviderAccessControl = DefaultAccountProviderAccessControl( + enterpriseService = FakeEnterpriseService( + isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false }, + ), + isEnterpriseBuild = { false }, + ), + localNetworkPermissionGate = LocalNetworkPermissionGate( + advisor = FakeLocalNetworkPermissionAdvisor(), + permissionsPresenterFactory = FakePermissionsPresenterFactory(FakePermissionsPresenter()), + ), ), ) } diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountPresenterTest.kt deleted file mode 100644 index c70a5c9a9a..0000000000 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/CreateAccountPresenterTest.kt +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import com.google.common.truth.Truth.assertThat -import io.element.android.libraries.architecture.AsyncAction -import io.element.android.libraries.core.meta.BuildMeta -import io.element.android.libraries.matrix.api.auth.MatrixAuthenticationService -import io.element.android.libraries.matrix.api.auth.external.ExternalSession -import io.element.android.libraries.matrix.api.verification.SessionVerifiedStatus -import io.element.android.libraries.matrix.test.AN_EXCEPTION -import io.element.android.libraries.matrix.test.A_SESSION_ID -import io.element.android.libraries.matrix.test.auth.FakeMatrixAuthenticationService -import io.element.android.libraries.matrix.test.core.aBuildMeta -import io.element.android.libraries.matrix.test.verification.FakeSessionVerificationService -import io.element.android.tests.testutils.WarmUpRule -import io.element.android.tests.testutils.lambda.lambdaRecorder -import io.element.android.tests.testutils.lambda.value -import io.element.android.tests.testutils.test -import kotlinx.coroutines.test.runTest -import org.junit.Rule -import org.junit.Test - -class CreateAccountPresenterTest { - @get:Rule - val warmUpRule = WarmUpRule() - - @Test - fun `present - initial state`() = runTest { - val presenter = createPresenter() - presenter.test { - val initialState = awaitItem() - assertThat(initialState.url).isEqualTo("aUrl") - assertThat(initialState.pageProgress).isEqualTo(0) - assertThat(initialState.createAction).isEqualTo(AsyncAction.Uninitialized) - assertThat(initialState.isDebugBuild).isTrue() - } - } - - @Test - fun `present - set up progress update the state`() = runTest { - val presenter = createPresenter() - presenter.test { - val initialState = awaitItem() - initialState.eventSink(CreateAccountEvents.SetPageProgress(33)) - assertThat(awaitItem().pageProgress).isEqualTo(33) - } - } - - @Test - fun `present - receiving a message not able to be parsed change the state to error`() = runTest { - val presenter = createPresenter( - messageParser = FakeMessageParser { error("An error") } - ) - presenter.test { - val initialState = awaitItem() - initialState.eventSink(CreateAccountEvents.OnMessageReceived("")) - assertThat(awaitItem().createAction).isInstanceOf(AsyncAction.Failure::class.java) - } - } - - @Test - fun `present - receiving a message containing isTrusted is ignored`() = runTest { - val presenter = createPresenter() - presenter.test { - val initialState = awaitItem() - initialState.eventSink(CreateAccountEvents.OnMessageReceived("isTrusted")) - } - } - - @Test - fun `present - receiving a message able to be parsed change the state to success`() = runTest { - val lambda = lambdaRecorder { _ -> anExternalSession() } - val sessionVerificationService = FakeSessionVerificationService() - val presenter = createPresenter( - authenticationService = FakeMatrixAuthenticationService( - importCreatedSessionLambda = { Result.success(A_SESSION_ID) } - ), - messageParser = FakeMessageParser(lambda), - ) - presenter.test { - val initialState = awaitItem() - initialState.eventSink(CreateAccountEvents.OnMessageReceived("aMessage")) - assertThat(awaitItem().createAction.isLoading()).isTrue() - sessionVerificationService.emitVerifiedStatus(SessionVerifiedStatus.Verified) - assertThat(awaitItem().createAction.dataOrNull()).isEqualTo(A_SESSION_ID) - } - lambda.assertions().isCalledOnce().with(value("aMessage")) - } - - @Test - fun `present - receiving a message able to be parsed but error in importing change the state to error`() = runTest { - val presenter = createPresenter( - authenticationService = FakeMatrixAuthenticationService( - importCreatedSessionLambda = { Result.failure(AN_EXCEPTION) } - ), - messageParser = FakeMessageParser { anExternalSession() } - ) - presenter.test { - val initialState = awaitItem() - initialState.eventSink(CreateAccountEvents.OnMessageReceived("")) - assertThat(awaitItem().createAction.isLoading()).isTrue() - assertThat(awaitItem().createAction.errorOrNull()).isNotNull() - } - } - - private fun createPresenter( - url: String = "aUrl", - authenticationService: MatrixAuthenticationService = FakeMatrixAuthenticationService(), - messageParser: MessageParser = FakeMessageParser(), - buildMeta: BuildMeta = aBuildMeta(), - ) = CreateAccountPresenter( - url = url, - authenticationService = authenticationService, - messageParser = messageParser, - buildMeta = buildMeta, - ) -} diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/DefaultMessageParserTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/DefaultMessageParserTest.kt deleted file mode 100644 index 680fda2838..0000000000 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/DefaultMessageParserTest.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import com.google.common.truth.Truth.assertThat -import io.element.android.appconfig.AuthenticationConfig -import io.element.android.features.enterprise.test.FakeEnterpriseService -import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource -import io.element.android.libraries.androidutils.json.DefaultJsonProvider -import io.element.android.libraries.matrix.api.auth.external.ExternalSession -import kotlinx.serialization.SerializationException -import org.junit.Assert.assertThrows -import org.junit.Test - -class DefaultMessageParserTest { - private val validMessage = """ - { - "user_id": "user_id", - "home_server": "home_server", - "access_token": "access_token", - "device_id": "device_id" - } - """.trimIndent() - - @Test - fun `DefaultMessageParser is able to parse correct message`() { - val sut = createDefaultMessageParser() - assertThat(sut.parse(validMessage)).isEqualTo( - anExternalSession( - homeserverUrl = "home_server", - ) - ) - } - - @Test - fun `DefaultMessageParser should throw Exception in case of error`() { - val sut = createDefaultMessageParser() - // kotlinx.serialization.json.internal.JsonDecodingException - assertThrows(SerializationException::class.java) { sut.parse("invalid json") } - // missing userId - assertThrows(IllegalStateException::class.java) { sut.parse(validMessage.replace(""""user_id": "user_id",""", "")) } - // missing accessToken - assertThrows(IllegalStateException::class.java) { sut.parse(validMessage.replace(""""access_token": "access_token",""", "")) } - // missing deviceId - assertThrows(IllegalStateException::class.java) { - sut.parse( - validMessage - .replace(""""access_token": "access_token",""", """"access_token": "access_token"""") - .replace(""""device_id": "device_id"""", "") - ) - } - } - - @Test - fun `DefaultMessageParser should be successful even is homeserver url is missing`() { - val sut = createDefaultMessageParser() - // missing homeServer - assertThat(sut.parse(validMessage.replace(""""home_server": "home_server",""", ""))).isEqualTo( - anExternalSession( - homeserverUrl = AuthenticationConfig.MATRIX_ORG_URL, - ) - ) - } - - private fun createDefaultMessageParser(): DefaultMessageParser { - return DefaultMessageParser( - accountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()), - json = DefaultJsonProvider(), - ) - } -} - -internal fun anExternalSession( - homeserverUrl: String = "home_server", -) = ExternalSession( - userId = "user_id", - homeserverUrl = homeserverUrl, - accessToken = "access_token", - deviceId = "device_id", - refreshToken = null, -) diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/FakeMessageParser.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/FakeMessageParser.kt deleted file mode 100644 index 62d6dd7dd4..0000000000 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/createaccount/FakeMessageParser.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.createaccount - -import io.element.android.libraries.matrix.api.auth.external.ExternalSession -import io.element.android.tests.testutils.lambda.lambdaError - -class FakeMessageParser( - private val parseResult: (String) -> ExternalSession = { lambdaError() } -) : MessageParser { - override fun parse(message: String): ExternalSession { - return parseResult(message) - } -} diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenterTest.kt index 31a835cb8c..4dd2859dee 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenterTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordPresenterTest.kt @@ -10,8 +10,9 @@ package io.element.android.features.login.impl.screens.loginpassword import com.google.common.truth.Truth.assertThat import io.element.android.appconfig.AuthenticationConfig -import io.element.android.features.enterprise.test.FakeEnterpriseService import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.accountprovider.SaveAccountProviderToHistory +import io.element.android.features.login.impl.accountprovider.anAccountProviderDataSource import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.matrix.test.AN_EXCEPTION @@ -21,8 +22,11 @@ import io.element.android.libraries.matrix.test.A_USER_NAME import io.element.android.libraries.matrix.test.A_USER_NAME_2 import io.element.android.libraries.matrix.test.auth.FakeMatrixAuthenticationService import io.element.android.libraries.matrix.test.auth.aMatrixHomeServerDetails +import io.element.android.libraries.preferences.api.store.AppPreferencesStore +import io.element.android.libraries.preferences.test.InMemoryAppPreferencesStore import io.element.android.tests.testutils.WarmUpRule import io.element.android.tests.testutils.test +import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.Test @@ -101,6 +105,32 @@ class LoginPasswordPresenterTest { } } + @Test + fun `present - successful login saves the account provider to history`() = runTest { + val authenticationService = FakeMatrixAuthenticationService( + setHomeserverResult = { + Result.success(aMatrixHomeServerDetails()) + }, + ) + val appPreferencesStore = InMemoryAppPreferencesStore() + createLoginPasswordPresenter( + authenticationService = authenticationService, + appPreferencesStore = appPreferencesStore, + ).test { + val initialState = awaitItem() + initialState.eventSink.invoke(LoginPasswordEvents.SetLogin(A_USER_NAME)) + initialState.eventSink.invoke(LoginPasswordEvents.SetPassword(A_PASSWORD)) + skipItems(1) + val loginAndPasswordState = awaitItem() + loginAndPasswordState.eventSink.invoke(LoginPasswordEvents.Submit) + skipItems(1) + val loggedInState = awaitItem() + assertThat(loggedInState.loginAction).isEqualTo(AsyncData.Success(A_SESSION_ID)) + assertThat(appPreferencesStore.getHomeserverHistoryFlow().first()) + .containsExactly(AuthenticationConfig.MATRIX_ORG_URL) + } + } + @Test fun `present - submit with error`() = runTest { val authenticationService = FakeMatrixAuthenticationService( @@ -157,10 +187,12 @@ class LoginPasswordPresenterTest { private fun createLoginPasswordPresenter( initialLogin: String = "", authenticationService: FakeMatrixAuthenticationService = FakeMatrixAuthenticationService(), - accountProviderDataSource: AccountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()), + accountProviderDataSource: AccountProviderDataSource = anAccountProviderDataSource(), + appPreferencesStore: AppPreferencesStore = InMemoryAppPreferencesStore(), ): LoginPasswordPresenter = LoginPasswordPresenter( initialLogin = initialLogin, authenticationService = authenticationService, accountProviderDataSource = accountProviderDataSource, + saveAccountProviderToHistory = SaveAccountProviderToHistory(accountProviderDataSource, appPreferencesStore), ) } diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordViewTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordViewTest.kt index 3a128f2e4f..d76c94d5ea 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordViewTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/loginpassword/LoginPasswordViewTest.kt @@ -81,6 +81,21 @@ class LoginPasswordViewTest : RobolectricTest() { ) } + @Test + fun `changing login removes carriage returns the expected event`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder() + setLoginPasswordView( + aLoginPasswordState( + eventSink = eventsRecorder, + ), + ) + val userNameHint = activity!!.getString(CommonStrings.common_username) + onNodeWithText(userNameHint).performTextInput("a\r\nb") + eventsRecorder.assertSingle( + LoginPasswordEvents.SetLogin("ab") + ) + } + @Test fun `clearing login invokes the expected event`() = runAndroidComposeUiTest { val eventsRecorder = EventsRecorder() @@ -112,6 +127,21 @@ class LoginPasswordViewTest : RobolectricTest() { ) } + @Test + fun `changing password removes carriage returns the expected event`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder() + setLoginPasswordView( + aLoginPasswordState( + eventSink = eventsRecorder, + ), + ) + val passwordHint = activity!!.getString(CommonStrings.common_password) + onNodeWithText(passwordHint).performTextInput("a\r\nb") + eventsRecorder.assertSingle( + LoginPasswordEvents.SetPassword("ab") + ) + } + @Test fun `reveal password makes the password visible`() = runAndroidComposeUiTest { val eventsRecorder = EventsRecorder(expectEvents = false) diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenterTest.kt index 79268aa1e4..3c2e4b574f 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenterTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnBoardingPresenterTest.kt @@ -12,14 +12,14 @@ import com.google.common.truth.Truth.assertThat import io.element.android.appconfig.AuthenticationConfig import io.element.android.appconfig.OnBoardingConfig import io.element.android.features.enterprise.api.EnterpriseService +import io.element.android.features.enterprise.api.IsEnterpriseBuild import io.element.android.features.enterprise.test.FakeEnterpriseService import io.element.android.features.login.impl.accesscontrol.DefaultAccountProviderAccessControl import io.element.android.features.login.impl.accountprovider.AccountProviderDataSource +import io.element.android.features.login.impl.accountprovider.SaveAccountProviderToHistory +import io.element.android.features.login.impl.accountprovider.anAccountProviderDataSource import io.element.android.features.login.impl.localnetwork.LocalNetworkPermissionGate import io.element.android.features.login.impl.login.LoginModePresenter -import io.element.android.features.login.impl.web.FakeWebClientUrlForAuthenticationRetriever -import io.element.android.features.login.impl.web.WebClientUrlForAuthenticationRetriever -import io.element.android.features.wellknown.test.FakeWellknownRetriever import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.matrix.api.auth.MatrixAuthenticationService @@ -33,12 +33,15 @@ import io.element.android.libraries.matrix.test.A_LOGIN_HINT import io.element.android.libraries.matrix.test.auth.FakeMatrixAuthenticationService import io.element.android.libraries.matrix.test.core.aBuildMeta import io.element.android.libraries.oauth.api.OAuthActionFlow -import io.element.android.libraries.oauth.test.customtab.FakeOAuthActionFlow +import io.element.android.libraries.oauth.test.FakeOAuthActionFlow +import io.element.android.libraries.permissions.api.PermissionsPresenter import io.element.android.libraries.permissions.api.localnetwork.LocalNetworkPermissionAdvisor +import io.element.android.libraries.permissions.test.FakeLocalNetworkPermissionAdvisor +import io.element.android.libraries.permissions.test.FakePermissionsPresenterFactory +import io.element.android.libraries.preferences.test.InMemoryAppPreferencesStore import io.element.android.libraries.sessionstorage.api.SessionStore import io.element.android.libraries.sessionstorage.test.InMemorySessionStore import io.element.android.libraries.sessionstorage.test.aSessionData -import io.element.android.libraries.wellknown.api.WellknownRetriever import io.element.android.tests.testutils.WarmUpRule import io.element.android.tests.testutils.test import kotlinx.coroutines.flow.Flow @@ -183,6 +186,7 @@ class OnBoardingPresenterTest { enterpriseService = FakeEnterpriseService( defaultHomeserverListResult = { listOf(ACCOUNT_PROVIDER_FROM_CONFIG, EnterpriseService.ANY_ACCOUNT_PROVIDER) }, isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false }, ), ) presenter.test { @@ -247,7 +251,7 @@ class OnBoardingPresenterTest { Result.failure(AN_EXCEPTION) }, ) - val accountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()) + val accountProviderDataSource = anAccountProviderDataSource() val presenter = createPresenter( params = OnBoardingNode.Params( accountProvider = A_HOMESERVER_URL, @@ -256,6 +260,7 @@ class OnBoardingPresenterTest { ), enterpriseService = FakeEnterpriseService( isAllowedToConnectToHomeserverResult = { true }, + isElementProEnforcedResult = { false }, ), loginModePresenter = createLoginModePresenter( authenticationService = authenticationService, @@ -292,19 +297,19 @@ private fun createPresenter( ), buildMeta: BuildMeta = aBuildMeta(), enterpriseService: EnterpriseService = FakeEnterpriseService(), - wellknownRetriever: WellknownRetriever = FakeWellknownRetriever(), + isEnterpriseBuild: IsEnterpriseBuild = { false }, rageshakeFeatureAvailability: () -> Flow = { flowOf(true) }, loginModePresenter: LoginModePresenter = createLoginModePresenter(), onBoardingLogoResIdProvider: OnBoardingLogoResIdProvider = OnBoardingLogoResIdProvider { null }, sessionStore: SessionStore = InMemorySessionStore(), - accountProviderDataSource: AccountProviderDataSource = AccountProviderDataSource(FakeEnterpriseService()), + accountProviderDataSource: AccountProviderDataSource = anAccountProviderDataSource(), ) = OnBoardingPresenter( params = params, buildMeta = buildMeta, enterpriseService = enterpriseService, defaultAccountProviderAccessControl = DefaultAccountProviderAccessControl( enterpriseService = enterpriseService, - wellknownRetriever = wellknownRetriever, + isEnterpriseBuild = isEnterpriseBuild, ), rageshakeFeatureAvailability = rageshakeFeatureAvailability, loginModePresenter = loginModePresenter, @@ -316,17 +321,18 @@ private fun createPresenter( fun createLoginModePresenter( oAuthActionFlow: OAuthActionFlow = FakeOAuthActionFlow(), authenticationService: MatrixAuthenticationService = FakeMatrixAuthenticationService(), - webClientUrlForAuthenticationRetriever: WebClientUrlForAuthenticationRetriever = FakeWebClientUrlForAuthenticationRetriever(), localNetworkPermissionAdvisor: LocalNetworkPermissionAdvisor = - io.element.android.libraries.permissions.test.FakeLocalNetworkPermissionAdvisor(), - permissionsPresenterFactory: io.element.android.libraries.permissions.api.PermissionsPresenter.Factory = - io.element.android.libraries.permissions.test.FakePermissionsPresenterFactory(), + FakeLocalNetworkPermissionAdvisor(), + permissionsPresenterFactory: PermissionsPresenter.Factory = + FakePermissionsPresenterFactory(), + saveAccountProviderToHistory: SaveAccountProviderToHistory = + SaveAccountProviderToHistory(anAccountProviderDataSource(), InMemoryAppPreferencesStore()), ): LoginModePresenter = LoginModePresenter( oAuthActionFlow = oAuthActionFlow, authenticationService = authenticationService, - webClientUrlForAuthenticationRetriever = webClientUrlForAuthenticationRetriever, localNetworkPermissionGate = LocalNetworkPermissionGate( advisor = localNetworkPermissionAdvisor, permissionsPresenterFactory = permissionsPresenterFactory, ), + saveAccountProviderToHistory = saveAccountProviderToHistory, ) diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnboardingViewTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnboardingViewTest.kt index 1bdcb9bda1..dfa4119711 100644 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnboardingViewTest.kt +++ b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/onboarding/OnboardingViewTest.kt @@ -234,22 +234,6 @@ class OnboardingViewTest : RobolectricTestParameter() { eventSink.assertSingle(OnBoardingEvents.ClearError) } - @Test - fun `when success AccountCreation - the expected callback is invoked and the event is received`() = runAndroidComposeUiTest { - val eventSink = EventsRecorder() - val oAuthDetails = OAuthDetails("aUrl") - ensureCalledOnceWithParam(oAuthDetails.url) { callback -> - setOnboardingView( - state = anOnBoardingState( - loginModeState = aLoginModeState(loginMode = AsyncData.Success(LoginMode.AccountCreation("aUrl"))), - eventSink = eventSink, - ), - onCreateAccountContinue = callback, - ) - } - eventSink.assertSingle(OnBoardingEvents.ClearError) - } - private fun AndroidComposeUiTest.setOnboardingView( state: OnBoardingState, onBackClick: () -> Unit = EnsureNeverCalled(), @@ -261,7 +245,6 @@ class OnboardingViewTest : RobolectricTestParameter() { onOAuthDetails: (OAuthDetails) -> Unit = EnsureNeverCalledWithParam(), onNeedLoginPassword: () -> Unit = EnsureNeverCalled(), onLearnMoreClick: () -> Unit = EnsureNeverCalled(), - onCreateAccountContinue: (url: String) -> Unit = EnsureNeverCalledWithParam(), ) { setContent { OnBoardingView( @@ -275,7 +258,6 @@ class OnboardingViewTest : RobolectricTestParameter() { onOAuthDetails = onOAuthDetails, onNeedLoginPassword = onNeedLoginPassword, onLearnMoreClick = onLearnMoreClick, - onCreateAccountContinue = onCreateAccountContinue, ) } } diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderPresenterTest.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderPresenterTest.kt deleted file mode 100644 index 29c5d4a86c..0000000000 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/screens/searchaccountprovider/SearchAccountProviderPresenterTest.kt +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2023-2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.screens.searchaccountprovider - -import com.google.common.truth.Truth.assertThat -import io.element.android.features.login.impl.changeserver.aChangeServerState -import io.element.android.features.login.impl.resolver.HomeserverResolver -import io.element.android.libraries.architecture.AsyncData -import io.element.android.libraries.matrix.test.auth.FakeHomeServerLoginCompatibilityChecker -import io.element.android.libraries.permissions.test.FakeLocalNetworkPermissionAdvisor -import io.element.android.tests.testutils.WarmUpRule -import io.element.android.tests.testutils.lambda.lambdaRecorder -import io.element.android.tests.testutils.lambda.value -import io.element.android.tests.testutils.test -import io.element.android.tests.testutils.testCoroutineDispatchers -import kotlinx.coroutines.test.runTest -import org.junit.Rule -import org.junit.Test - -class SearchAccountProviderPresenterTest { - @get:Rule - val warmUpRule = WarmUpRule() - - @Test - fun `present - initial state`() = runTest { - val fakeLoginCompatibilityChecker = FakeHomeServerLoginCompatibilityChecker(checkResult = { Result.success(true) }) - val presenter = SearchAccountProviderPresenter( - homeserverResolver = HomeserverResolver(testCoroutineDispatchers(), fakeLoginCompatibilityChecker, FakeLocalNetworkPermissionAdvisor()), - changeServerPresenter = { aChangeServerState() } - ) - presenter.test { - val initialState = awaitItem() - assertThat(initialState.userInput).isEmpty() - assertThat(initialState.userInputResult).isEqualTo(AsyncData.Uninitialized) - } - } - - @Test - fun `present - error while checking login compatibility`() = runTest { - val fakeLoginCompatibilityChecker = FakeHomeServerLoginCompatibilityChecker(checkResult = { Result.failure(IllegalStateException("Oops")) }) - val presenter = SearchAccountProviderPresenter( - homeserverResolver = HomeserverResolver(testCoroutineDispatchers(), fakeLoginCompatibilityChecker, FakeLocalNetworkPermissionAdvisor()), - changeServerPresenter = { aChangeServerState() } - ) - presenter.test { - val initialState = awaitItem() - initialState.eventSink.invoke(SearchAccountProviderEvents.UserInput("https://test.org")) - val withInputState = awaitItem() - assertThat(withInputState.userInput).isEqualTo("https://test.org") - assertThat(initialState.userInputResult).isEqualTo(AsyncData.Uninitialized) - assertThat(awaitItem().userInputResult).isInstanceOf(AsyncData.Loading::class.java) - assertThat(awaitItem().userInputResult).isEqualTo( - AsyncData.Success( - listOf( - aHomeserverData(homeserverUrl = "https://test.org") - ) - ) - ) - } - } - - @Test - fun `present - enter text no result`() = runTest { - val fakeWellknownRetriever = FakeHomeServerLoginCompatibilityChecker(checkResult = { Result.success(false) }) - val presenter = SearchAccountProviderPresenter( - homeserverResolver = HomeserverResolver(testCoroutineDispatchers(), fakeWellknownRetriever, FakeLocalNetworkPermissionAdvisor()), - changeServerPresenter = { aChangeServerState() } - ) - presenter.test { - val initialState = awaitItem() - initialState.eventSink.invoke(SearchAccountProviderEvents.UserInput("test")) - val withInputState = awaitItem() - assertThat(withInputState.userInput).isEqualTo("test") - assertThat(initialState.userInputResult).isEqualTo(AsyncData.Uninitialized) - assertThat(awaitItem().userInputResult).isInstanceOf(AsyncData.Loading::class.java) - assertThat(awaitItem().userInputResult).isEqualTo( - AsyncData.Success( - listOf( - aHomeserverData(homeserverUrl = "https://test"), - ) - ) - ) - } - } - - @Test - fun `present - enter text one result with wellknown`() = runTest { - val checkResult = lambdaRecorder> { - when (it) { - "https://test.org" -> Result.success(false) - "https://test.com" -> Result.success(false) - "https://test.io" -> Result.success(true) - "https://test" -> Result.success(false) - else -> error("should not happen") - } - } - val fakeLoginCompatibilityChecker = FakeHomeServerLoginCompatibilityChecker(checkResult = checkResult) - val presenter = SearchAccountProviderPresenter( - homeserverResolver = HomeserverResolver(testCoroutineDispatchers(), fakeLoginCompatibilityChecker, FakeLocalNetworkPermissionAdvisor()), - changeServerPresenter = { aChangeServerState() } - ) - presenter.test { - val initialState = awaitItem() - initialState.eventSink.invoke(SearchAccountProviderEvents.UserInput("test")) - val withInputState = awaitItem() - assertThat(withInputState.userInput).isEqualTo("test") - assertThat(initialState.userInputResult).isEqualTo(AsyncData.Uninitialized) - assertThat(awaitItem().userInputResult).isInstanceOf(AsyncData.Loading::class.java) - assertThat(awaitItem().userInputResult).isEqualTo( - AsyncData.Success( - listOf( - aHomeserverData(homeserverUrl = "https://test.io") - ) - ) - ) - checkResult.assertions().isCalledExactly(4) - .withSequence( - listOf(value("https://test.org")), - listOf(value("https://test.com")), - listOf(value("https://test.io")), - listOf(value("https://test")), - ) - } - } - - @Test - fun `present - enter text two results with wellknown`() = runTest { - val checkResult = lambdaRecorder> { - when (it) { - "https://test.org" -> Result.success(true) - "https://test.com" -> Result.success(false) - "https://test.io" -> Result.success(true) - "https://test" -> Result.success(false) - else -> error("should not happen") - } - } - val fakeLoginCompatibilityChecker = FakeHomeServerLoginCompatibilityChecker(checkResult = checkResult) - val presenter = SearchAccountProviderPresenter( - homeserverResolver = HomeserverResolver(testCoroutineDispatchers(), fakeLoginCompatibilityChecker, FakeLocalNetworkPermissionAdvisor()), - changeServerPresenter = { aChangeServerState() } - ) - presenter.test { - val initialState = awaitItem() - initialState.eventSink.invoke(SearchAccountProviderEvents.UserInput("test")) - val withInputState = awaitItem() - assertThat(withInputState.userInput).isEqualTo("test") - assertThat(initialState.userInputResult).isEqualTo(AsyncData.Uninitialized) - assertThat(awaitItem().userInputResult).isInstanceOf(AsyncData.Loading::class.java) - assertThat(awaitItem().userInputResult).isEqualTo( - AsyncData.Success( - listOf( - aHomeserverData(homeserverUrl = "https://test.org"), - ) - ) - ) - assertThat(awaitItem().userInputResult).isEqualTo( - AsyncData.Success( - listOf( - aHomeserverData(homeserverUrl = "https://test.org"), - aHomeserverData(homeserverUrl = "https://test.io"), - ) - ) - ) - checkResult.assertions().isCalledExactly(4) - .withSequence( - listOf(value("https://test.org")), - listOf(value("https://test.com")), - listOf(value("https://test.io")), - listOf(value("https://test")), - ) - } - } -} diff --git a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/web/FakeWebClientUrlForAuthenticationRetriever.kt b/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/web/FakeWebClientUrlForAuthenticationRetriever.kt deleted file mode 100644 index f52af0adf3..0000000000 --- a/features/login/impl/src/test/kotlin/io/element/android/features/login/impl/web/FakeWebClientUrlForAuthenticationRetriever.kt +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.features.login.impl.web - -import io.element.android.tests.testutils.lambda.lambdaError - -class FakeWebClientUrlForAuthenticationRetriever( - private val retrieveLambda: suspend (homeServerUrl: String) -> String = { lambdaError() } -) : WebClientUrlForAuthenticationRetriever { - override suspend fun retrieve(homeServerUrl: String): String { - return retrieveLambda(homeServerUrl) - } -} diff --git a/features/login/test/build.gradle.kts b/features/login/test/build.gradle.kts index 7073648dd2..4cbf0910db 100644 --- a/features/login/test/build.gradle.kts +++ b/features/login/test/build.gradle.kts @@ -15,6 +15,7 @@ android { } dependencies { + implementation(projects.libraries.architecture) implementation(projects.features.login.api) implementation(projects.tests.testutils) } diff --git a/features/login/test/src/main/kotlin/io/element/android/features/login/test/FakeLoginEntryPoint.kt b/features/login/test/src/main/kotlin/io/element/android/features/login/test/FakeLoginEntryPoint.kt new file mode 100644 index 0000000000..2c94144890 --- /dev/null +++ b/features/login/test/src/main/kotlin/io/element/android/features/login/test/FakeLoginEntryPoint.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.login.test + +import com.bumble.appyx.core.modality.BuildContext +import com.bumble.appyx.core.node.Node +import io.element.android.features.login.api.LoginEntryPoint +import io.element.android.tests.testutils.lambda.lambdaError + +class FakeLoginEntryPoint( + private val createNodeResult: (BuildContext, LoginEntryPoint.Params) -> Node = { _, _ -> lambdaError() }, +) : LoginEntryPoint { + override fun createNode( + parentNode: Node, + buildContext: BuildContext, + params: LoginEntryPoint.Params, + callback: LoginEntryPoint.Callback, + ): Node = createNodeResult(buildContext, params) +} diff --git a/features/login/test/src/main/kotlin/io/element/android/features/login/test/accesscontrol/FakeAccountProviderAccessControl.kt b/features/login/test/src/main/kotlin/io/element/android/features/login/test/accesscontrol/FakeAccountProviderAccessControl.kt new file mode 100644 index 0000000000..9ebd3be7fc --- /dev/null +++ b/features/login/test/src/main/kotlin/io/element/android/features/login/test/accesscontrol/FakeAccountProviderAccessControl.kt @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.login.test.accesscontrol + +import io.element.android.features.login.api.accesscontrol.AccountProviderAccessControl +import io.element.android.tests.testutils.lambda.lambdaError + +class FakeAccountProviderAccessControl( + private val isAllowedToConnectToAccountProviderResult: (String) -> Boolean = { lambdaError() }, +) : AccountProviderAccessControl { + override suspend fun isAllowedToConnectToAccountProvider(accountProviderUrl: String): Boolean { + return isAllowedToConnectToAccountProviderResult(accountProviderUrl) + } +} diff --git a/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutStateProvider.kt b/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutStatePreviewParam.kt similarity index 92% rename from features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutStateProvider.kt rename to features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutStatePreviewParam.kt index feaf21ef4a..c208978fd9 100644 --- a/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutStateProvider.kt +++ b/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.logout.api.direct import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class DirectLogoutStateProvider : PreviewParameterProvider { +open class DirectLogoutStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDirectLogoutState(), diff --git a/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutView.kt b/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutView.kt index 7841b85a5a..affd2be94d 100644 --- a/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutView.kt +++ b/features/logout/api/src/main/kotlin/io/element/android/features/logout/api/direct/DirectLogoutView.kt @@ -10,7 +10,17 @@ package io.element.android.features.logout.api.direct import androidx.compose.runtime.Composable +/** + * Renders the confirmation dialogs of logging out directly, in particular the warning shown when the user would lose their room keys. + * + * It draws nothing until the host screen sends a logout event. + */ fun interface DirectLogoutView { + /** + * Draws whichever dialog the current state calls for. + * + * @param state the state produced by the direct logout presenter. + */ @Composable fun Render(state: DirectLogoutState) } diff --git a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutStateProvider.kt b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutStatePreviewParam.kt similarity index 97% rename from features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutStateProvider.kt rename to features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutStatePreviewParam.kt index a3b59860b5..7bd55faa2c 100644 --- a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutStateProvider.kt +++ b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.matrix.api.encryption.BackupUploadState import io.element.android.libraries.matrix.api.encryption.RecoveryState import io.element.android.libraries.matrix.api.encryption.SteadyStateException -open class LogoutStateProvider : PreviewParameterProvider { +open class LogoutStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLogoutState(), diff --git a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutView.kt b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutView.kt index 9700e54f5c..befabe7421 100644 --- a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutView.kt +++ b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutView.kt @@ -186,7 +186,7 @@ private fun Content( @PreviewsDayNight @Composable internal fun LogoutViewPreview( - @PreviewParameter(LogoutStateProvider::class) state: LogoutState, + @PreviewParameter(LogoutStatePreviewParam::class) state: LogoutState, ) = ElementPreview { LogoutView( state, diff --git a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/di/LogoutModule.kt b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/di/LogoutBindingContainer.kt similarity index 95% rename from features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/di/LogoutModule.kt rename to features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/di/LogoutBindingContainer.kt index 9b38fde22e..879d0fc5cf 100644 --- a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/di/LogoutModule.kt +++ b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/di/LogoutBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.di.SessionScope @ContributesTo(SessionScope::class) @BindingContainer -interface LogoutModule { +interface LogoutBindingContainer { @Binds fun bindDirectLogoutPresenter(presenter: DirectLogoutPresenter): Presenter } diff --git a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/direct/DefaultDirectLogoutView.kt b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/direct/DefaultDirectLogoutView.kt index 7fb483a447..a8cad6ffba 100644 --- a/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/direct/DefaultDirectLogoutView.kt +++ b/features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/direct/DefaultDirectLogoutView.kt @@ -13,7 +13,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import dev.zacsweers.metro.ContributesBinding import io.element.android.features.logout.api.direct.DirectLogoutEvents import io.element.android.features.logout.api.direct.DirectLogoutState -import io.element.android.features.logout.api.direct.DirectLogoutStateProvider +import io.element.android.features.logout.api.direct.DirectLogoutStatePreviewParam import io.element.android.features.logout.api.direct.DirectLogoutView import io.element.android.features.logout.impl.ui.LogoutActionDialog import io.element.android.libraries.designsystem.preview.ElementPreview @@ -43,7 +43,7 @@ class DefaultDirectLogoutView : DirectLogoutView { @PreviewsDayNight @Composable internal fun DefaultDirectLogoutViewPreview( - @PreviewParameter(DirectLogoutStateProvider::class) state: DirectLogoutState, + @PreviewParameter(DirectLogoutStatePreviewParam::class) state: DirectLogoutState, ) = ElementPreview { DefaultDirectLogoutView().Render(state = state) } diff --git a/features/logout/impl/src/main/res/values-ar/translations.xml b/features/logout/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..6825a5c54d --- /dev/null +++ b/features/logout/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,18 @@ + + + "أمتأكد من إزالة هذا الجهاز؟" + "إزالة هذا الجهاز" + "إزالة هذا الجهاز" + "تجري إزالة الجهاز…" + "هذا هو جهازك الوحيد. إذا أزلته، فستحتاج إلى مفتاح استرداد لتأكيد هويتك الرقمية واستعادة محادثاتك المشفّرة في المرة التالية التي تسجّل فيها الدخول." + "أنت على وشك فقدان الوصول إلى محادثاتك المشفّرة" + "كان النسخ الاحتياطي لمفاتيحك لا يزال جاريًا عندما أصبحت غير متصل. أعد الاتصال حتى يمكن نسخ مفاتيحك احتياطيًا قبل إزالة هذا الجهاز." + "لا يزال النسخ الاحتياطي لمفاتيحك جاريًا" + "يُرجى الانتظار حتى تكتمل هذه العملية قبل إزالة هذا الجهاز." + "لا يزال النسخ الاحتياطي لمفاتيحك جاريًا" + "إزالة هذا الجهاز" + "هذا هو جهازك الوحيد. إذا أزلته، فستحتاج إلى مفتاح استرداد لتأكيد هويتك الرقمية واستعادة محادثاتك المشفّرة في المرة التالية التي تسجّل فيها الدخول." + "أنت على وشك فقدان الوصول إلى محادثاتك المشفّرة" + "هذا هو جهازك الوحيد. إذا أزلته، فستحتاج إلى مفتاح استرداد لتأكيد هويتك الرقمية واستعادة محادثاتك المشفّرة في المرة التالية التي تسجّل فيها الدخول." + "تأكد من أن لديك إمكانية الوصول إلى مفتاح الاسترداد الخاص بك قبل إزالة هذا الجهاز" + diff --git a/features/logout/impl/src/main/res/values-es/translations.xml b/features/logout/impl/src/main/res/values-es/translations.xml index 94d0ec56a8..6c451c0834 100644 --- a/features/logout/impl/src/main/res/values-es/translations.xml +++ b/features/logout/impl/src/main/res/values-es/translations.xml @@ -1,18 +1,18 @@ - "¿Estás seguro de que quieres cerrar sesión?" - "Cerrar sesión" - "Cerrar sesión" - "Cerrando sesión…" - "Estás a punto de cerrar tu última sesión. Si cierras sesión ahora, perderás el acceso a tus mensajes cifrados." - "Has desactivado la copia de seguridad" - "Se estaba haciendo una copia de seguridad de tus claves cuando te desconectaste. Vuelve a conectarte para que se haga una copia de seguridad de tus claves antes de desconectarte." + "¿Estás seguro de que quieres eliminar este dispositivo?" + "Eliminar este dispositivo" + "Eliminar este dispositivo" + "Eliminando dispositivo…" + "Este es tu único dispositivo. Si lo eliminas, necesitarás una clave de recuperación para poder confirmar tu identidad digital y restaurar tus chats cifrados la próxima vez que inicies sesión." + "Estás a punto de perder acceso a tus chats cifrados" + "Se estaba haciendo una copia de seguridad de tus claves cuando te desconectaste. Vuelve a conectarte para que se haga una copia de seguridad de tus claves antes de eliminar este dispositivo." "Se sigue guardando una copia de seguridad de tus claves" - "Espera a que se complete antes de cerrar sesión." + "Espera a que se complete antes de eliminar este dispositivo." "Se sigue guardando una copia de seguridad de tus claves" - "Cerrar sesión" - "Estás a punto de cerrar tu última sesión. Si cierras sesión ahora, perderás el acceso a tus mensajes cifrados." - "La recuperación no está configurada" - "Estás a punto de cerrar tu última sesión. Si cierras la sesión ahora, podrías perder el acceso a tus mensajes cifrados." - "¿Has guardado tu clave de recuperación?" + "Eliminar este dispositivo" + "Este es tu único dispositivo. Si lo eliminas, necesitarás una clave de recuperación para poder confirmar tu identidad digital y restaurar tus chats cifrados la próxima vez que inicies sesión." + "Estás a punto de perder el acceso a tus chats cifrados." + "Este es tu único dispositivo. Si lo eliminas, necesitarás una clave de recuperación para poder confirmar tu identidad digital y restaurar tus chats cifrados la próxima vez que inicies sesión." + "Asegúrate de tener acceso a tu clave de recuperación antes de eliminar este dispositivo" diff --git a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessageComposerContext.kt b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessageComposerContext.kt index 534af8a5f9..12af1b32f2 100644 --- a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessageComposerContext.kt +++ b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessageComposerContext.kt @@ -17,5 +17,6 @@ import io.element.android.libraries.textcomposer.model.MessageComposerMode * the composer is in a thread, if it's editing a message, etc. */ interface MessageComposerContext { + /** What the composer is currently doing: writing a new message, editing one, replying, or composing in a thread. */ val composerMode: MessageComposerMode } diff --git a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessagesEntryPoint.kt b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessagesEntryPoint.kt index 3eecd54f3e..dd49dd0465 100644 --- a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessagesEntryPoint.kt +++ b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/MessagesEntryPoint.kt @@ -50,7 +50,16 @@ interface MessagesEntryPoint : FeatureEntryPoint { callback: Callback, ): Node + /** + * Lets callers outside this feature drive an already created messages node, for navigation that has to happen after it is attached. + */ interface NodeProxy { + /** + * Opens a thread on top of the messages screen, suspending until the thread node is attached. + * + * @param threadId the thread to open. + * @param focusedEventId the event to scroll to within the thread, or `null` to open at the latest message. + */ suspend fun attachThread(threadId: ThreadId, focusedEventId: EventId?) } } diff --git a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/pinned/PinnedEventsTimelineProvider.kt b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/pinned/PinnedEventsTimelineProvider.kt index 849b97479e..550373ed00 100644 --- a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/pinned/PinnedEventsTimelineProvider.kt +++ b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/pinned/PinnedEventsTimelineProvider.kt @@ -10,4 +10,9 @@ package io.element.android.features.messages.api.pinned import io.element.android.libraries.matrix.api.timeline.TimelineProvider +/** + * A [TimelineProvider] whose active timeline holds the pinned events of the room, rather than its live events. + * + * It exists as its own type so that it can be injected where only the pinned timeline is wanted. + */ interface PinnedEventsTimelineProvider : TimelineProvider diff --git a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/HtmlConverterProvider.kt b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/HtmlConverterProvider.kt index f44c996cac..baeb37e417 100644 --- a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/HtmlConverterProvider.kt +++ b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/HtmlConverterProvider.kt @@ -11,9 +11,16 @@ package io.element.android.features.messages.api.timeline import androidx.compose.runtime.Composable import io.element.android.wysiwyg.utils.HtmlConverter +/** + * Provides the converter that turns message HTML into styled text. + * + * The converter depends on the current theme and typography, so [Update] must be composed before [provide] is called. + */ interface HtmlConverterProvider { + /** Rebuilds the converter from the current Compose theme; call this once, high in the composition of a screen that renders messages. */ @Composable fun Update() + /** Returns the converter built by the last [Update] call. */ fun provide(): HtmlConverter } diff --git a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerPresenter.kt b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerPresenter.kt index 848f9fe82d..832d029e40 100644 --- a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerPresenter.kt +++ b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerPresenter.kt @@ -12,7 +12,13 @@ import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.matrix.api.timeline.Timeline fun interface VoiceMessageComposerPresenter : Presenter { + /** + * Creates a presenter for one voice message composer. + */ interface Factory { + /** + * @param timelineMode the timeline the recording will be sent to, which matters for threads in particular. + */ fun create(timelineMode: Timeline.Mode): VoiceMessageComposerPresenter } } diff --git a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerStateProvider.kt b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerStatePreviewParam.kt similarity index 93% rename from features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerStateProvider.kt rename to features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerStatePreviewParam.kt index 7b264a3ddb..2cf698dd84 100644 --- a/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerStateProvider.kt +++ b/features/messages/api/src/main/kotlin/io/element/android/features/messages/api/timeline/voicemessages/composer/VoiceMessageComposerStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.designsystem.components.media.WaveFormSample import io.element.android.libraries.textcomposer.model.VoiceMessageState import kotlin.time.Duration.Companion.seconds -open class VoiceMessageComposerStateProvider : PreviewParameterProvider { +open class VoiceMessageComposerStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aVoiceMessageComposerState(voiceMessageState = VoiceMessageState.Recording(duration = 61.seconds, levels = WaveFormSamples.allRangeWaveForm)), diff --git a/features/messages/impl/build.gradle.kts b/features/messages/impl/build.gradle.kts index b40aebab39..0b51a2b80d 100644 --- a/features/messages/impl/build.gradle.kts +++ b/features/messages/impl/build.gradle.kts @@ -61,6 +61,7 @@ dependencies { implementation(projects.libraries.push.api) implementation(projects.libraries.uiUtils) implementation(projects.libraries.testtags) + implementation(projects.libraries.wellknown.api) implementation(projects.features.networkmonitor.api) implementation(projects.features.contentscanner.api) implementation(projects.services.analytics.compose) diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesPresenter.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesPresenter.kt index dd3afb0ea6..4af0c05955 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesPresenter.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesPresenter.kt @@ -400,9 +400,23 @@ class MessagesPresenter( TimelineItemAction.Pin -> handlePinAction(targetEvent) TimelineItemAction.Unpin -> handleUnpinAction(targetEvent) TimelineItemAction.ViewInTimeline -> Unit + TimelineItemAction.RetrySending -> handleRetrySending(targetEvent) } } + private suspend fun handleRetrySending(targetEvent: TimelineItem.Event) { + val sendHandle = targetEvent.sendhandle ?: return Unit.also { + Timber.w("No send handle for event ${targetEvent.eventOrTransactionId}") + } + sendHandle.retry() + .onSuccess { + Timber.d("Succeed to add the message back to the send queue") + } + .onFailure { + Timber.e(it, "Failed to add the message back to the send queue") + } + } + private suspend fun handleRemoveCaption(targetEvent: TimelineItem.Event) { timelineController.invokeOnCurrentTimeline { editCaption( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesStatePreviewParam.kt similarity index 99% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesStatePreviewParam.kt index 7315ace96e..8ab7e64121 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesStatePreviewParam.kt @@ -57,7 +57,7 @@ import io.element.android.libraries.textcomposer.model.aTextEditorStateRich import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentSetOf -open class MessagesStateProvider : PreviewParameterProvider { +open class MessagesStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMessagesState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesView.kt index 5911de7372..16ca023d50 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/MessagesView.kt @@ -93,6 +93,7 @@ import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.model.TimelineItemGroupPosition import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemStateEventContent import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemTextContent +import io.element.android.features.messages.impl.timeline.sendfailure.SendFailureDialogView import io.element.android.features.messages.impl.topbars.MessagesViewTopBar import io.element.android.features.messages.impl.topbars.ThreadTopBar import io.element.android.features.messages.impl.voicemessages.composer.VoiceMessagePermissionRationaleDialog @@ -178,8 +179,8 @@ fun MessagesView( fun onContentClick(event: TimelineItem.Event) { Timber.v("onMessageClick= ${event.id}") - val eventId = event.eventId ?: return - if (eventContentValidationState[eventId].getCurrentOverallState() != ContentValidationValue.Valid) return + val eventId = event.eventId + if (eventId != null && eventContentValidationState[eventId].getCurrentOverallState() != ContentValidationValue.Valid) return val hideKeyboard = onEventContentClick(state.timelineState.isLive, event) if (hideKeyboard) { @@ -429,6 +430,31 @@ fun MessagesView( }, state = state.linkState, ) + + SendFailureDialogView( + sendFailureDialogState = state.timelineState.sendFailureDialogState, + onDismiss = { + state.timelineState.eventSink(TimelineEvent.HideSendFailureDialog) + }, + onRetry = { event -> + state.eventSink( + MessagesEvent.HandleAction( + action = TimelineItemAction.RetrySending, + event = event, + ) + ) + state.timelineState.eventSink(TimelineEvent.HideSendFailureDialog) + }, + onRemoveMessage = { event -> + state.eventSink( + MessagesEvent.HandleAction( + action = TimelineItemAction.Redact, + event = event, + ) + ) + state.timelineState.eventSink(TimelineEvent.HideSendFailureDialog) + }, + ) } @Composable @@ -590,13 +616,19 @@ private fun MessagesViewComposerBottomSheetContents( when { state.successorRoom != null -> { SuccessorRoomBanner( - modifier = Modifier.fillMaxWidth().padding(contentPadding), + modifier = Modifier + .fillMaxWidth() + .padding(contentPadding), roomSuccessor = state.successorRoom, onRoomSuccessorClick = onRoomSuccessorClick ) } state.userEventPermissions.canSendMessage -> { - Column(modifier = Modifier.fillMaxWidth().padding(contentPadding)) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(contentPadding) + ) { // Do not show the identity change if user is composing a Rich message or is seeing suggestion(s). if (state.composerState.suggestions.isEmpty() && state.composerState.textEditorState is TextEditorState.Markdown) { @@ -662,7 +694,7 @@ private fun SuccessorRoomBanner( @PreviewsDayNight @Composable -internal fun MessagesViewPreview(@PreviewParameter(MessagesStateProvider::class) state: MessagesState) = ElementPreview { +internal fun MessagesViewPreview(@PreviewParameter(MessagesStatePreviewParam::class) state: MessagesState) = ElementPreview { MessagesView( state = state, onBackClick = {}, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListStatePreviewParam.kt similarity index 99% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListStatePreviewParam.kt index 56bac5be33..8474b4833d 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListStatePreviewParam.kt @@ -28,7 +28,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -open class ActionListStateProvider : PreviewParameterProvider { +open class ActionListStatePreviewParam : PreviewParameterProvider { private val suggestedEmojis = persistentListOf("👍️", "👎️", "🔥", "❤️", "👏") override val values: Sequence diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListView.kt index 669a696111..24a325b641 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/ActionListView.kt @@ -514,7 +514,7 @@ private fun EmojiButton( @PreviewsDayNight @Composable internal fun ActionListViewContentPreview( - @PreviewParameter(ActionListStateProvider::class) state: ActionListState + @PreviewParameter(ActionListStatePreviewParam::class) state: ActionListState ) = ElementPreview { ActionListViewContent( state = state, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemAction.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemAction.kt index 25e75beb99..3c64223e59 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemAction.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemAction.kt @@ -36,4 +36,7 @@ enum class TimelineItemAction( EndPoll(CommonStrings.action_end_poll, CompoundDrawables.ic_compound_polls_end), Pin(CommonStrings.action_pin, CompoundDrawables.ic_compound_pin), Unpin(CommonStrings.action_unpin, CompoundDrawables.ic_compound_unpin), + + // Note: this action is not used in UI for now + RetrySending(CommonStrings.action_retry, CompoundDrawables.ic_compound_send_solid), } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemActionComparator.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemActionComparator.kt index 0a0d9b17af..2f6fa4e4e0 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemActionComparator.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/actionlist/model/TimelineItemActionComparator.kt @@ -32,6 +32,8 @@ class TimelineItemActionComparator : Comparator { TimelineItemAction.ViewSource, TimelineItemAction.ReportContent, TimelineItemAction.Redact, + // Not rendered in the action list, but has to be listed here for exhaustiveness. + TimelineItemAction.RetrySending, ) override fun compare(o1: TimelineItemAction, o2: TimelineItemAction): Int { diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewStatePreviewParam.kt similarity index 98% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewStatePreviewParam.kt index a7d4e14436..cdcc37008d 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewStatePreviewParam.kt @@ -30,7 +30,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import java.io.File -open class AttachmentsPreviewStateProvider : PreviewParameterProvider { +open class AttachmentsPreviewStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAttachmentsPreviewState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewView.kt index 077d086720..86b8a85557 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/AttachmentsPreviewView.kt @@ -553,7 +553,7 @@ private fun AttachmentsPreviewBottomActions( // Only preview in dark, dark theme is forced on the Node. @Preview @Composable -internal fun AttachmentsPreviewViewPreview(@PreviewParameter(AttachmentsPreviewStateProvider::class) state: AttachmentsPreviewState) = ElementPreviewDark { +internal fun AttachmentsPreviewViewPreview(@PreviewParameter(AttachmentsPreviewStatePreviewParam::class) state: AttachmentsPreviewState) = ElementPreviewDark { AttachmentsPreviewView( state = state, localMediaRenderer = SampleMediaRenderer(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorStatePreviewParam.kt similarity index 97% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorStatePreviewParam.kt index 7c542fd1a8..fb9901e7ec 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.core.net.toUri import io.element.android.libraries.mediaviewer.api.anImageMediaInfo import io.element.android.libraries.mediaviewer.api.local.LocalMedia -open class AttachmentImageEditorStateProvider : PreviewParameterProvider { +open class AttachmentImageEditorStatePreviewParam : PreviewParameterProvider { private val caterpillarCrop = NormalizedCropRect( left = 0.3f, top = 0.3f, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorView.kt index a5317b96c6..70a3375fa8 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/attachments/preview/imageeditor/AttachmentImageEditorView.kt @@ -676,7 +676,7 @@ private fun DrawScope.drawEdgeHandle( @Preview @Composable internal fun AttachmentImageEditorViewPreview( - @PreviewParameter(AttachmentImageEditorStateProvider::class) state: AttachmentImageEditorState, + @PreviewParameter(AttachmentImageEditorStatePreviewParam::class) state: AttachmentImageEditorState, ) = ElementPreviewDark { AttachmentImageEditorView( state = state, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStatePreviewParam.kt similarity index 97% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStatePreviewParam.kt index be53de5f66..bc1d587709 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStatePreviewParam.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.matrix.ui.room.IdentityRoomMember import io.element.android.libraries.matrix.ui.room.RoomMemberIdentityStateChange import kotlinx.collections.immutable.toImmutableList -class IdentityChangeStateProvider : PreviewParameterProvider { +class IdentityChangeStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anIdentityChangeState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStateView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStateView.kt index 21684206b5..1c7bb38588 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStateView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/IdentityChangeStateView.kt @@ -122,7 +122,7 @@ private fun ViolationAlert( @PreviewsDayNight @Composable internal fun IdentityChangeStateViewPreview( - @PreviewParameter(IdentityChangeStateProvider::class) state: IdentityChangeState, + @PreviewParameter(IdentityChangeStatePreviewParam::class) state: IdentityChangeState, ) = ElementPreview { IdentityChangeStateView( state = state, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/MessagesViewWithIdentityChangePreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/MessagesViewWithIdentityChangePreview.kt index 4e9bf9249a..5e5afb7f60 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/MessagesViewWithIdentityChangePreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/identity/MessagesViewWithIdentityChangePreview.kt @@ -20,7 +20,7 @@ import io.element.android.libraries.textcomposer.model.aTextEditorStateMarkdown @PreviewsDayNight @Composable internal fun MessagesViewWithIdentityChangePreview( - @PreviewParameter(IdentityChangeStateProvider::class) identityChangeState: IdentityChangeState + @PreviewParameter(IdentityChangeStatePreviewParam::class) identityChangeState: IdentityChangeState ) = ElementPreview { MessagesView( state = aMessagesState( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureStatePreviewParam.kt similarity index 93% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureStatePreviewParam.kt index ee4b749c8f..624882b509 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.features.messages.impl.crypto.sendfailure.VerifiedUser import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.designsystem.preview.USER_NAME_ALICE -open class ResolveVerifiedUserSendFailureStateProvider : PreviewParameterProvider { +open class ResolveVerifiedUserSendFailureStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aResolveVerifiedUserSendFailureState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureView.kt index a430d4621f..2d745df474 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/crypto/sendfailure/resolve/ResolveVerifiedUserSendFailureView.kt @@ -158,7 +158,7 @@ private fun VerifiedUserSendFailure.resolveAction(): String { @PreviewsDayNight @Composable internal fun ResolveVerifiedUserSendFailureViewPreview( - @PreviewParameter(ResolveVerifiedUserSendFailureStateProvider::class) state: ResolveVerifiedUserSendFailureState + @PreviewParameter(ResolveVerifiedUserSendFailureStatePreviewParam::class) state: ResolveVerifiedUserSendFailureState ) = ElementPreview { ResolveVerifiedUserSendFailureView(state) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesBindsModule.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesBindingContainer.kt similarity index 98% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesBindsModule.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesBindingContainer.kt index a345e09fa2..7e67c027d7 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesBindsModule.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesBindingContainer.kt @@ -34,7 +34,7 @@ import io.element.android.libraries.di.RoomScope @ContributesTo(RoomScope::class) @BindingContainer -interface MessagesBindsModule { +interface MessagesBindingContainer { @Binds fun bindPinnedMessagesBannerPresenter(presenter: PinnedMessagesBannerPresenter): Presenter diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesProvidesModule.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesProvidesBindingContainer.kt similarity index 85% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesProvidesModule.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesProvidesBindingContainer.kt index 856a14cdb0..f66c26061b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesProvidesModule.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/di/MessagesProvidesBindingContainer.kt @@ -18,8 +18,8 @@ import io.element.android.libraries.matrix.api.timeline.Timeline @ContributesTo(RoomScope::class) @BindingContainer -object MessagesProvidesModule { +object MessagesProvidesBindingContainer { @Provides @LiveTimeline - fun provideLiveTimeline(joinedRoom: JoinedRoom): Timeline = joinedRoom.liveTimeline + fun providesLiveTimeline(joinedRoom: JoinedRoom): Timeline = joinedRoom.liveTimeline } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkStatePreviewParam.kt similarity index 93% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkStatePreviewParam.kt index 2e021ec276..f72d9e2517 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.wysiwyg.link.Link -open class LinkStateProvider : PreviewParameterProvider { +open class LinkStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLinkState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkView.kt index 69e6ee8673..950765f40f 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/link/LinkView.kt @@ -66,7 +66,7 @@ fun LinkView( @PreviewsDayNight @Composable -internal fun LinkViewPreview(@PreviewParameter(LinkStateProvider::class) state: LinkState) = ElementPreview { +internal fun LinkViewPreview(@PreviewParameter(LinkStatePreviewParam::class) state: LinkState) = ElementPreview { LinkView( state = state, onLinkValid = {}, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenter.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenter.kt index 18252ee17d..2974b99696 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenter.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenter.kt @@ -86,6 +86,7 @@ import io.element.android.libraries.textcomposer.model.MarkdownTextEditorState import io.element.android.libraries.textcomposer.model.Message import io.element.android.libraries.textcomposer.model.MessageComposerMode import io.element.android.libraries.textcomposer.model.Suggestion +import io.element.android.libraries.textcomposer.model.SuggestionType import io.element.android.libraries.textcomposer.model.TextEditorState import io.element.android.libraries.textcomposer.model.rememberMarkdownTextEditorState import io.element.android.services.analytics.api.AnalyticsService @@ -103,7 +104,9 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -425,6 +428,7 @@ class MessageComposerPresenter( textEditorState = textEditorState, isFullScreen = isFullScreen.value, mode = messageComposerContext.composerMode, + isInThreadTimeline = isInThread, showAttachmentSourcePicker = showAttachmentSourcePicker, showTextFormatting = showTextFormatting, canShareLocation = canShareLocation.value, @@ -458,6 +462,14 @@ class MessageComposerPresenter( val mentionTriggerFlow = merge(mentionStartTrigger, mentionCompletionTrigger) + // Refresh the room members, which are only loaded on demand, when a mention starts + launch { + suggestionSearchTrigger + .distinctUntilChangedBy { it?.type } + .filter { it?.type == SuggestionType.Mention } + .collect { room.updateMembers() } + } + val roomAliasSuggestionsFlow = roomAliasSuggestionsDataSource .getAllRoomAliasSuggestions() .stateIn(this, SharingStarted.Lazily, emptyList()) diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerState.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerState.kt index f3fdb3d59a..b4da119d96 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerState.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerState.kt @@ -21,6 +21,7 @@ data class MessageComposerState( val textEditorState: TextEditorState, val isFullScreen: Boolean, val mode: MessageComposerMode, + val isInThreadTimeline: Boolean, val showAttachmentSourcePicker: Boolean, val showTextFormatting: Boolean, val canShareLocation: Boolean, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerStatePreviewParam.kt similarity index 91% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerStatePreviewParam.kt index ef9cd7933b..31ef5fed50 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerStatePreviewParam.kt @@ -18,7 +18,7 @@ import io.element.android.wysiwyg.display.TextDisplay import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -open class MessageComposerStateProvider : PreviewParameterProvider { +open class MessageComposerStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMessageComposerState(), @@ -29,6 +29,7 @@ fun aMessageComposerState( textEditorState: TextEditorState = aTextEditorStateRich(), isFullScreen: Boolean = false, mode: MessageComposerMode = MessageComposerMode.Normal, + isInThreadTimeline: Boolean = false, showTextFormatting: Boolean = false, showAttachmentSourcePicker: Boolean = false, canShareLocation: Boolean = true, @@ -39,6 +40,7 @@ fun aMessageComposerState( textEditorState = textEditorState, isFullScreen = isFullScreen, mode = mode, + isInThreadTimeline = isInThreadTimeline, showTextFormatting = showTextFormatting, showAttachmentSourcePicker = showAttachmentSourcePicker, canShareLocation = canShareLocation, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerView.kt index 245b23cf8e..58842b6824 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerView.kt @@ -20,7 +20,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp import io.element.android.features.messages.api.timeline.voicemessages.composer.VoiceMessageComposerEvent import io.element.android.features.messages.api.timeline.voicemessages.composer.VoiceMessageComposerState -import io.element.android.features.messages.api.timeline.voicemessages.composer.VoiceMessageComposerStateProvider +import io.element.android.features.messages.api.timeline.voicemessages.composer.VoiceMessageComposerStatePreviewParam import io.element.android.features.messages.api.timeline.voicemessages.composer.aVoiceMessageComposerState import io.element.android.libraries.designsystem.components.async.AsyncActionView import io.element.android.libraries.designsystem.preview.ElementPreview @@ -102,6 +102,7 @@ internal fun MessageComposerView( onRequestFocus = ::onRequestFocus, onSendMessage = ::sendMessage, composerMode = state.mode, + isInThreadTimeline = state.isInThreadTimeline, showTextFormatting = state.showTextFormatting, onResetComposerMode = ::onCloseSpecialMode, onAddAttachment = ::onAddAttachment, @@ -128,7 +129,7 @@ internal fun MessageComposerView( @PreviewsDayNight @Composable internal fun MessageComposerViewPreview( - @PreviewParameter(MessageComposerStateProvider::class) state: MessageComposerState, + @PreviewParameter(MessageComposerStatePreviewParam::class) state: MessageComposerState, ) = ElementPreview { Column { MessageComposerView( @@ -148,7 +149,7 @@ internal fun MessageComposerViewPreview( @PreviewsDayNight @Composable internal fun MessageComposerViewVoicePreview( - @PreviewParameter(VoiceMessageComposerStateProvider::class) state: VoiceMessageComposerState, + @PreviewParameter(VoiceMessageComposerStatePreviewParam::class) state: VoiceMessageComposerState, ) = ElementPreview { Column { MessageComposerView( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/DisplayablePinnedEvents.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/DisplayablePinnedEvents.kt new file mode 100644 index 0000000000..55c4b61ed1 --- /dev/null +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/DisplayablePinnedEvents.kt @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.pinned + +import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem +import io.element.android.libraries.matrix.api.timeline.item.event.EventContent +import io.element.android.libraries.matrix.api.timeline.item.event.FailedToParseMessageLikeContent +import io.element.android.libraries.matrix.api.timeline.item.event.FailedToParseStateContent +import io.element.android.libraries.matrix.api.timeline.item.event.UnknownContent +import io.element.android.libraries.matrix.api.timeline.item.virtual.VirtualTimelineItem + +internal fun List.keepDisplayablePinnedEvents(): List { + val items = filter { it.isDisplayableAsPinnedEvent() } + return items.filterIndexed { index, item -> + !item.isDayDivider() || items.getOrNull(index + 1) is MatrixTimelineItem.Event + } +} + +internal fun EventContent.isDisplayableAsPinnedEvent(): Boolean { + return when (this) { + UnknownContent, + is FailedToParseMessageLikeContent, + is FailedToParseStateContent -> false + else -> true + } +} + +private fun MatrixTimelineItem.isDisplayableAsPinnedEvent(): Boolean { + return this !is MatrixTimelineItem.Event || event.content.isDisplayableAsPinnedEvent() +} + +private fun MatrixTimelineItem.isDayDivider(): Boolean { + return this is MatrixTimelineItem.Virtual && virtual is VirtualTimelineItem.DayDivider +} diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerItemFactory.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerItemFactory.kt index d1d53b36b4..0420416bff 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerItemFactory.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerItemFactory.kt @@ -10,6 +10,7 @@ package io.element.android.features.messages.impl.pinned.banner import androidx.compose.ui.text.AnnotatedString import dev.zacsweers.metro.Inject +import io.element.android.features.messages.impl.pinned.isDisplayableAsPinnedEvent import io.element.android.libraries.core.coroutine.CoroutineDispatchers import io.element.android.libraries.eventformatter.api.PinnedMessagesBannerFormatter import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem @@ -24,6 +25,7 @@ class PinnedMessagesBannerItemFactory( when (timelineItem) { is MatrixTimelineItem.Event -> { val eventId = timelineItem.eventId ?: return@withContext null + if (!timelineItem.event.content.isDisplayableAsPinnedEvent()) return@withContext null val formatted = formatter.format(timelineItem.event) PinnedMessagesBannerItem( eventId = eventId, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerStatePreviewParam.kt similarity index 96% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerStatePreviewParam.kt index 2a2c30bf6b..37660d0000 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerStatePreviewParam.kt @@ -13,7 +13,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.matrix.api.core.EventId import kotlin.random.Random -internal class PinnedMessagesBannerStateProvider : PreviewParameterProvider { +internal class PinnedMessagesBannerStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aHiddenPinnedMessagesBannerState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerView.kt index bc80d6b014..70a98d4b4e 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerView.kt @@ -294,7 +294,9 @@ private class ExitOnScrollBehavior : PinnedMessagesBannerViewScrollBehavior { @PreviewsDayNight @Composable -internal fun PinnedMessagesBannerViewPreview(@PreviewParameter(PinnedMessagesBannerStateProvider::class) state: PinnedMessagesBannerState) = ElementPreview { +internal fun PinnedMessagesBannerViewPreview(@PreviewParameter( + PinnedMessagesBannerStatePreviewParam::class +) state: PinnedMessagesBannerState) = ElementPreview { PinnedMessagesBannerView( state = state, onClick = {}, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListEvent.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListEvent.kt index 73ba08b29d..9be11d244a 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListEvent.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListEvent.kt @@ -11,8 +11,10 @@ package io.element.android.features.messages.impl.pinned.list import io.element.android.features.messages.impl.actionlist.model.TimelineItemAction import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.libraries.matrix.api.core.ThreadId +import io.element.android.libraries.matrix.api.timeline.item.event.EventOrTransactionId sealed interface PinnedMessagesListEvent { data class HandleAction(val action: TimelineItemAction, val event: TimelineItem.Event) : PinnedMessagesListEvent data class OpenThread(val threadRootId: ThreadId) : PinnedMessagesListEvent + data class ToggleReaction(val emoji: String, val eventOrTransactionId: EventOrTransactionId) : PinnedMessagesListEvent } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListNode.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListNode.kt index 06d97f167c..36ae68de9b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListNode.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListNode.kt @@ -30,6 +30,7 @@ import io.element.android.libraries.androidutils.system.copyToClipboard import io.element.android.libraries.androidutils.system.openUrlInExternalApp import io.element.android.libraries.architecture.callback import io.element.android.libraries.di.RoomScope +import io.element.android.libraries.emoji.api.picker.EmojiPickerRenderer import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.ThreadId import io.element.android.libraries.matrix.api.core.UserId @@ -50,6 +51,7 @@ class PinnedMessagesListNode( actionListPresenterFactory: ActionListPresenter.Factory, private val timelineItemPresenterFactories: TimelineItemPresenterFactories, private val permalinkParser: PermalinkParser, + private val emojiPickerRenderer: EmojiPickerRenderer, ) : Node(buildContext, plugins = plugins), PinnedMessagesListNavigator { interface Callback : Plugin { fun handleEventClick(event: TimelineItem.Event, canUseOverlay: Boolean) @@ -134,6 +136,7 @@ class PinnedMessagesListNode( toastMessage = toastMessage, ) }, + emojiPickerRenderer = emojiPickerRenderer, modifier = modifier ) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenter.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenter.kt index 6e8974b871..748fa084f8 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenter.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenter.kt @@ -28,7 +28,10 @@ import io.element.android.features.messages.impl.actionlist.ActionListState import io.element.android.features.messages.impl.actionlist.model.TimelineItemAction import io.element.android.features.messages.impl.link.LinkState import io.element.android.features.messages.impl.pinned.DefaultPinnedEventsTimelineProvider +import io.element.android.features.messages.impl.pinned.keepDisplayablePinnedEvents import io.element.android.features.messages.impl.timeline.TimelineRoomInfo +import io.element.android.features.messages.impl.timeline.components.customreaction.CustomReactionState +import io.element.android.features.messages.impl.timeline.components.reactionsummary.ReactionSummaryState import io.element.android.features.messages.impl.timeline.factories.TimelineItemsFactory import io.element.android.features.messages.impl.timeline.factories.TimelineItemsFactoryConfig import io.element.android.features.messages.impl.timeline.model.TimelineItem @@ -46,6 +49,7 @@ import io.element.android.libraries.featureflag.api.FeatureFlags import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.api.room.powerlevels.permissionsAsState import io.element.android.libraries.matrix.api.room.roomMembers +import io.element.android.libraries.matrix.api.timeline.item.event.EventOrTransactionId import io.element.android.libraries.ui.strings.CommonStrings import io.element.android.services.analytics.api.AnalyticsService import io.element.android.services.analyticsproviders.api.trackers.captureInteraction @@ -70,6 +74,8 @@ class PinnedMessagesListPresenter( private val linkPresenter: Presenter, private val snackbarDispatcher: SnackbarDispatcher, @Assisted private val actionListPresenter: Presenter, + private val customReactionPresenter: Presenter, + private val reactionSummaryPresenter: Presenter, @SessionCoroutineScope private val sessionCoroutineScope: CoroutineScope, private val analyticsService: AnalyticsService, @@ -87,7 +93,7 @@ class PinnedMessagesListPresenter( private val timelineItemsFactory: TimelineItemsFactory = timelineItemsFactoryCreator.create( config = TimelineItemsFactoryConfig( computeReadReceipts = false, - computeReactions = false, + computeReactions = true, ) ) @@ -95,6 +101,9 @@ class PinnedMessagesListPresenter( override fun present(): PinnedMessagesListState { htmlConverterProvider.Update() val roomInfo by room.roomInfoFlow.collectAsState() + val userEventPermissions by room.permissionsAsState(UserEventPermissions.DEFAULT) { perms -> + perms.userEventPermissions() + } val timelineRoomInfo by remember { derivedStateOf { TimelineRoomInfo( @@ -102,7 +111,7 @@ class PinnedMessagesListPresenter( name = roomInfo.name, // We don't need to compute those values userHasPermissionToSendMessage = false, - userHasPermissionToSendReaction = false, + userHasPermissionToSendReaction = userEventPermissions.canSendReaction, // We do not care about the call state here. roomCallState = aStandByCallState(), // don't compute this value or the pin icon will be shown @@ -118,9 +127,8 @@ class PinnedMessagesListPresenter( } val timelineProtectionState = timelineProtectionPresenter.present() val linkState = linkPresenter.present() - val userEventPermissions by room.permissionsAsState(UserEventPermissions.DEFAULT) { perms -> - perms.userEventPermissions() - } + val customReactionState = customReactionPresenter.present() + val reactionSummaryState = reactionSummaryPresenter.present() val displayThreadSummaries by featureFlagService.isFeatureEnabledFlow(FeatureFlags.Threads).collectAsState(false) @@ -137,6 +145,7 @@ class PinnedMessagesListPresenter( when (event) { is PinnedMessagesListEvent.HandleAction -> sessionCoroutineScope.handleTimelineAction(event.action, event.event) is PinnedMessagesListEvent.OpenThread -> navigator.navigateToThread(event.threadRootId) + is PinnedMessagesListEvent.ToggleReaction -> sessionCoroutineScope.toggleReaction(event.emoji, event.eventOrTransactionId) } } @@ -147,10 +156,20 @@ class PinnedMessagesListPresenter( displayThreadSummaries = displayThreadSummaries, userEventPermissions = userEventPermissions, timelineItems = pinnedMessageItems, + customReactionState = customReactionState, + reactionSummaryState = reactionSummaryState, eventSink = ::handleEvent, ) } + private fun CoroutineScope.toggleReaction(emoji: String, eventOrTransactionId: EventOrTransactionId) { + launch { + timelineProvider.invokeOnTimeline { + toggleReaction(emoji, eventOrTransactionId) + } + } + } + private fun CoroutineScope.handleTimelineAction( action: TimelineItemAction, targetEvent: TimelineItem.Event, @@ -207,7 +226,7 @@ class PinnedMessagesListPresenter( val timelineItemsFlow = asyncTimeline.data.timelineItems combine(timelineItemsFlow, room.membersStateFlow) { items, membersState -> timelineItemsFactory.replaceWith( - timelineItems = items, + timelineItems = items.keepDisplayablePinnedEvents(), roomMembers = membersState.roomMembers().orEmpty(), renderReadReceipts = false, ) @@ -233,13 +252,15 @@ class PinnedMessagesListPresenter( linkState: LinkState, userEventPermissions: UserEventPermissions, timelineItems: AsyncData>, + customReactionState: CustomReactionState, + reactionSummaryState: ReactionSummaryState, eventSink: (PinnedMessagesListEvent) -> Unit ): PinnedMessagesListState { return when (timelineItems) { AsyncData.Uninitialized, is AsyncData.Loading -> PinnedMessagesListState.Loading is AsyncData.Failure -> PinnedMessagesListState.Failed is AsyncData.Success -> { - if (timelineItems.data.isEmpty()) { + if (timelineItems.data.all { it is TimelineItem.Virtual }) { PinnedMessagesListState.Empty } else { val actionListState = actionListPresenter.present() @@ -251,6 +272,8 @@ class PinnedMessagesListPresenter( userEventPermissions = userEventPermissions, timelineItems = timelineItems.data, actionListState = actionListState, + customReactionState = customReactionState, + reactionSummaryState = reactionSummaryState, eventSink = eventSink ) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListState.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListState.kt index bf37029eff..6c55a0d90a 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListState.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListState.kt @@ -16,6 +16,8 @@ import io.element.android.features.messages.impl.UserEventPermissions import io.element.android.features.messages.impl.actionlist.ActionListState import io.element.android.features.messages.impl.link.LinkState import io.element.android.features.messages.impl.timeline.TimelineRoomInfo +import io.element.android.features.messages.impl.timeline.components.customreaction.CustomReactionState +import io.element.android.features.messages.impl.timeline.components.reactionsummary.ReactionSummaryState import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.protection.TimelineProtectionState import io.element.android.libraries.ui.strings.CommonPlurals @@ -34,6 +36,8 @@ sealed interface PinnedMessagesListState { val timelineItems: ImmutableList, val actionListState: ActionListState, val linkState: LinkState, + val customReactionState: CustomReactionState, + val reactionSummaryState: ReactionSummaryState, val displayThreadSummaries: Boolean, val eventSink: (PinnedMessagesListEvent) -> Unit, ) : PinnedMessagesListState { diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListStatePreviewParam.kt similarity index 88% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListStatePreviewParam.kt index bfa9820a44..3d01906df8 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListStatePreviewParam.kt @@ -10,6 +10,8 @@ package io.element.android.features.messages.impl.pinned.list import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.messages.impl.UserEventPermissions +import io.element.android.features.messages.impl.aCustomReactionState +import io.element.android.features.messages.impl.aReactionSummaryState import io.element.android.features.messages.impl.actionlist.ActionListState import io.element.android.features.messages.impl.actionlist.anActionListState import io.element.android.features.messages.impl.link.LinkState @@ -19,6 +21,8 @@ import io.element.android.features.messages.impl.timeline.aTimelineItemDaySepara import io.element.android.features.messages.impl.timeline.aTimelineItemEvent import io.element.android.features.messages.impl.timeline.aTimelineItemReactions import io.element.android.features.messages.impl.timeline.aTimelineRoomInfo +import io.element.android.features.messages.impl.timeline.components.customreaction.CustomReactionState +import io.element.android.features.messages.impl.timeline.components.reactionsummary.ReactionSummaryState import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.model.TimelineItemGroupPosition import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemAudioContent @@ -30,7 +34,7 @@ import io.element.android.features.messages.impl.timeline.protection.aTimelinePr import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -open class PinnedMessagesListStateProvider : PreviewParameterProvider { +open class PinnedMessagesListStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aFailedPinnedMessagesListState(), @@ -92,6 +96,8 @@ fun aLoadedPinnedMessagesListState( linkState: LinkState = aLinkState(), timelineItems: List = emptyList(), actionListState: ActionListState = anActionListState(), + customReactionState: CustomReactionState = aCustomReactionState(), + reactionSummaryState: ReactionSummaryState = aReactionSummaryState(), aUserEventPermissions: UserEventPermissions = UserEventPermissions.DEFAULT, displayThreadSummaries: Boolean = false, eventSink: (PinnedMessagesListEvent) -> Unit = {} @@ -101,6 +107,8 @@ fun aLoadedPinnedMessagesListState( linkState = linkState, timelineItems = timelineItems.toImmutableList(), actionListState = actionListState, + customReactionState = customReactionState, + reactionSummaryState = reactionSummaryState, userEventPermissions = aUserEventPermissions, displayThreadSummaries = displayThreadSummaries, eventSink = eventSink, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListView.kt index 4f69bacd28..5daec3e275 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListView.kt @@ -33,8 +33,12 @@ import io.element.android.features.messages.impl.link.LinkEvent import io.element.android.features.messages.impl.link.LinkView import io.element.android.features.messages.impl.timeline.TimelineEvent import io.element.android.features.messages.impl.timeline.components.TimelineItemRow +import io.element.android.features.messages.impl.timeline.components.customreaction.CustomReactionBottomSheet +import io.element.android.features.messages.impl.timeline.components.customreaction.CustomReactionEvent import io.element.android.features.messages.impl.timeline.components.event.TimelineItemEventContentView import io.element.android.features.messages.impl.timeline.components.layout.ContentAvoidingLayoutData +import io.element.android.features.messages.impl.timeline.components.reactionsummary.ReactionSummaryEvent +import io.element.android.features.messages.impl.timeline.components.reactionsummary.ReactionSummaryView import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.model.event.TimelineItemPollContent import io.element.android.features.messages.impl.timeline.protection.TimelineProtectionState @@ -50,6 +54,8 @@ import io.element.android.libraries.designsystem.theme.components.Scaffold import io.element.android.libraries.designsystem.theme.components.TopAppBar import io.element.android.libraries.designsystem.utils.lazyColumnContentPadding import io.element.android.libraries.designsystem.utils.scaffoldScrollableContentInsets +import io.element.android.libraries.emoji.api.picker.EmojiPickerRenderer +import io.element.android.libraries.emoji.api.picker.NoOpEmojiPickerRenderer import io.element.android.libraries.matrix.api.timeline.Timeline import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.ui.strings.CommonStrings @@ -66,6 +72,7 @@ fun PinnedMessagesListView( onUserDataClick: (MatrixUser) -> Unit, onLinkClick: (Link) -> Unit, onLinkLongClick: (Link) -> Unit, + emojiPickerRenderer: EmojiPickerRenderer, modifier: Modifier = Modifier, ) { Scaffold( @@ -89,6 +96,7 @@ fun PinnedMessagesListView( onLinkClick = onLinkClick, onLinkLongClick = onLinkLongClick, onErrorDismiss = onBackClick, + emojiPickerRenderer = emojiPickerRenderer, modifier = Modifier .padding(padding) .consumeWindowInsets(padding), @@ -121,6 +129,7 @@ private fun PinnedMessagesListContent( onLinkClick: (Link) -> Unit, onLinkLongClick: (Link) -> Unit, onErrorDismiss: () -> Unit, + emojiPickerRenderer: EmojiPickerRenderer, modifier: Modifier = Modifier, ) { Box(modifier.fillMaxSize()) { @@ -141,6 +150,7 @@ private fun PinnedMessagesListContent( onUserDataClick = onUserDataClick, onLinkClick = onLinkClick, onLinkLongClick = onLinkLongClick, + emojiPickerRenderer = emojiPickerRenderer, ) PinnedMessagesListState.Loading -> { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { @@ -180,6 +190,7 @@ private fun PinnedMessagesListLoaded( onUserDataClick: (MatrixUser) -> Unit, onLinkClick: (Link) -> Unit, onLinkLongClick: (Link) -> Unit, + emojiPickerRenderer: EmojiPickerRenderer, modifier: Modifier = Modifier, ) { fun onActionSelected(timelineItemAction: TimelineItemAction, event: TimelineItem.Event) { @@ -203,11 +214,25 @@ private fun PinnedMessagesListLoaded( ) } + fun onReactionClick(emoji: String, event: TimelineItem.Event) { + state.eventSink(PinnedMessagesListEvent.ToggleReaction(emoji, event.eventOrTransactionId)) + } + + fun onReactionLongClick(emoji: String, event: TimelineItem.Event) { + event.eventId?.let { eventId -> + state.reactionSummaryState.eventSink(ReactionSummaryEvent.ShowReactionSummary(eventId, event.reactionsState.reactions, emoji)) + } + } + + fun onMoreReactionsClick(event: TimelineItem.Event) { + state.customReactionState.eventSink(CustomReactionEvent.ShowCustomReactionSheet(event)) + } + ActionListView( state = state.actionListState, onSelectAction = ::onActionSelected, - onCustomReactionClick = {}, - onEmojiReactionClick = { _, _ -> }, + onCustomReactionClick = ::onMoreReactionsClick, + onEmojiReactionClick = ::onReactionClick, onVerifiedUserSendFailureClick = {} ) @@ -239,9 +264,9 @@ private fun PinnedMessagesListLoaded( onLongClick = ::onMessageLongClick, displayThreadSummaries = displayThreadSummaries, inReplyToClick = {}, - onReactionClick = { _, _ -> }, - onReactionLongClick = { _, _ -> }, - onMoreReactionsClick = {}, + onReactionClick = ::onReactionClick, + onReactionLongClick = ::onReactionLongClick, + onMoreReactionsClick = ::onMoreReactionsClick, onReadReceiptClick = {}, onSwipeToReply = {}, onJoinCallClick = {}, @@ -273,6 +298,14 @@ private fun PinnedMessagesListLoaded( state.linkState, onLinkValid = onLinkClick, ) + CustomReactionBottomSheet( + state = state.customReactionState, + onSelectEmoji = { eventOrTransactionId, emoji -> + state.eventSink(PinnedMessagesListEvent.ToggleReaction(emoji.unicode, eventOrTransactionId)) + }, + emojiPickerRenderer = emojiPickerRenderer, + ) + ReactionSummaryView(state = state.reactionSummaryState) } @Composable @@ -312,7 +345,7 @@ private fun TimelineItemEventContentViewWrapper( @PreviewsDayNight @Composable -internal fun PinnedMessagesListViewPreview(@PreviewParameter(PinnedMessagesListStateProvider::class) state: PinnedMessagesListState) = +internal fun PinnedMessagesListViewPreview(@PreviewParameter(PinnedMessagesListStatePreviewParam::class) state: PinnedMessagesListState) = ElementPreview { PinnedMessagesListView( state = state, @@ -322,5 +355,6 @@ internal fun PinnedMessagesListViewPreview(@PreviewParameter(PinnedMessagesListS onUserDataClick = {}, onLinkClick = {}, onLinkLongClick = {}, + emojiPickerRenderer = NoOpEmojiPickerRenderer, ) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageStatePreviewParam.kt similarity index 94% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageStatePreviewParam.kt index 0e2b4b0c50..1f24b3f480 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.messages.impl.report import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class ReportMessageStateProvider : PreviewParameterProvider { +open class ReportMessageStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aReportMessageState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageView.kt index dde3f13558..a3cf4f09da 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/report/ReportMessageView.kt @@ -137,7 +137,7 @@ fun ReportMessageView( @PreviewsDayNight @Composable -internal fun ReportMessageViewPreview(@PreviewParameter(ReportMessageStateProvider::class) state: ReportMessageState) = ElementPreview { +internal fun ReportMessageViewPreview(@PreviewParameter(ReportMessageStatePreviewParam::class) state: ReportMessageState) = ElementPreview { ReportMessageView( onBackClick = {}, state = state, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/threads/ThreadedMessagesNode.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/threads/ThreadedMessagesNode.kt index b56268eb02..b7fd9f572f 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/threads/ThreadedMessagesNode.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/threads/ThreadedMessagesNode.kt @@ -28,6 +28,7 @@ import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedInject import io.element.android.annotations.ContributesNode import io.element.android.compound.theme.ElementTheme +import io.element.android.features.messages.impl.MessagesEvent import io.element.android.features.messages.impl.MessagesNavigator import io.element.android.features.messages.impl.MessagesPresenter import io.element.android.features.messages.impl.MessagesState @@ -40,6 +41,7 @@ import io.element.android.features.messages.impl.messagecomposer.MessageComposer import io.element.android.features.messages.impl.timeline.TimelineController import io.element.android.features.messages.impl.timeline.TimelineEvent import io.element.android.features.messages.impl.timeline.TimelinePresenter +import io.element.android.features.messages.impl.timeline.components.customreaction.CustomReactionBottomSheet import io.element.android.features.messages.impl.timeline.di.LocalTimelineItemPresenterFactories import io.element.android.features.messages.impl.timeline.di.TimelineItemPresenterFactories import io.element.android.features.messages.impl.timeline.model.TimelineItem @@ -54,6 +56,7 @@ import io.element.android.libraries.architecture.callback import io.element.android.libraries.architecture.inputs import io.element.android.libraries.designsystem.utils.OnLifecycleEvent import io.element.android.libraries.di.RoomScope +import io.element.android.libraries.emoji.api.picker.EmojiPickerRenderer import io.element.android.libraries.matrix.api.analytics.toAnalyticsViewRoom import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomId @@ -91,6 +94,7 @@ class ThreadedMessagesNode( private val permalinkParser: PermalinkParser, private val appNavigationStateService: AppNavigationStateService, private val roomMemberModerationRenderer: RoomMemberModerationRenderer, + private val emojiPickerRenderer: EmojiPickerRenderer, ) : Node(buildContext, plugins = plugins), MessagesNavigator { data class Inputs( val threadRootEventId: ThreadId, @@ -322,7 +326,15 @@ class ThreadedMessagesNode( onViewAllPinnedMessagesClick = {}, modifier = modifier, knockRequestsBannerView = {}, - customReactionBottomSheet = {}, + customReactionBottomSheet = { + CustomReactionBottomSheet( + state = state.customReactionState, + onSelectEmoji = { uniqueId, emoji -> + state.eventSink(MessagesEvent.ToggleReaction(emoji.unicode, uniqueId)) + }, + emojiPickerRenderer = emojiPickerRenderer, + ) + }, onThreadsListClick = {}, ) diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineEvent.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineEvent.kt index f51103197d..de4031d1a4 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineEvent.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineEvent.kt @@ -34,6 +34,9 @@ sealed interface TimelineEvent { */ sealed interface TimelineItemEvent : TimelineEvent + data class ShowSendFailureDialog(val event: TimelineItem.Event) : TimelineItemEvent + data object HideSendFailureDialog : TimelineEvent + data class ComputeVerifiedUserSendFailure(val event: TimelineItem.Event) : TimelineItemEvent data class ShowShieldDialog(val messageShieldData: MessageShieldData) : TimelineItemEvent data class LoadMore(val direction: Timeline.PaginationDirection) : TimelineItemEvent diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenter.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenter.kt index da274445fd..3317d8f05c 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenter.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenter.kt @@ -37,6 +37,7 @@ import io.element.android.features.messages.impl.timeline.model.virtual.Timeline import io.element.android.features.messages.impl.timeline.model.virtual.TimelineItemTypingNotificationModel import io.element.android.features.messages.impl.timeline.protection.TimelineProtectionEvent import io.element.android.features.messages.impl.timeline.protection.TimelineProtectionState +import io.element.android.features.messages.impl.timeline.sendfailure.SendFailureDialogState import io.element.android.features.messages.impl.typing.TypingNotificationState import io.element.android.features.messages.impl.userEventPermissions import io.element.android.features.messages.impl.voicemessages.timeline.RedactedVoiceMessageManager @@ -56,6 +57,7 @@ import io.element.android.libraries.matrix.api.room.powerlevels.permissionsAsSta import io.element.android.libraries.matrix.api.room.roomMembers import io.element.android.libraries.matrix.api.timeline.ReceiptType import io.element.android.libraries.matrix.api.timeline.Timeline +import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState import io.element.android.libraries.matrix.api.timeline.item.event.TimelineItemEventOrigin import io.element.android.libraries.preferences.api.store.SessionPreferencesStore import io.element.android.services.analytics.api.AnalyticsLongRunningTransaction.DisplayFirstTimelineItems @@ -142,6 +144,7 @@ class TimelinePresenter( val newEventState = remember { mutableStateOf(NewEventState.None) } val messageShieldDialogData: MutableState = remember { mutableStateOf(null) } + var sendFailureDialogState by remember { mutableStateOf(SendFailureDialogState.Hidden) } // Forces [JumpToUnreadState.Hidden] until the next RoomInfo push. Set after a // [TimelineEvent.MarkAllAsRead] await completes so the FAB hides without waiting for @@ -166,9 +169,14 @@ class TimelinePresenter( fun handleEvent(event: TimelineEvent) { when (event) { is TimelineEvent.LoadMore -> { - if (event.direction == Timeline.PaginationDirection.FORWARDS && timelineMode is Timeline.Mode.Thread) { - // Do not paginate forwards in thread mode, as it's not supported - return + if (event.direction == Timeline.PaginationDirection.FORWARDS) { + if (timelineMode is Timeline.Mode.Thread) { + // Do not paginate forwards in thread mode, as it's not supported + return + } + if (focusRequestState.value.isPending()) { + return + } } localScope.launch { timelineController.paginate(direction = event.direction) @@ -246,6 +254,47 @@ class TimelinePresenter( suppressJumpToUnread.value = true } is TimelineEvent.ShowShieldDialog -> messageShieldDialogData.value = event.messageShieldData + is TimelineEvent.ShowSendFailureDialog -> { + val sendStateFailure = event.event.localSendState as? LocalEventSendState.Failed ?: return + when (sendStateFailure) { + is LocalEventSendState.Failed.VerifiedUser -> { + // defer to the resolveVerifiedUserSendFailureState to handle this case, + // as it will show a dialog with the right information + resolveVerifiedUserSendFailureState.eventSink(ResolveVerifiedUserSendFailureEvent.ComputeForMessage(event.event)) + } + is LocalEventSendState.Failed.InvalidMimeType -> { + sendFailureDialogState = SendFailureDialogState.Show( + event = event.event, + sendFailureType = SendFailureDialogState.SendFailureType.InvalidMimeType(sendStateFailure.mimeType), + ) + } + LocalEventSendState.Failed.MissingMediaContent -> { + sendFailureDialogState = SendFailureDialogState.Show( + event = event.event, + sendFailureType = SendFailureDialogState.SendFailureType.MissingMediaContent, + ) + } + LocalEventSendState.Failed.SendingFromUnverifiedDevice -> { + sendFailureDialogState = SendFailureDialogState.Show( + event = event.event, + sendFailureType = SendFailureDialogState.SendFailureType.SendingFromUnverifiedDevice, + ) + } + is LocalEventSendState.Failed.Unknown -> { + sendFailureDialogState = SendFailureDialogState.Show( + event = event.event, + sendFailureType = if (sendStateFailure.error.isNotBlank()) { + SendFailureDialogState.SendFailureType.Error(sendStateFailure.error) + } else { + SendFailureDialogState.SendFailureType.Unknown + } + ) + } + } + } + is TimelineEvent.HideSendFailureDialog -> { + sendFailureDialogState = SendFailureDialogState.Hidden + } is TimelineEvent.ComputeVerifiedUserSendFailure -> { resolveVerifiedUserSendFailureState.eventSink(ResolveVerifiedUserSendFailureEvent.ComputeForMessage(event.event)) } @@ -410,6 +459,7 @@ class TimelinePresenter( focusRequestState = focusRequestState.value, messageShieldDialogData = messageShieldDialogData.value, resolveVerifiedUserSendFailureState = resolveVerifiedUserSendFailureState, + sendFailureDialogState = sendFailureDialogState, displayThreadSummaries = displayThreadSummaries, displayJumpToUnread = displayJumpToUnread, jumpToUnread = jumpToUnread.value, @@ -539,6 +589,16 @@ private fun FocusRequestState.onFocusEventRender(): FocusRequestState { } } +private fun FocusRequestState.isPending(): Boolean { + return when (this) { + is FocusRequestState.Requested, + is FocusRequestState.Loading -> true + is FocusRequestState.Success -> !rendered + FocusRequestState.None, + is FocusRequestState.Failure -> false + } +} + // Workaround for not having the server names available, get possible server names from the user ids of the room members private fun calculateServerNamesForRoom(room: JoinedRoom): List { // If we have no room members, return right ahead diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineState.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineState.kt index 7836c17563..1ebc96f15f 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineState.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineState.kt @@ -13,6 +13,7 @@ import io.element.android.features.messages.impl.crypto.sendfailure.resolve.Reso import io.element.android.features.messages.impl.timeline.components.MessageShieldData import io.element.android.features.messages.impl.timeline.model.NewEventState import io.element.android.features.messages.impl.timeline.model.TimelineItem +import io.element.android.features.messages.impl.timeline.sendfailure.SendFailureDialogState import io.element.android.features.messages.impl.typing.TypingNotificationState import io.element.android.features.roomcall.api.RoomCallState import io.element.android.libraries.matrix.api.core.EventId @@ -32,6 +33,7 @@ data class TimelineState( // If not null, info will be rendered in a dialog val messageShieldDialogData: MessageShieldData?, val resolveVerifiedUserSendFailureState: ResolveVerifiedUserSendFailureState, + val sendFailureDialogState: SendFailureDialogState, val displayThreadSummaries: Boolean, val displayJumpToUnread: Boolean, val jumpToUnread: JumpToUnreadState, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineStateProvider.kt index 61b5c690a4..89545b5d0b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineStateProvider.kt @@ -25,6 +25,7 @@ import io.element.android.features.messages.impl.timeline.model.event.TimelineIt import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemStateEventContent import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemTextContent import io.element.android.features.messages.impl.timeline.model.virtual.aTimelineItemDaySeparatorModel +import io.element.android.features.messages.impl.timeline.sendfailure.SendFailureDialogState import io.element.android.features.messages.impl.typing.TypingNotificationState import io.element.android.features.messages.impl.typing.aTypingNotificationState import io.element.android.features.roomcall.api.aStandByCallState @@ -57,6 +58,7 @@ fun aTimelineState( isLive: Boolean = true, messageShield: MessageShield? = null, resolveVerifiedUserSendFailureState: ResolveVerifiedUserSendFailureState = aResolveVerifiedUserSendFailureState(), + sendFailureDialogState: SendFailureDialogState = SendFailureDialogState.Hidden, displayThreadSummaries: Boolean = false, displayJumpToUnread: Boolean = false, jumpToUnread: JumpToUnreadState = JumpToUnreadState.Hidden, @@ -78,6 +80,7 @@ fun aTimelineState( focusRequestState = focusRequestState, messageShieldDialogData = messageShield?.let { MessageShieldData(it) }, resolveVerifiedUserSendFailureState = resolveVerifiedUserSendFailureState, + sendFailureDialogState = sendFailureDialogState, displayThreadSummaries = displayThreadSummaries, displayJumpToUnread = displayJumpToUnread, jumpToUnread = jumpToUnread, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineView.kt index 78c067eed1..5e7fd34723 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/TimelineView.kt @@ -90,7 +90,7 @@ import io.element.android.features.messages.impl.timeline.focus.FocusRequestStat import io.element.android.features.messages.impl.timeline.model.NewEventState import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEventContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEventContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEventContentPreviewParam import io.element.android.features.messages.impl.timeline.protection.TimelineProtectionState import io.element.android.features.messages.impl.timeline.protection.aTimelineProtectionState import io.element.android.libraries.androidutils.system.copyToClipboard @@ -582,7 +582,7 @@ private fun JumpToPositionButton( @PreviewsDayNight @Composable internal fun TimelineViewPreview( - @PreviewParameter(TimelineItemEventContentProvider::class) content: TimelineItemEventContent + @PreviewParameter(TimelineItemEventContentPreviewParam::class) content: TimelineItemEventContent ) = ElementPreview { val timelineItems = aTimelineItemList(content) val timelineEvents = timelineItems.filterIsInstance() diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/CallMenuItem.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/CallMenuItem.kt index 28f5011652..d4b9885ea5 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/CallMenuItem.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/CallMenuItem.kt @@ -25,7 +25,7 @@ import androidx.compose.ui.unit.dp import io.element.android.compound.theme.ElementTheme import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.roomcall.api.RoomCallState -import io.element.android.features.roomcall.api.RoomCallStateProvider +import io.element.android.features.roomcall.api.RoomCallStatePreviewParam import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.designsystem.theme.components.Icon @@ -133,7 +133,7 @@ private fun OnGoingCallMenuItem( @PreviewsDayNight @Composable internal fun CallMenuItemPreview( - @PreviewParameter(RoomCallStateProvider::class) roomCallState: RoomCallState + @PreviewParameter(RoomCallStatePreviewParam::class) roomCallState: RoomCallState ) = ElementPreview { CallMenuItem( roomCallState = roomCallState, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessageEventBubble.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessageEventBubble.kt index 1ebdc34c6c..0dcf489fe3 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessageEventBubble.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessageEventBubble.kt @@ -38,7 +38,7 @@ import androidx.compose.ui.unit.dp import io.element.android.compound.theme.ElementTheme import io.element.android.features.messages.impl.timeline.model.TimelineItemGroupPosition import io.element.android.features.messages.impl.timeline.model.bubble.BubbleState -import io.element.android.features.messages.impl.timeline.model.bubble.BubbleStateProvider +import io.element.android.features.messages.impl.timeline.model.bubble.BubbleStatePreviewParam import io.element.android.libraries.core.extensions.to01 import io.element.android.libraries.designsystem.components.avatar.AvatarSize import io.element.android.libraries.designsystem.modifiers.onKeyboardContextMenuAction @@ -192,7 +192,7 @@ object MessageEventBubbleDefaults { @PreviewsDayNight @Composable -internal fun MessageEventBubblePreview(@PreviewParameter(BubbleStateProvider::class) state: BubbleState) = ElementPreview { +internal fun MessageEventBubblePreview(@PreviewParameter(BubbleStatePreviewParam::class) state: BubbleState) = ElementPreview { // Due to position offset, surround with a Box Box( modifier = Modifier diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessagesReactionButton.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessagesReactionButton.kt index dc8e171298..931e0de801 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessagesReactionButton.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/MessagesReactionButton.kt @@ -41,7 +41,7 @@ import io.element.android.features.messages.impl.R import io.element.android.features.messages.impl.timeline.a11y.a11yReactionAction import io.element.android.features.messages.impl.timeline.a11y.a11yReactionDetails import io.element.android.features.messages.impl.timeline.model.AggregatedReaction -import io.element.android.features.messages.impl.timeline.model.AggregatedReactionProvider +import io.element.android.features.messages.impl.timeline.model.AggregatedReactionPreviewParam import io.element.android.features.messages.impl.timeline.model.aTimelineItemReactions import io.element.android.libraries.designsystem.icons.CompoundDrawables import io.element.android.libraries.designsystem.modifiers.onKeyboardContextMenuAction @@ -199,7 +199,7 @@ private fun ReactionContent( @PreviewsDayNight @Composable -internal fun MessagesReactionButtonPreview(@PreviewParameter(AggregatedReactionProvider::class) reaction: AggregatedReaction) = ElementPreview { +internal fun MessagesReactionButtonPreview(@PreviewParameter(AggregatedReactionPreviewParam::class) reaction: AggregatedReaction) = ElementPreview { MessagesReactionButton( content = MessagesReactionsButtonContent.Reaction(reaction), onClick = {}, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineEventTimestampView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineEventTimestampView.kt index b6af359269..d7492ca40b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineEventTimestampView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineEventTimestampView.kt @@ -56,10 +56,11 @@ fun TimelineEventTimestampView( val isVerifiedUserSendFailure = event.localSendState is LocalEventSendState.Failed.VerifiedUser val onClickLabel = when { shield != null -> stringResource(CommonStrings.a11y_view_details) - hasError && isVerifiedUserSendFailure -> stringResource(CommonStrings.action_open_context_menu) + isVerifiedUserSendFailure -> stringResource(CommonStrings.action_open_context_menu) + hasError -> stringResource(CommonStrings.a11y_view_details) else -> null } - val clickableModifier = remember(shield, hasError) { + val clickableModifier = remember(event) { when { shield != null -> { Modifier.clickable( @@ -70,10 +71,9 @@ fun TimelineEventTimestampView( } hasError -> Modifier .clickable( - enabled = isVerifiedUserSendFailure, onClickLabel = onClickLabel, ) { - eventSink(TimelineEvent.ComputeVerifiedUserSendFailure(event)) + eventSink(TimelineEvent.ShowSendFailureDialog(event)) } else -> Modifier } @@ -134,7 +134,9 @@ fun TimelineEventTimestampView( @PreviewsDayNight @Composable -internal fun TimelineEventTimestampViewPreview(@PreviewParameter(TimelineItemEventForTimestampViewProvider::class) event: TimelineItem.Event) = ElementPreview { +internal fun TimelineEventTimestampViewPreview(@PreviewParameter( + TimelineItemEventForTimestampViewPreviewParam::class +) event: TimelineItem.Event) = ElementPreview { TimelineEventTimestampView( event = event, eventSink = {}, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventContentForGalleryViewProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventContentForGalleryViewPreviewParam.kt similarity index 98% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventContentForGalleryViewProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventContentForGalleryViewPreviewParam.kt index ed790da8a2..0f7da4209f 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventContentForGalleryViewProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventContentForGalleryViewPreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.features.messages.impl.timeline.model.event.aTimelineI import io.element.android.features.messages.impl.timeline.model.event.anAttachmentItem import kotlin.time.Duration -class TimelineItemEventContentForGalleryViewProvider : +class TimelineItemEventContentForGalleryViewPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventForTimestampViewProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventForTimestampViewPreviewParam.kt similarity index 95% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventForTimestampViewProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventForTimestampViewPreviewParam.kt index 3689c84875..118edae373 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventForTimestampViewProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventForTimestampViewPreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.features.messages.impl.timeline.model.event.aTimelineI import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState import io.element.android.libraries.matrix.api.timeline.item.event.MessageShield -class TimelineItemEventForTimestampViewProvider : PreviewParameterProvider { +class TimelineItemEventForTimestampViewPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemEvent(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRow.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRow.kt index fed2ab6577..b0be2dde88 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRow.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRow.kt @@ -125,6 +125,7 @@ import io.element.android.libraries.matrix.api.timeline.item.event.getAvatarUrl import io.element.android.libraries.matrix.api.timeline.item.event.getDisambiguatedDisplayName import io.element.android.libraries.matrix.api.timeline.item.event.getDisplayName import io.element.android.libraries.matrix.api.timeline.item.event.mediaSources +import io.element.android.libraries.matrix.api.timeline.item.event.toMatrixUser import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.ui.media.contentvalidation.collectOverallState import io.element.android.libraries.matrix.ui.media.contentvalidation.rememberEventContentValidationState @@ -207,11 +208,7 @@ fun TimelineItemEventRow( } fun onUserDataClick() { - val sender = MatrixUser( - userId = event.senderId, - displayName = event.senderProfile.getDisplayName(), - avatarUrl = event.senderProfile.getAvatarUrl(), - ) + val sender = event.senderProfile.toMatrixUser(event.senderId) onUserDataClick(sender) } @@ -804,15 +801,15 @@ private fun MessageEventBubbleContent( .padding(top = topPadding, start = 8.dp, end = 8.dp) .clip(shape) - val talkbackCompatModifier = if (isTalkbackActive()) { + val talkbackCompatModifier = when { // Use z-index to make the replied to text being read after the message // Usually, you'd use traversalIndex for that, but it's not working for some reason - inReplyToModifier.zIndex(1f) - } else { - inReplyToModifier.clickable(onClick = inReplyToClick) + isTalkbackActive() -> inReplyToModifier.zIndex(1f) + inReplyTo is InReplyToDetails.Error -> inReplyToModifier + else -> inReplyToModifier.clickable(onClick = inReplyToClick) } - val contentHasError = currentContentValidationState.hasError() + val contentHasError = currentContentValidationState.hasError() || inReplyTo is InReplyToDetails.Error val borderColor = if (contentHasError) ElementTheme.colors.borderCriticalSubtle else ElementTheme.colors.separatorPrimary val backgroundColor = if (contentHasError) ElementTheme.colors.bgCriticalSubtle else ElementTheme.colors.bgCanvasDefault Box( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowDisambiguatedPreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowDisambiguatedPreview.kt index 4b6223fd97..94d29d2191 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowDisambiguatedPreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowDisambiguatedPreview.kt @@ -13,12 +13,12 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetails -import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsDisambiguatedProvider +import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsDisambiguatedPreviewParam @PreviewsDayNight @Composable internal fun TimelineItemEventRowDisambiguatedPreview( - @PreviewParameter(InReplyToDetailsDisambiguatedProvider::class) inReplyToDetails: InReplyToDetails, + @PreviewParameter(InReplyToDetailsDisambiguatedPreviewParam::class) inReplyToDetails: InReplyToDetails, ) = ElementPreview { TimelineItemEventRowWithReplyContentToPreview( inReplyToDetails = inReplyToDetails, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowGalleryPreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowGalleryPreview.kt index 22c3f354f2..b942695470 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowGalleryPreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowGalleryPreview.kt @@ -19,7 +19,7 @@ import io.element.android.libraries.designsystem.preview.PreviewsDayNight @PreviewsDayNight @Composable internal fun TimelineItemEventRowWithGalleryPreview( - @PreviewParameter(TimelineItemEventContentForGalleryViewProvider::class) content: TimelineItemEventContent, + @PreviewParameter(TimelineItemEventContentForGalleryViewPreviewParam::class) content: TimelineItemEventContent, ) = ElementPreview { Column { sequenceOf(false, true).forEach { isMine -> diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowTimestampPreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowTimestampPreview.kt index c588b1d071..ae0077786b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowTimestampPreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowTimestampPreview.kt @@ -20,7 +20,7 @@ import io.element.android.libraries.designsystem.preview.PreviewsDayNight @PreviewsDayNight @Composable internal fun TimelineItemEventRowTimestampPreview( - @PreviewParameter(TimelineItemEventForTimestampViewProvider::class) event: TimelineItem.Event + @PreviewParameter(TimelineItemEventForTimestampViewPreviewParam::class) event: TimelineItem.Event ) = ElementPreview { Column { when (event.content) { diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithRRPreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithRRPreview.kt index 6ea1161605..379a5b3547 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithRRPreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithRRPreview.kt @@ -14,7 +14,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.features.messages.impl.timeline.aTimelineItemEvent import io.element.android.features.messages.impl.timeline.aTimelineItemReactions import io.element.android.features.messages.impl.timeline.components.receipt.ReadReceiptViewState -import io.element.android.features.messages.impl.timeline.components.receipt.ReadReceiptViewStateForTimelineItemEventRowProvider +import io.element.android.features.messages.impl.timeline.components.receipt.ReadReceiptViewStateForTimelineItemEventRowPreviewParam import io.element.android.features.messages.impl.timeline.model.TimelineItemReadReceipts import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemTextContent import io.element.android.libraries.designsystem.preview.ElementPreview @@ -25,7 +25,7 @@ import io.element.android.libraries.designsystem.preview.PreviewsDayNight @PreviewsDayNight @Composable internal fun TimelineItemEventRowWithRRPreview( - @PreviewParameter(ReadReceiptViewStateForTimelineItemEventRowProvider::class) state: ReadReceiptViewState, + @PreviewParameter(ReadReceiptViewStateForTimelineItemEventRowPreviewParam::class) state: ReadReceiptViewState, ) = ElementPreview { Column { // A message from someone else diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyInformativePreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyInformativePreview.kt index cdc60a9e7e..374561e553 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyInformativePreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyInformativePreview.kt @@ -13,12 +13,12 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetails -import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsInformativeProvider +import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsInformativePreviewParam @PreviewsDayNight @Composable internal fun TimelineItemEventRowWithReplyInformativePreview( - @PreviewParameter(InReplyToDetailsInformativeProvider::class) inReplyToDetails: InReplyToDetails, + @PreviewParameter(InReplyToDetailsInformativePreviewParam::class) inReplyToDetails: InReplyToDetails, ) = ElementPreview { TimelineItemEventRowWithReplyContentToPreview(inReplyToDetails) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyOtherPreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyOtherPreview.kt index 3071fe114a..f7d2de2ced 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyOtherPreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyOtherPreview.kt @@ -13,12 +13,12 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetails -import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsOtherProvider +import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsOtherPreviewParam @PreviewsDayNight @Composable internal fun TimelineItemEventRowWithReplyOtherPreview( - @PreviewParameter(InReplyToDetailsOtherProvider::class) inReplyToDetails: InReplyToDetails, + @PreviewParameter(InReplyToDetailsOtherPreviewParam::class) inReplyToDetails: InReplyToDetails, ) = ElementPreview { TimelineItemEventRowWithReplyContentToPreview(inReplyToDetails) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyPreview.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyPreview.kt index 7ddcadfe3c..aba6971f1d 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyPreview.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowWithReplyPreview.kt @@ -21,12 +21,12 @@ import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.matrix.api.core.ThreadId import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetails -import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsProvider +import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsPreviewParam @PreviewsDayNight @Composable internal fun TimelineItemEventRowWithReplyPreview( - @PreviewParameter(InReplyToDetailsProvider::class) inReplyToDetails: InReplyToDetails, + @PreviewParameter(InReplyToDetailsPreviewParam::class) inReplyToDetails: InReplyToDetails, ) = ElementPreview { TimelineItemEventRowWithReplyContentToPreview(inReplyToDetails) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/customreaction/CustomReactionBottomSheet.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/customreaction/CustomReactionBottomSheet.kt index c90a0e5acc..a14d3b3893 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/customreaction/CustomReactionBottomSheet.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/customreaction/CustomReactionBottomSheet.kt @@ -8,11 +8,16 @@ package io.element.android.features.messages.impl.timeline.components.customreaction +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.isImeVisible import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.SheetState import androidx.compose.material3.SheetValue import androidx.compose.material3.rememberBottomSheetState import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import io.element.android.emojibasebindings.Emoji @@ -54,6 +59,7 @@ fun CustomReactionBottomSheet( modifier = modifier, scrollable = false, ) { + ExpandSheetWhenImeIsVisible(sheetState) emojiPickerRenderer.Render( state = state.target.emojiPickerState, onSelectEmoji = ::onEmojiSelectedDismiss, @@ -67,3 +73,14 @@ fun CustomReactionBottomSheet( } } } + +@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class) +@Composable +internal fun ExpandSheetWhenImeIsVisible(sheetState: SheetState) { + val isImeVisible = WindowInsets.isImeVisible + LaunchedEffect(isImeVisible) { + if (isImeVisible) { + sheetState.expand() + } + } +} diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsContentPreviewParam.kt similarity index 96% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsContentPreviewParam.kt index c63d68e062..a42eec8504 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsContentPreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.features.messages.impl.timeline.model.event.aTimelineI import io.element.android.features.messages.impl.timeline.model.event.anAttachmentItem import io.element.android.libraries.matrix.api.media.MediaSource -class TimelineItemAttachmentsContentProvider : PreviewParameterProvider { +class TimelineItemAttachmentsContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemAttachmentsContent( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsListView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsListView.kt index f3745b2c5a..232c107698 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsListView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAttachmentsListView.kt @@ -265,7 +265,7 @@ private fun AttachmentListItem( @PreviewsDayNight @Composable internal fun TimelineItemAttachmentsListViewPreview( - @PreviewParameter(TimelineItemAttachmentsContentProvider::class) content: TimelineItemAttachmentsContent + @PreviewParameter(TimelineItemAttachmentsContentPreviewParam::class) content: TimelineItemAttachmentsContent ) = ElementPreview { TimelineItemAttachmentsListView( eventId = EventId("\$eventId"), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAudioView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAudioView.kt index 221ba2ca6f..d47ca552b8 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAudioView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemAudioView.kt @@ -14,7 +14,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.messages.impl.timeline.components.layout.ContentAvoidingLayoutData import io.element.android.features.messages.impl.timeline.model.event.TimelineItemAudioContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemAudioContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemAudioContentPreviewParam import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.matrix.ui.media.contentvalidation.ContentValidationValue @@ -38,7 +38,7 @@ fun TimelineItemAudioView( @PreviewsDayNight @Composable -internal fun TimelineItemAudioViewPreview(@PreviewParameter(TimelineItemAudioContentProvider::class) content: TimelineItemAudioContent) = +internal fun TimelineItemAudioViewPreview(@PreviewParameter(TimelineItemAudioContentPreviewParam::class) content: TimelineItemAudioContent) = ElementTimelineItemPreview { TimelineItemAudioView( content, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemEncryptedView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemEncryptedView.kt index 48b3acfbb8..6b9022d3cf 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemEncryptedView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemEncryptedView.kt @@ -14,7 +14,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.features.messages.impl.timeline.components.layout.ContentAvoidingLayoutData import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEncryptedContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEncryptedContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEncryptedContentPreviewParam import io.element.android.libraries.designsystem.icons.CompoundDrawables import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight @@ -75,7 +75,7 @@ fun TimelineItemEncryptedView( @PreviewsDayNight @Composable internal fun TimelineItemEncryptedViewPreview( - @PreviewParameter(TimelineItemEncryptedContentProvider::class) content: TimelineItemEncryptedContent + @PreviewParameter(TimelineItemEncryptedContentPreviewParam::class) content: TimelineItemEncryptedContent ) = ElementPreview { TimelineItemEncryptedView( content = content, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemFileView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemFileView.kt index cd0632282e..77df9ba923 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemFileView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemFileView.kt @@ -15,7 +15,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.messages.impl.timeline.components.layout.ContentAvoidingLayoutData import io.element.android.features.messages.impl.timeline.model.event.TimelineItemFileContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemFileContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemFileContentPreviewParam import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.matrix.ui.media.contentvalidation.ContentValidationValue import io.element.android.libraries.ui.strings.CommonStrings @@ -43,7 +43,7 @@ fun TimelineItemFileView( @PreviewsDayNight @Composable -internal fun TimelineItemFileViewPreview(@PreviewParameter(TimelineItemFileContentProvider::class) content: TimelineItemFileContent) { +internal fun TimelineItemFileViewPreview(@PreviewParameter(TimelineItemFileContentPreviewParam::class) content: TimelineItemFileContent) { ElementTimelineItemPreview { TimelineItemFileView( content, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryContentPreviewParam.kt similarity index 97% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryContentPreviewParam.kt index 9d88d8c0fb..9fb34afaea 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryContentPreviewParam.kt @@ -15,7 +15,7 @@ import kotlinx.collections.immutable.toImmutableList import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds -class TimelineItemGalleryContentProvider : PreviewParameterProvider { +class TimelineItemGalleryContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemGalleryContent( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryView.kt index 3212d789f9..e433f6ef8e 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemGalleryView.kt @@ -390,7 +390,7 @@ private fun RemainingCountOverlay(count: Int) { @PreviewsDayNight @Composable internal fun TimelineItemGalleryViewPreview( - @PreviewParameter(TimelineItemGalleryContentProvider::class) content: TimelineItemGalleryContent, + @PreviewParameter(TimelineItemGalleryContentPreviewParam::class) content: TimelineItemGalleryContent, ) = ElementPreview { TimelineItemGalleryView( eventId = null, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemImageView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemImageView.kt index 3e79fd6fd9..ce12690534 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemImageView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemImageView.kt @@ -33,7 +33,7 @@ import io.element.android.features.messages.impl.timeline.aTimelineItemEvent import io.element.android.features.messages.impl.timeline.components.ATimelineItemEventRow import io.element.android.features.messages.impl.timeline.model.TimelineItemGroupPosition import io.element.android.features.messages.impl.timeline.model.event.TimelineItemImageContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemImageContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemImageContentPreviewParam import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemImageContent import io.element.android.features.messages.impl.timeline.protection.ProtectedView import io.element.android.features.messages.impl.timeline.protection.coerceRatioWhenHidingContent @@ -125,7 +125,7 @@ fun TimelineItemImageView( @PreviewsDayNight @Composable -internal fun TimelineItemImageViewPreview(@PreviewParameter(TimelineItemImageContentProvider::class) content: TimelineItemImageContent) = ElementPreview { +internal fun TimelineItemImageViewPreview(@PreviewParameter(TimelineItemImageContentPreviewParam::class) content: TimelineItemImageContent) = ElementPreview { TimelineItemImageView( content = content, hideMediaContent = false, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemLocationView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemLocationView.kt index 4ab4ee84a6..3ff8a62455 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemLocationView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemLocationView.kt @@ -28,9 +28,10 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp import io.element.android.compound.theme.ElementTheme import io.element.android.compound.tokens.generated.CompoundIcons +import io.element.android.features.location.api.LocalMapTilerConfig import io.element.android.features.location.api.StaticMapView import io.element.android.features.messages.impl.timeline.model.event.TimelineItemLocationContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemLocationContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemLocationContentPreviewParam import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.designsystem.theme.components.CircularProgressIndicator @@ -50,6 +51,7 @@ fun TimelineItemLocationView( modifier = Modifier .fillMaxWidth() .heightIn(max = 188.dp), + mapTilerConfig = LocalMapTilerConfig.current, pinVariant = content.pinVariant, location = content.location, zoom = 15.0, @@ -160,7 +162,7 @@ private fun LiveLocationOverlay( @PreviewsDayNight @Composable -internal fun TimelineItemLocationViewPreview(@PreviewParameter(TimelineItemLocationContentProvider::class) content: TimelineItemLocationContent) = +internal fun TimelineItemLocationViewPreview(@PreviewParameter(TimelineItemLocationContentPreviewParam::class) content: TimelineItemLocationContent) = ElementPreview { TimelineItemLocationView( content = content, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemPollView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemPollView.kt index 6b8886c592..041f3ad5a5 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemPollView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemPollView.kt @@ -13,7 +13,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.features.messages.impl.timeline.TimelineEvent import io.element.android.features.messages.impl.timeline.model.event.TimelineItemPollContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemPollContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemPollContentPreviewParam import io.element.android.features.poll.api.pollcontent.PollContentView import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight @@ -57,7 +57,7 @@ fun TimelineItemPollView( @PreviewsDayNight @Composable -internal fun TimelineItemPollViewPreview(@PreviewParameter(TimelineItemPollContentProvider::class) content: TimelineItemPollContent) = +internal fun TimelineItemPollViewPreview(@PreviewParameter(TimelineItemPollContentPreviewParam::class) content: TimelineItemPollContent) = ElementPreview { TimelineItemPollView( content = content, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemStickerView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemStickerView.kt index 7e240f8b51..c7878c00f5 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemStickerView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemStickerView.kt @@ -28,7 +28,7 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.tooling.preview.PreviewParameter import coil3.compose.AsyncImage import io.element.android.features.messages.impl.timeline.model.event.TimelineItemStickerContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemStickerContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemStickerContentPreviewParam import io.element.android.features.messages.impl.timeline.protection.ProtectedView import io.element.android.features.messages.impl.timeline.protection.coerceRatioWhenHidingContent import io.element.android.features.messages.impl.timeline.util.handleAsyncImageStateChange @@ -123,7 +123,9 @@ fun TimelineItemStickerView( @PreviewsDayNight @Composable -internal fun TimelineItemStickerViewPreview(@PreviewParameter(TimelineItemStickerContentProvider::class) content: TimelineItemStickerContent) = ElementPreview { +internal fun TimelineItemStickerViewPreview(@PreviewParameter( + TimelineItemStickerContentPreviewParam::class +) content: TimelineItemStickerContent) = ElementPreview { TimelineItemStickerView( content = content, hideMediaContent = false, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemTextView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemTextView.kt index 1a4be5d2e5..a7d54e819b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemTextView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemTextView.kt @@ -24,7 +24,7 @@ import io.element.android.compound.theme.ElementTheme import io.element.android.features.messages.impl.timeline.components.layout.ContentAvoidingLayout import io.element.android.features.messages.impl.timeline.components.layout.ContentAvoidingLayoutData import io.element.android.features.messages.impl.timeline.model.event.TimelineItemTextBasedContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemTextBasedContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemTextBasedContentPreviewParam import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemTextContent import io.element.android.features.messages.impl.utils.containsOnlyEmojis import io.element.android.libraries.androidutils.text.LinkifyHelper @@ -82,7 +82,7 @@ internal fun getTextWithResolvedMentions(content: TimelineItemTextBasedContent): @PreviewsDayNight @Composable internal fun TimelineItemTextViewPreview( - @PreviewParameter(TimelineItemTextBasedContentProvider::class) content: TimelineItemTextBasedContent + @PreviewParameter(TimelineItemTextBasedContentPreviewParam::class) content: TimelineItemTextBasedContent ) = ElementPreview { TimelineItemTextView( content = content, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVideoView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVideoView.kt index b47220fa5e..5b3803713e 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVideoView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVideoView.kt @@ -37,7 +37,7 @@ import androidx.compose.ui.unit.dp import coil3.compose.AsyncImage import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVideoContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVideoContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVideoContentPreviewParam import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemVideoContent import io.element.android.features.messages.impl.timeline.protection.ProtectedView import io.element.android.features.messages.impl.timeline.protection.coerceRatioWhenHidingContent @@ -150,7 +150,7 @@ fun TimelineItemVideoView( @PreviewsDayNight @Composable -internal fun TimelineItemVideoViewPreview(@PreviewParameter(TimelineItemVideoContentProvider::class) content: TimelineItemVideoContent) = ElementPreview { +internal fun TimelineItemVideoViewPreview(@PreviewParameter(TimelineItemVideoContentPreviewParam::class) content: TimelineItemVideoContent) = ElementPreview { TimelineItemVideoView( content = content, hideMediaContent = false, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVoiceView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVoiceView.kt index 15387f51c0..a05ac78f84 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVoiceView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemVoiceView.kt @@ -42,7 +42,7 @@ import io.element.android.compound.theme.ElementTheme import io.element.android.compound.tokens.generated.CompoundIcons import io.element.android.features.messages.impl.timeline.components.layout.ContentAvoidingLayoutData import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVoiceContent -import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVoiceContentProvider +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVoiceContentPreviewParam import io.element.android.libraries.designsystem.atomic.atoms.PlaybackSpeedButton import io.element.android.libraries.designsystem.components.media.WaveformPlaybackView import io.element.android.libraries.designsystem.preview.ElementPreview @@ -56,7 +56,7 @@ import io.element.android.libraries.ui.strings.CommonStrings import io.element.android.libraries.ui.utils.a11y.isTalkbackActive import io.element.android.libraries.voiceplayer.api.VoiceMessageEvent import io.element.android.libraries.voiceplayer.api.VoiceMessageState -import io.element.android.libraries.voiceplayer.api.VoiceMessageStateProvider +import io.element.android.libraries.voiceplayer.api.VoiceMessageStatePreviewParam import kotlinx.coroutines.delay @Composable @@ -261,9 +261,9 @@ private fun CustomIconButton( ) } -open class TimelineItemVoiceViewParametersProvider : PreviewParameterProvider { - private val voiceMessageStateProvider = VoiceMessageStateProvider() - private val timelineItemVoiceContentProvider = TimelineItemVoiceContentProvider() +open class TimelineItemVoiceViewParametersPreviewParam : PreviewParameterProvider { + private val voiceMessageStateProvider = VoiceMessageStatePreviewParam() + private val timelineItemVoiceContentProvider = TimelineItemVoiceContentPreviewParam() override val values: Sequence get() = timelineItemVoiceContentProvider.values.flatMap { content -> voiceMessageStateProvider.values.map { state -> @@ -283,7 +283,7 @@ data class TimelineItemVoiceViewParameters( @PreviewsDayNight @Composable internal fun TimelineItemVoiceViewPreview( - @PreviewParameter(TimelineItemVoiceViewParametersProvider::class) timelineItemVoiceViewParameters: TimelineItemVoiceViewParameters, + @PreviewParameter(TimelineItemVoiceViewParametersPreviewParam::class) timelineItemVoiceViewParameters: TimelineItemVoiceViewParameters, ) = ElementPreview { TimelineItemVoiceView( state = timelineItemVoiceViewParameters.state, @@ -296,7 +296,7 @@ internal fun TimelineItemVoiceViewPreview( @PreviewsDayNight @Composable internal fun TimelineItemVoiceViewUnifiedPreview() = ElementPreview { - val timelineItemVoiceViewParametersProvider = TimelineItemVoiceViewParametersProvider() + val timelineItemVoiceViewParametersProvider = TimelineItemVoiceViewParametersPreviewParam() Column { timelineItemVoiceViewParametersProvider.values.forEach { TimelineItemVoiceView( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryStatePreviewParam.kt similarity index 91% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryStatePreviewParam.kt index 82974c8908..a617394723 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.messages.impl.timeline.aTimelineItemReactions import io.element.android.libraries.matrix.api.core.EventId -open class ReactionSummaryStateProvider : PreviewParameterProvider { +open class ReactionSummaryStatePreviewParam : PreviewParameterProvider { override val values = sequenceOf(aReactionSummaryState()) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryView.kt index 2a902fd692..5b6c7fda37 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/reactionsummary/ReactionSummaryView.kt @@ -293,7 +293,7 @@ private fun SenderRow( @PreviewsDayNight @Composable internal fun ReactionSummaryViewContentPreview( - @PreviewParameter(ReactionSummaryStateProvider::class) state: ReactionSummaryState + @PreviewParameter(ReactionSummaryStatePreviewParam::class) state: ReactionSummaryState ) = ElementPreview { ReactionSummaryViewContent(summary = state.target as ReactionSummaryState.Summary) } diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateForTimelineItemEventRowProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateForTimelineItemEventRowPreviewParam.kt similarity index 95% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateForTimelineItemEventRowProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateForTimelineItemEventRowPreviewParam.kt index c5140c4c03..a3556a9b03 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateForTimelineItemEventRowProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateForTimelineItemEventRowPreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.features.messages.impl.timeline.model.ReadReceiptData import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState -class ReadReceiptViewStateForTimelineItemEventRowProvider : +class ReadReceiptViewStateForTimelineItemEventRowPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStatePreviewParam.kt similarity index 96% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStatePreviewParam.kt index 64a7cf34ff..751a88cb39 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/ReadReceiptViewStatePreviewParam.kt @@ -17,7 +17,7 @@ import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState import kotlinx.collections.immutable.toImmutableList -class ReadReceiptViewStateProvider : PreviewParameterProvider { +class ReadReceiptViewStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aReadReceiptViewState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/TimelineItemReadReceiptView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/TimelineItemReadReceiptView.kt index c9b712eba7..17a9b0c5eb 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/TimelineItemReadReceiptView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/TimelineItemReadReceiptView.kt @@ -202,7 +202,7 @@ private fun computeReceiptDescription(receipts: ImmutableList): @PreviewsDayNight @Composable internal fun TimelineItemReadReceiptViewPreview( - @PreviewParameter(ReadReceiptViewStateProvider::class) state: ReadReceiptViewState, + @PreviewParameter(ReadReceiptViewStatePreviewParam::class) state: ReadReceiptViewState, ) = ElementPreview { TimelineItemReadReceiptView( state = state, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheet.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheet.kt index 407cd29026..ad30a3765e 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheet.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheet.kt @@ -117,7 +117,7 @@ private fun ReadReceiptBottomSheetContent( @PreviewsDayNight @Composable -internal fun ReadReceiptBottomSheetPreview(@PreviewParameter(ReadReceiptBottomSheetStateProvider::class) state: ReadReceiptBottomSheetState) { +internal fun ReadReceiptBottomSheetPreview(@PreviewParameter(ReadReceiptBottomSheetStatePreviewParam::class) state: ReadReceiptBottomSheetState) { ElementPreview(fillMaxSize = true) { ReadReceiptBottomSheet( state = state, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheetStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheetStatePreviewParam.kt similarity index 87% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheetStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheetStatePreviewParam.kt index ff297a4f8d..86c2beb707 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheetStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/receipt/bottomsheet/ReadReceiptBottomSheetStatePreviewParam.kt @@ -10,14 +10,14 @@ package io.element.android.features.messages.impl.timeline.components.receipt.bo import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.messages.impl.timeline.aTimelineItemEvent -import io.element.android.features.messages.impl.timeline.components.receipt.ReadReceiptViewStateProvider +import io.element.android.features.messages.impl.timeline.components.receipt.ReadReceiptViewStatePreviewParam import io.element.android.features.messages.impl.timeline.model.TimelineItemReadReceipts import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState import kotlinx.collections.immutable.toImmutableList -class ReadReceiptBottomSheetStateProvider : PreviewParameterProvider { - // Reuse the provider ReadReceiptViewStateProvider - private val readReceiptViewStateProvider = ReadReceiptViewStateProvider() +class ReadReceiptBottomSheetStatePreviewParam : PreviewParameterProvider { + // Reuse the provider ReadReceiptViewStatePreviewParam + private val readReceiptViewStateProvider = ReadReceiptViewStatePreviewParam() override val values: Sequence = readReceiptViewStateProvider.values .filter { it.sendState is LocalEventSendState.Sent } .map { readReceiptViewState -> diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/virtual/TimelineItemDaySeparatorView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/virtual/TimelineItemDaySeparatorView.kt index 30befea07d..f2a62aa4a4 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/virtual/TimelineItemDaySeparatorView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/virtual/TimelineItemDaySeparatorView.kt @@ -21,7 +21,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp import io.element.android.compound.theme.ElementTheme import io.element.android.features.messages.impl.timeline.model.virtual.TimelineItemDaySeparatorModel -import io.element.android.features.messages.impl.timeline.model.virtual.TimelineItemDaySeparatorModelProvider +import io.element.android.features.messages.impl.timeline.model.virtual.TimelineItemDaySeparatorModelPreviewParam import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.designsystem.theme.components.Text @@ -53,7 +53,7 @@ internal fun TimelineItemDaySeparatorView( @PreviewsDayNight @Composable internal fun TimelineItemDaySeparatorViewPreview( - @PreviewParameter(TimelineItemDaySeparatorModelProvider::class) model: TimelineItemDaySeparatorModel + @PreviewParameter(TimelineItemDaySeparatorModelPreviewParam::class) model: TimelineItemDaySeparatorModel ) = ElementPreview { TimelineItemDaySeparatorView( model = model, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/di/TimelineItemPresenterFactories.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/di/TimelineItemPresenterFactories.kt index 1063157bef..2234593c4b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/di/TimelineItemPresenterFactories.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/di/TimelineItemPresenterFactories.kt @@ -10,28 +10,13 @@ package io.element.android.features.messages.impl.timeline.di import androidx.compose.runtime.Composable import androidx.compose.runtime.remember -import dev.zacsweers.metro.BindingContainer -import dev.zacsweers.metro.ContributesTo import dev.zacsweers.metro.Inject -import dev.zacsweers.metro.Multibinds import dev.zacsweers.metro.SingleIn import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEventContent import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.di.RoomScope import kotlin.reflect.KClass -/** - * Container that declares the [TimelineItemPresenterFactory] map multi binding. - * - * Its sole purpose is to support the case of an empty map multibinding. - */ -@BindingContainer -@ContributesTo(RoomScope::class) -interface TimelineItemPresenterFactoriesModule { - @Multibinds - fun multiBindTimelineItemPresenterFactories(): @JvmSuppressWildcards Map, TimelineItemPresenterFactory<*, *>> -} - /** * Room level caching layer for the [TimelineItemPresenterFactory] instances. * diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/di/TimelineItemPresenterFactoriesBindingContainer.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/di/TimelineItemPresenterFactoriesBindingContainer.kt new file mode 100644 index 0000000000..65dcd6dee0 --- /dev/null +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/di/TimelineItemPresenterFactoriesBindingContainer.kt @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.timeline.di + +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Multibinds +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemEventContent +import io.element.android.libraries.di.RoomScope +import kotlin.reflect.KClass + +/** + * Container that declares the [TimelineItemPresenterFactory] map multi binding. + * + * Its sole purpose is to support the case of an empty map multibinding. + */ +@BindingContainer +@ContributesTo(RoomScope::class) +interface TimelineItemPresenterFactoriesBindingContainer { + @Multibinds + fun multiBindTimelineItemPresenterFactories(): @JvmSuppressWildcards Map, TimelineItemPresenterFactory<*, *>> +} diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/TimelineItemsFactory.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/TimelineItemsFactory.kt index 1679a6030a..9bf7aa3c32 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/TimelineItemsFactory.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/TimelineItemsFactory.kt @@ -21,6 +21,9 @@ import io.element.android.libraries.androidutils.diff.MutableListDiffCache import io.element.android.libraries.core.coroutine.CoroutineDispatchers import io.element.android.libraries.matrix.api.room.RoomMember import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem +import io.element.android.libraries.matrix.api.timeline.item.event.EventTimelineItem +import io.element.android.libraries.matrix.api.timeline.item.event.MessageContent +import io.element.android.libraries.matrix.api.timeline.item.event.OtherMessageType import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.flow.Flow @@ -110,7 +113,11 @@ class TimelineItemsFactory( ): TimelineItem? { val timelineItem = when (val currentTimelineItem = timelineItems[index]) { - is MatrixTimelineItem.Event -> eventItemFactory.create(currentTimelineItem, index, timelineItems, roomMembers, renderReadReceipts) + is MatrixTimelineItem.Event -> if (currentTimelineItem.event.isKeyVerificationRequest()) { + null + } else { + eventItemFactory.create(currentTimelineItem, index, timelineItems, roomMembers, renderReadReceipts) + } is MatrixTimelineItem.Virtual -> virtualItemFactory.create(currentTimelineItem) MatrixTimelineItem.Other -> null } @@ -118,3 +125,8 @@ class TimelineItemsFactory( return timelineItem } } + +private fun EventTimelineItem.isKeyVerificationRequest(): Boolean { + val messageType = (content as? MessageContent)?.type + return messageType is OtherMessageType && messageType.isKeyVerificationRequest +} diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/event/TimelineItemEventFactory.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/event/TimelineItemEventFactory.kt index f29f23e903..af3e18e3cc 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/event/TimelineItemEventFactory.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/factories/event/TimelineItemEventFactory.kt @@ -38,6 +38,8 @@ import io.element.android.libraries.matrix.ui.messages.reply.map import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList +private const val GROUPING_TIMEOUT_MS = 5 * 60 * 1000L + @AssistedInject class TimelineItemEventFactory( @Assisted private val config: TimelineItemsFactoryConfig, @@ -221,8 +223,14 @@ class TimelineItemEventFactory( val previousSender = prevTimelineItem?.event?.sender val nextSender = nextTimelineItem?.event?.sender - val previousIsGroupable = prevTimelineItem?.canBeDisplayedInBubbleBlock().orTrue() - val nextIsGroupable = nextTimelineItem?.canBeDisplayedInBubbleBlock().orTrue() + val previousIsGroupable = prevTimelineItem?.let { + it.canBeDisplayedInBubbleBlock() && + currentTimelineItem.event.timestamp - it.event.timestamp <= GROUPING_TIMEOUT_MS + }.orTrue() + val nextIsGroupable = nextTimelineItem?.let { + it.canBeDisplayedInBubbleBlock() && + it.event.timestamp - currentTimelineItem.event.timestamp <= GROUPING_TIMEOUT_MS + }.orTrue() return when { previousSender != currentSender && nextSender == currentSender -> { diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStatePreviewParam.kt similarity index 93% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStatePreviewParam.kt index 0a6fb70cc5..c28e9c4d92 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.features.messages.impl.timeline.FocusRequestState import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.room.errors.FocusEventException -open class FocusRequestStateProvider : PreviewParameterProvider { +open class FocusRequestStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( FocusRequestState.Loading( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStateView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStateView.kt index 3dff7ac4f7..2bda2fe4bf 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStateView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/focus/FocusRequestStateView.kt @@ -55,7 +55,7 @@ fun FocusRequestStateView( @PreviewsDayNight @Composable internal fun FocusRequestStateViewPreview( - @PreviewParameter(FocusRequestStateProvider::class) state: FocusRequestState, + @PreviewParameter(FocusRequestStatePreviewParam::class) state: FocusRequestState, ) = ElementPreview { FocusRequestStateView( focusRequestState = state, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/AggregatedReactionProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/AggregatedReactionPreviewParam.kt similarity index 95% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/AggregatedReactionProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/AggregatedReactionPreviewParam.kt index e5eb52c91e..f7ede5ebd7 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/AggregatedReactionProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/AggregatedReactionPreviewParam.kt @@ -15,7 +15,7 @@ import java.text.DateFormat import java.util.Date import java.util.TimeZone -open class AggregatedReactionProvider : PreviewParameterProvider { +open class AggregatedReactionPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf(false, true).flatMap { sequenceOf( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/TimelineItemReactionsProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/TimelineItemReactionsProvider.kt index 3190e61a75..35d4f21dda 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/TimelineItemReactionsProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/TimelineItemReactionsProvider.kt @@ -11,6 +11,6 @@ package io.element.android.features.messages.impl.timeline.model import kotlinx.collections.immutable.toImmutableList fun aTimelineItemReactions() = TimelineItemReactions( - // Use values from AggregatedReactionProvider - reactions = AggregatedReactionProvider().values.toImmutableList() + // Use values from AggregatedReactionPreviewParam + reactions = AggregatedReactionPreviewParam().values.toImmutableList() ) diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/bubble/BubbleStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/bubble/BubbleStatePreviewParam.kt similarity index 94% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/bubble/BubbleStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/bubble/BubbleStatePreviewParam.kt index cdd24ed264..4a7a9f8187 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/bubble/BubbleStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/bubble/BubbleStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.features.messages.impl.timeline.TimelineRoomInfo import io.element.android.features.messages.impl.timeline.aTimelineRoomInfo import io.element.android.features.messages.impl.timeline.model.TimelineItemGroupPosition -open class BubbleStateProvider : PreviewParameterProvider { +open class BubbleStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( TimelineItemGroupPosition.First, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemAudioContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemAudioContentPreviewParam.kt similarity index 92% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemAudioContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemAudioContentPreviewParam.kt index 3b60a48c78..600288012b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemAudioContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemAudioContentPreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.core.mimetype.MimeTypes import io.element.android.libraries.matrix.api.media.MediaSource import kotlin.time.Duration.Companion.milliseconds -open class TimelineItemAudioContentProvider : PreviewParameterProvider { +open class TimelineItemAudioContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemAudioContent("A sound.mp3"), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEncryptedContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEncryptedContentPreviewParam.kt similarity index 96% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEncryptedContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEncryptedContentPreviewParam.kt index bb53da3b7b..a85553360a 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEncryptedContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEncryptedContentPreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.matrix.api.timeline.item.event.UnableToDecryptContent import io.element.android.libraries.matrix.api.timeline.item.event.UtdCause -open class TimelineItemEncryptedContentProvider : PreviewParameterProvider { +open class TimelineItemEncryptedContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemEncryptedContent(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContent.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContent.kt index c60e3847da..01146a070b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContent.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContent.kt @@ -58,10 +58,12 @@ fun TimelineItemEventContent.canBeForwarded(): Boolean = is TimelineItemFileContent, is TimelineItemAudioContent, is TimelineItemVideoContent, - is TimelineItemLocationContent, is TimelineItemVoiceContent, is TimelineItemGalleryContent, is TimelineItemAttachmentsContent -> true + // Live location shares can't be forwarded, the SDK rejects them, so we only show the option for static locations + // See https://github.com/element-hq/element-x-android/issues/7190 + is TimelineItemLocationContent -> mode is TimelineItemLocationContent.Mode.Static // Stickers can't be forwarded (yet) so we don't show the option // See https://github.com/element-hq/element-x-android/issues/2161 is TimelineItemStickerContent -> false diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContentPreviewParam.kt similarity index 96% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContentPreviewParam.kt index 1d4c7c04ec..0dd91fccfe 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContentPreviewParam.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.matrix.api.timeline.item.event.UnableToDecry import kotlinx.collections.immutable.toImmutableList import org.jsoup.nodes.Document -class TimelineItemEventContentProvider : PreviewParameterProvider { +class TimelineItemEventContentPreviewParam : PreviewParameterProvider { override val values = sequenceOf( aTimelineItemEmoteContent(), aTimelineItemEncryptedContent(), @@ -45,7 +45,7 @@ class TimelineItemEventContentProvider : PreviewParameterProvider { +class TimelineItemTextBasedContentPreviewParam : PreviewParameterProvider { private fun buildSpanned(text: String) = buildSpannedString { inSpans(StyleSpan(Typeface.BOLD)) { append("Rich Text") diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemFileContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemFileContentPreviewParam.kt similarity index 92% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemFileContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemFileContentPreviewParam.kt index e2021e9646..277f461edc 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemFileContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemFileContentPreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.core.mimetype.MimeTypes import io.element.android.libraries.matrix.api.media.MediaSource -open class TimelineItemFileContentProvider : PreviewParameterProvider { +open class TimelineItemFileContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemFileContent(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemImageContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemImageContentPreviewParam.kt similarity index 93% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemImageContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemImageContentPreviewParam.kt index 6d3b114428..cd93c7c006 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemImageContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemImageContentPreviewParam.kt @@ -13,7 +13,7 @@ import androidx.media3.common.MimeTypes import io.element.android.libraries.matrix.api.media.MediaSource import io.element.android.libraries.matrix.ui.components.A_BLUR_HASH -open class TimelineItemImageContentProvider : PreviewParameterProvider { +open class TimelineItemImageContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemImageContent(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemLocationContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemLocationContentPreviewParam.kt similarity index 95% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemLocationContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemLocationContentPreviewParam.kt index 6c095c828e..e4f2691f27 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemLocationContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemLocationContentPreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.timeline.item.event.ProfileDetails import io.element.android.libraries.matrix.ui.messages.reply.aProfileDetailsReady -open class TimelineItemLocationContentProvider : PreviewParameterProvider { +open class TimelineItemLocationContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemLocationContent( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemPollContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemPollContentPreviewParam.kt similarity index 94% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemPollContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemPollContentPreviewParam.kt index 040a3cd7fe..7c74f7f7f1 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemPollContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemPollContentPreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.features.poll.api.pollcontent.aPollQuestion import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.poll.PollKind -open class TimelineItemPollContentProvider : PreviewParameterProvider { +open class TimelineItemPollContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemPollContent(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemStickerContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemStickerContentPreviewParam.kt similarity index 92% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemStickerContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemStickerContentPreviewParam.kt index eb564cd803..def748d97b 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemStickerContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemStickerContentPreviewParam.kt @@ -13,7 +13,7 @@ import androidx.media3.common.MimeTypes import io.element.android.libraries.matrix.api.media.MediaSource import io.element.android.libraries.matrix.ui.components.A_BLUR_HASH -open class TimelineItemStickerContentProvider : PreviewParameterProvider { +open class TimelineItemStickerContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemStickerContent(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVideoContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVideoContentPreviewParam.kt similarity index 94% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVideoContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVideoContentPreviewParam.kt index 627dbf3dd7..46de9ea89a 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVideoContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVideoContentPreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.matrix.api.media.MediaSource import io.element.android.libraries.matrix.ui.components.A_BLUR_HASH import kotlin.time.Duration.Companion.milliseconds -open class TimelineItemVideoContentProvider : PreviewParameterProvider { +open class TimelineItemVideoContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemVideoContent(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVoiceContentProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVoiceContentPreviewParam.kt similarity index 95% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVoiceContentProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVoiceContentPreviewParam.kt index d596963ebc..9b9a044791 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVoiceContentProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemVoiceContentPreviewParam.kt @@ -17,7 +17,7 @@ import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes -open class TimelineItemVoiceContentProvider : PreviewParameterProvider { +open class TimelineItemVoiceContentPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTimelineItemVoiceContent( diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/virtual/TimelineItemDaySeparatorModelProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/virtual/TimelineItemDaySeparatorModelPreviewParam.kt similarity index 85% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/virtual/TimelineItemDaySeparatorModelProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/virtual/TimelineItemDaySeparatorModelPreviewParam.kt index d31d35d62f..2fb4e7ac63 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/virtual/TimelineItemDaySeparatorModelProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/virtual/TimelineItemDaySeparatorModelPreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.messages.impl.timeline.model.virtual import androidx.compose.ui.tooling.preview.PreviewParameterProvider -class TimelineItemDaySeparatorModelProvider : PreviewParameterProvider { +class TimelineItemDaySeparatorModelPreviewParam : PreviewParameterProvider { override val values = sequenceOf( aTimelineItemDaySeparatorModel("Today"), aTimelineItemDaySeparatorModel("March 6, 2023") diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/AspectRatioProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/AspectRatioPreviewParam.kt similarity index 88% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/AspectRatioProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/AspectRatioPreviewParam.kt index 0ebd63439a..43118d96fd 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/AspectRatioProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/AspectRatioPreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.messages.impl.timeline.protection import androidx.compose.ui.tooling.preview.PreviewParameterProvider -class AspectRatioProvider : PreviewParameterProvider { +class AspectRatioPreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( null, 0.05f, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/ProtectedView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/ProtectedView.kt index 2dbe47e9e4..f8a0b7ac89 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/ProtectedView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/protection/ProtectedView.kt @@ -83,7 +83,7 @@ fun ProtectedView( @PreviewsDayNight @Composable internal fun ProtectedViewPreview( - @PreviewParameter(AspectRatioProvider::class) aspectRatio: Float?, + @PreviewParameter(AspectRatioPreviewParam::class) aspectRatio: Float?, ) = ElementPreview { TimelineItemAspectRatioBox( modifier = Modifier.blurHashBackground(A_BLUR_HASH, alpha = 0.9f), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogState.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogState.kt new file mode 100644 index 0000000000..02da5a6503 --- /dev/null +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogState.kt @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.timeline.sendfailure + +import androidx.compose.runtime.Immutable +import io.element.android.features.messages.impl.timeline.model.TimelineItem + +@Immutable +sealed interface SendFailureDialogState { + data object Hidden : SendFailureDialogState + + data class Show( + val event: TimelineItem.Event, + val sendFailureType: SendFailureType, + ) : SendFailureDialogState + + @Immutable + sealed interface SendFailureType { + data class InvalidMimeType(val mimeType: String) : SendFailureType + data object MissingMediaContent : SendFailureType + data object SendingFromUnverifiedDevice : SendFailureType + data class Error(val message: String) : SendFailureType + data object Unknown : SendFailureType + } +} diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogStatePreviewParam.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogStatePreviewParam.kt new file mode 100644 index 0000000000..728431cc44 --- /dev/null +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogStatePreviewParam.kt @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.timeline.sendfailure + +import androidx.compose.ui.tooling.preview.PreviewParameterProvider +import io.element.android.features.messages.impl.timeline.aTimelineItemEvent + +class SendFailureDialogStatePreviewParam : PreviewParameterProvider { + override val values: Sequence + get() = sequenceOf( + SendFailureDialogState.Hidden, + SendFailureDialogState.Show( + event = aTimelineItemEvent(), + sendFailureType = SendFailureDialogState.SendFailureType.InvalidMimeType("image/invalid") + ), + SendFailureDialogState.Show( + event = aTimelineItemEvent(), + sendFailureType = SendFailureDialogState.SendFailureType.MissingMediaContent, + ), + SendFailureDialogState.Show( + event = aTimelineItemEvent(), + sendFailureType = SendFailureDialogState.SendFailureType.SendingFromUnverifiedDevice, + ), + SendFailureDialogState.Show( + event = aTimelineItemEvent(), + sendFailureType = SendFailureDialogState.SendFailureType.Error("Message error from server"), + ), + SendFailureDialogState.Show( + event = aTimelineItemEvent(), + sendFailureType = SendFailureDialogState.SendFailureType.Unknown, + ) + ) +} diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogView.kt new file mode 100644 index 0000000000..15ee42d575 --- /dev/null +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogView.kt @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.timeline.sendfailure + +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.PreviewParameter +import io.element.android.features.messages.impl.R +import io.element.android.features.messages.impl.timeline.model.TimelineItem +import io.element.android.libraries.designsystem.components.dialogs.ConfirmationDialog +import io.element.android.libraries.designsystem.preview.ElementPreview +import io.element.android.libraries.designsystem.preview.PreviewsDayNight +import io.element.android.libraries.ui.strings.CommonStrings + +@Composable +fun SendFailureDialogView( + sendFailureDialogState: SendFailureDialogState, + onDismiss: () -> Unit, + onRetry: (TimelineItem.Event) -> Unit, + onRemoveMessage: (TimelineItem.Event) -> Unit, + modifier: Modifier = Modifier, +) { + when (sendFailureDialogState) { + is SendFailureDialogState.Hidden -> Unit + is SendFailureDialogState.Show -> { + // Show the dialog with the message and actions + val content = when (sendFailureDialogState.sendFailureType) { + is SendFailureDialogState.SendFailureType.InvalidMimeType -> stringResource( + id = R.string.error_sending_failure_invalid_mime_type, + sendFailureDialogState.sendFailureType.mimeType, + ) + is SendFailureDialogState.SendFailureType.MissingMediaContent -> stringResource( + id = R.string.error_sending_failure_missing_media_content, + ) + is SendFailureDialogState.SendFailureType.SendingFromUnverifiedDevice -> stringResource( + id = R.string.error_sending_failure_sending_from_unverified_device, + ) + is SendFailureDialogState.SendFailureType.Error -> stringResource( + id = R.string.error_sending_failure_other, + sendFailureDialogState.sendFailureType.message + ) + is SendFailureDialogState.SendFailureType.Unknown -> stringResource( + id = R.string.error_sending_failure_unknown, + ) + } + + ConfirmationDialog( + modifier = modifier, + title = stringResource(id = CommonStrings.common_sending_failed), + content = content, + onDismiss = onDismiss, + submitText = stringResource(id = CommonStrings.action_retry), + onSubmitClick = { onRetry(sendFailureDialogState.event) }, + onCancelClick = onDismiss, + thirdButtonText = stringResource(id = CommonStrings.action_remove_message), + onThirdButtonClick = { onRemoveMessage(sendFailureDialogState.event) }, + ) + } + } +} + +@PreviewsDayNight +@Composable +internal fun SendFailureDialogViewPreview( + @PreviewParameter(SendFailureDialogStatePreviewParam::class) sendFailureDialogState: SendFailureDialogState, +) = ElementPreview { + SendFailureDialogView( + sendFailureDialogState = sendFailureDialogState, + onDismiss = {}, + onRetry = {}, + onRemoveMessage = {}, + ) +} diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/topbars/MessagesViewTopBar.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/topbars/MessagesViewTopBar.kt index 6aabf97f2c..d6a55c0563 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/topbars/MessagesViewTopBar.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/topbars/MessagesViewTopBar.kt @@ -16,6 +16,7 @@ import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing @@ -84,6 +85,7 @@ internal fun MessagesViewTopBar( val roundedCornerShape = RoundedCornerShape(8.dp) Row( modifier = Modifier + .heightIn(min = 48.dp) .clip(roundedCornerShape) .clickable { onRoomDetailsClick() } .semantics { heading() }, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationStateProvider.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationStatePreviewParam.kt similarity index 97% rename from features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationStateProvider.kt rename to features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationStatePreviewParam.kt index e298b3af26..b98262a2a8 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationStateProvider.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.designsystem.preview.USER_NAME_DAVID import io.element.android.libraries.designsystem.preview.USER_NAME_EVE import kotlinx.collections.immutable.toImmutableList -class TypingNotificationStateProvider : PreviewParameterProvider { +class TypingNotificationStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTypingNotificationState(), diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationView.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationView.kt index c8e5722b19..3d2227c6d6 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationView.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/typing/TypingNotificationView.kt @@ -141,7 +141,7 @@ private fun computeTypingNotificationText(typingMembers: ImmutableList(start, end).isEmpty()) { + text.setSpan(URLSpan(match.value), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + } + } + } + } + private fun Spanned.canPillify(start: Int, end: Int): Boolean { if (getMentionSpans(start, end).isNotEmpty()) return false if (getSpans(start, end).isNotEmpty()) return false diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/voicemessages/timeline/VoiceMessagePresenter.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/voicemessages/timeline/VoiceMessagePresenter.kt index eef5c5efab..066ce09500 100644 --- a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/voicemessages/timeline/VoiceMessagePresenter.kt +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/voicemessages/timeline/VoiceMessagePresenter.kt @@ -12,27 +12,12 @@ import androidx.compose.runtime.Composable import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedFactory import dev.zacsweers.metro.AssistedInject -import dev.zacsweers.metro.BindingContainer -import dev.zacsweers.metro.Binds -import dev.zacsweers.metro.ContributesTo -import dev.zacsweers.metro.IntoMap -import io.element.android.features.messages.impl.timeline.di.TimelineItemEventContentKey import io.element.android.features.messages.impl.timeline.di.TimelineItemPresenterFactory import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVoiceContent import io.element.android.libraries.architecture.Presenter -import io.element.android.libraries.di.RoomScope import io.element.android.libraries.voiceplayer.api.VoiceMessagePresenterFactory import io.element.android.libraries.voiceplayer.api.VoiceMessageState -@BindingContainer -@ContributesTo(RoomScope::class) -interface VoiceMessagePresenterModule { - @Binds - @IntoMap - @TimelineItemEventContentKey(TimelineItemVoiceContent::class) - fun bindVoiceMessagePresenterFactory(factory: VoiceMessagePresenter.Factory): TimelineItemPresenterFactory<*, *> -} - @AssistedInject class VoiceMessagePresenter( voiceMessagePresenterFactory: VoiceMessagePresenterFactory, diff --git a/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/voicemessages/timeline/di/VoiceMessagePresenterBindingContainer.kt b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/voicemessages/timeline/di/VoiceMessagePresenterBindingContainer.kt new file mode 100644 index 0000000000..422ade8856 --- /dev/null +++ b/features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/voicemessages/timeline/di/VoiceMessagePresenterBindingContainer.kt @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.voicemessages.timeline.di + +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.Binds +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.IntoMap +import io.element.android.features.messages.impl.timeline.di.TimelineItemEventContentKey +import io.element.android.features.messages.impl.timeline.di.TimelineItemPresenterFactory +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemVoiceContent +import io.element.android.features.messages.impl.voicemessages.timeline.VoiceMessagePresenter +import io.element.android.libraries.di.RoomScope + +@BindingContainer +@ContributesTo(RoomScope::class) +interface VoiceMessagePresenterBindingContainer { + @Binds + @IntoMap + @TimelineItemEventContentKey(TimelineItemVoiceContent::class) + fun bindVoiceMessagePresenterFactory(factory: VoiceMessagePresenter.Factory): TimelineItemPresenterFactory<*, *> +} diff --git a/features/messages/impl/src/main/res/values-ar/translations.xml b/features/messages/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..80c296fa94 --- /dev/null +++ b/features/messages/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,114 @@ + + + "مرسل الحدث لا يطابق مالك الجهاز الذي أرسله." + "لا يمكن ضمان أصالة هذه الرسالة المشفّرة على هذا الجهاز." + "تم التشفير بواسطة مستخدم تم التحقق منه سابقًا." + "غير مشفّرة." + "تم التشفير بواسطة جهاز غير معروف أو محذوف." + "تم التشفير بواسطة جهاز لم يتحقق منه مالكه." + "تم التشفير بواسطة مستخدم لم يتم التحقق منه." + "قلب الصورة أفقيًا" + "مقلوبة أفقيًا" + "الأصلية" + "قلب الصورة رأسيًا" + "مقلوبة رأسيًا" + "الأصلية" + "تدوير الصورة إلى اليسار" + + "%1$d درجات" + "%1$d درجة" + "%1$d درجتان" + "%1$d درجات" + "%1$d درجة" + "%1$d درجة" + + "تعديل الصورة" + "قد لا تكون التعليقات التوضيحية مرئية للأشخاص الذين يستخدمون تطبيقات أقدم." + "اضغط لتغيير جودة رفع الفيديو" + "تعذّر رفع الملف." + "تعذّرت معالجة الوسائط من أجل رفعها، يرجى المحاولة مجدداً." + "تعذّر رفع الوسائط، يرجى المحاولة مجدداً." + "الحد الأقصى المسموح به لحجم الملف هو %1$s." + "الملف كبير جدًا ولا يمكن رفعه" + "العنصر %1$d من %2$d" + "تحسين جودة الصورة" + "جارٍ المعالجة…" + "إضافة وسائط" + "حظر المستخدم" + "حدِّد على هذا الخيار إذا كنت تريد إخفاء كل الرسائل الحالية والمستقبلية من هذا المستخدم" + "ستُبلَّغ هذه الرسالة إلى إدارة السيرفر خاصتك. لن يكونوا قادرين على قراءة أي رسالة مشفرة." + "سبب إبلاغك عن هذا المحتوى" + "الكاميرا" + "التقاط صورة" + "تسجيل مقطع فيديو" + "مرفق" + "معرض الصور والفيديوهات" + "مشاركة الموقع الجغرافي" + "استفتاء" + "تنسيق النص" + "سجل الرسائل غير متوفر حالياً." + "سجل الرسائل غير متاح في هذه الغرفة. تحقّق من هذا الجهاز لرؤية سجل رسائلك." + "هل تريد دعوته مجدداً؟" + "أنت لوحدك في هذه المحادثة" + "إشعار الغرفة بأكملها" + "الجميع" + "أرسل مجدداً" + "فشل إرسال رسالتك" + "أضف تفاعل" + "هنا بداية %1$s" + "هنا بداية المحادثة" + "مكالمة غير مدعومة. اسأل المتصل عما إذا كان بإمكانه استخدام تطبيق Element X الجديد." + "أظهر أقل" + "نُسِخت الرسالة" + "لا تملك الإذن بالنشر في هذه الغرفة" + + "تفاعل %1$d أعضاء بـ %2$s" + "تفاعل %1$d عضو بـ %2$s" + "تفاعل %1$d عضوان بـ %2$s" + "تفاعل %1$d أعضاء بـ %2$s" + "تفاعل %1$d عضوًا بـ %2$s" + "تفاعل %1$d عضو بـ %2$s" + + + "تفاعلت أنت و%1$d أعضاء بـ %2$s" + "تفاعلت أنت و%1$d عضو بـ %2$s" + "تفاعلت أنت و%1$d عضوان بـ %2$s" + "تفاعلت أنت و%1$d أعضاء بـ %2$s" + "تفاعلت أنت و%1$d عضوًا بـ %2$s" + "تفاعلت أنت و%1$d عضو بـ %2$s" + + "تفاعلت بـ %1$s" + "أظهر أقل" + "أظهر المزيد" + "اعرض ملخص التفاعلات" + "جديدة" + + "%1$d تغيير في الغرفة" + "%1$d تغيير في الغرفة" + "%1$d تغيير في الغرفة" + "%1$d تغييرات في الغرفة" + "%1$d تغيير في الغرفة" + "%1$d تغيير في الغرفة" + + "الانتقال إلى الغرفة الجديدة" + "استُبدلت هذه الغرفة ولم تعد نشطة" + "عرض الرسائل القديمة" + "هذه الغرفة هي استمرار لغرفة أخرى" + + "%1$s و%2$s و%3$d آخرون" + "%1$s و%2$s و%3$d آخر" + "%1$s و%2$s و%3$d آخران" + "%1$s و%2$s و%3$d آخرون" + "%1$s و%2$s و%3$d آخر" + "%1$s و%2$s و%3$d آخر" + + + "%1$s يكتبون الآن" + "%1$s يكتب الآن" + "%1$s يكتبان الآن" + "%1$s يكتبون الآن" + "%1$s يكتبون الآن" + "%1$s يكتبون الآن" + + "%1$s و%2$s" + diff --git a/features/messages/impl/src/main/res/values-es/translations.xml b/features/messages/impl/src/main/res/values-es/translations.xml index 0a0b57cc5e..ed725bc9d2 100644 --- a/features/messages/impl/src/main/res/values-es/translations.xml +++ b/features/messages/impl/src/main/res/values-es/translations.xml @@ -7,9 +7,29 @@ "Cifrado por un dispositivo desconocido o eliminado." "Cifrado por un dispositivo no verificado por su propietario." "Cifrado por un usuario no verificado." + "Voltear la imagen horizontalmente" + "Volteada horizontalmente" + "Original" + "Voltear la imagen verticalmente" + "Volteada verticalmente" + "Original" + "Rotar la imagen hacia la izquierda" + + "%1$d grado" + "%1$d grados" + + "Editar foto" "Es posible que las leyendas no sean visibles para las personas que usan aplicaciones más antiguas." + "Toca para cambiar la calidad de subida del vídeo" + "No se pudo subir el archivo." "Error al procesar el contenido multimedia, por favor inténtalo de nuevo." "Error al subir el contenido multimedia, por favor inténtalo de nuevo." + "El tamaño máximo permitido de archivo es de %1$s." + "El archivo es demasiado grande para subirlo" + "Elemento %1$d de %2$d" + "Optimizar la calidad de la imagen" + "Procesando…" + "Añadir contenido multimedia" "Bloquear usuario" "Marca esta casilla si quieres ocultar todos los mensajes actuales y futuros de este usuario" "Se denunciará este mensaje al administrador de tu servidor base. No será capaz de leer ningún mensaje cifrado." @@ -19,7 +39,7 @@ "Grabar video" "Archivo adjunto" "Biblioteca de fotos y vídeos" - "Ubicación" + "Compartir ubicación" "Encuesta" "Formato de texto" "El historial de mensajes no está disponible en este momento." @@ -37,10 +57,23 @@ "Mostrar menos" "Mensaje copiado" "No tienes permiso para publicar en esta sala" + + "%1$d miembro reaccionó con %2$s" + "%1$d miembros reaccionaron con %2$s" + + + "Tú y %1$d miembro reaccionasteis con %2$s" + "Tú y %1$d miembros reaccionasteis con %2$s" + + "Reaccionaste con %1$s" "Mostrar menos" "Mostrar más" "Mostrar todas las reacciones" "Nuevos" + + "%1$d mensaje eliminado" + "%1$d mensajes eliminados" + "%1$d cambio en la sala" "%1$d cambios en la sala" diff --git a/features/messages/impl/src/main/res/values-fa/translations.xml b/features/messages/impl/src/main/res/values-fa/translations.xml index 4f8f737f9c..f10d9ead33 100644 --- a/features/messages/impl/src/main/res/values-fa/translations.xml +++ b/features/messages/impl/src/main/res/values-fa/translations.xml @@ -1,14 +1,35 @@ + "فرستنده رویداد با صاحب دستگاهی که آن را ارسال کرده است، مطابقت ندارد." "اعتبار این پیام رمز شده نمی‌تواند روی این افزاره تأیید شود." "رمز شده به دست کاربری از پیش تأیید شده." "رمز نشده." "رمز شده به دست افزاره‌ای ناشناخته یا حذف شده." "رمز شده به دست افزاره‌ای که از سوی مالکش تأیید نشده." "رمز شده به دست کاربری تأیید نشده." + "تصویر را به صورت افقی بچرخانید" + "به صورت افقی برگردانده شده" + "اصلی" + "تصویر را به صورت عمودی بچرخانید" + "به صورت عمودی برگردانده شده" + "اصلی" + "تصویر را به سمت چپ بچرخانید" + + "درجه %1$d" + "درجه‌های %1$d" + + "ویرایش عکس" + "ممکن است زیرنویس‌ها برای افرادی که از برنامه‌های قدیمی‌تر استفاده می‌کنند قابل مشاهده نباشند." + "برای تغییر کیفیت آپلود ویدیو، ضربه بزنید" + "فایل قابل آپلود نبود." "پردازش رسانه برای بارگذاری شکست خورد. لطفاً دوباره تلاش کنید." "بارگذاری رسانه شکست خورد. لطفاً دوباره تلاش کنید." + "حداکثر اندازه مجاز فایل %1$s است." + "فایل برای آپلود خیلی بزرگ است" + "مورد %1$d از %2$d" + "بهینه سازی کیفیت تصویر" "پردازش کردن…" + "افزودن رسانه" "انسداد کاربر" "اگر می‌خواهید همه پیام‌های فعلی و آینده را از این کاربر را پنهان کنید، علامت بزنید" "این پیام به مدیر کارساز خانگی شما گزارش خواهد شد. آنها قادر به خواندن پیام های رمزگذاری شده نخواهند بود." @@ -32,13 +53,27 @@ "افزودن شکلک" "آغاز %1$s است." "این، آغاز گفت‌وگوست." + "تماس پشتیبانی نشده. بپرسید که آیا تماس گیرنده می‌تواند از برنامه جدید Element X استفاده کند یا خیر." "نمایش کم‌تر" "پیام رونوشت شد" "اجازهٔ فرستادن به این اتاق را ندارید" + + "عضو %1$d با %2$s واکنش نشان داد" + "اعضای %1$d با %2$s واکنش نشان دادند" + + + "شما و عضو %1$d با %2$s واکنش نشان دادید" + "شما و اعضای %1$d با %2$s واکنش نشان دادید" + + "شما با %1$s واکنش نشان دادید" "نمایش کم‌تر" "نمایش بیش‌تر" "نمایش خلاصهٔ واکنش‌ها" "جدید" + + "پیام حذف شده %1$d" + "پیام‌های حذف شده %1$d" + "%1$dتغییر اتاق" "%1$dتغییر اتاق" diff --git a/features/messages/impl/src/main/res/values-fi/translations.xml b/features/messages/impl/src/main/res/values-fi/translations.xml index 3705047087..308ae57f2b 100644 --- a/features/messages/impl/src/main/res/values-fi/translations.xml +++ b/features/messages/impl/src/main/res/values-fi/translations.xml @@ -70,6 +70,10 @@ "Näytä lisää" "Näytä reaktioiden yhteenveto" "Uusi" + + "%1$d poistettu viesti" + "%1$d poistettua viestiä" + "%1$d muutos huoneeseen" "%1$d muutosta huoneeseen" diff --git a/features/messages/impl/src/main/res/values-fr/translations.xml b/features/messages/impl/src/main/res/values-fr/translations.xml index 0062421326..6d10d9a493 100644 --- a/features/messages/impl/src/main/res/values-fr/translations.xml +++ b/features/messages/impl/src/main/res/values-fr/translations.xml @@ -70,6 +70,10 @@ "Afficher plus" "Afficher le résumé des réactions" "Nouveau" + + "%1$d message supprimé" + "%1$d messages supprimés" + "%1$d changement dans le salon" "%1$d changements dans le salon" diff --git a/features/messages/impl/src/main/res/values-hu/translations.xml b/features/messages/impl/src/main/res/values-hu/translations.xml index 2b428f92b2..98841bf995 100644 --- a/features/messages/impl/src/main/res/values-hu/translations.xml +++ b/features/messages/impl/src/main/res/values-hu/translations.xml @@ -70,6 +70,10 @@ "Több megjelenítése" "Reakció-összefoglaló megjelenítése" "Új" + + "%1$d eltávolított üzenet" + "%1$d eltávolított üzenet" + "%1$d szobaváltozás" "%1$d szobaváltozás" diff --git a/features/messages/impl/src/main/res/values-pl/translations.xml b/features/messages/impl/src/main/res/values-pl/translations.xml index 87ed6250c0..ac94594e99 100644 --- a/features/messages/impl/src/main/res/values-pl/translations.xml +++ b/features/messages/impl/src/main/res/values-pl/translations.xml @@ -32,7 +32,7 @@ "Przetwarzanie…" "Dodaj media" "Zablokuj użytkownika" - "Sprawdź, czy chcesz ukryć wszystkie bieżące i przyszłe wiadomości od tego użytkownika." + "Zaznacz, jeśli chcesz ukryć wszystkie bieżące i przyszłe wiadomości od tego użytkownika." "Ta wiadomość zostanie zgłoszona do administratora Twojego serwera domowego. Nie będzie mógł on przeczytać żadnych zaszyfrowanych wiadomości." "Powód zgłoszenia treści" "Kamera" diff --git a/features/messages/impl/src/main/res/values-ro/translations.xml b/features/messages/impl/src/main/res/values-ro/translations.xml index e9e4da87c3..d26a35bfc2 100644 --- a/features/messages/impl/src/main/res/values-ro/translations.xml +++ b/features/messages/impl/src/main/res/values-ro/translations.xml @@ -7,6 +7,19 @@ "Criptat de un dispozitiv necunoscut sau șters." "Criptat de un dispozitiv care nu este verificat de proprietarul său." "Criptat de un utilizator neverificat." + "Răsturnați imaginea pe orizontală" + "Răsturnat pe orizontală" + "Original" + "Răsturnați imaginea pe verticală" + "Răsturnat pe verticală" + "Original" + "Rotiți imaginea la stânga" + + "%1$d grad" + "%1$d grade" + "%1$d grade" + + "Editați poza" "Este posibil ca descrierile să nu fie vizibile pentru persoanele care folosesc aplicații mai vechi." "Atingeți pentru a modifica calitatea încărcării videoclipului" "Fișierul nu a putut fi încărcat." @@ -17,6 +30,7 @@ "Elementul %1$d din %2$d" "Optimizați calitatea imaginii" "Se procesează…" + "Adăugați media" "Blocați utilizatorul" "Confirmați că doriți să ascundeți toate mesajele curente și viitoare de la acest utilizator" "Acest mesaj va fi raportat administratorilor homeserver-ului tau. Ei nu vor putea citi niciun mesaj criptat." @@ -59,6 +73,11 @@ "Afișați mai mult" "Afișați rezumatul reacțiilor" "Nou" + + "%1$d mesaj șters" + "%1$d mesaje șterse" + "%1$d mesaje șterse" + "%1$d schimbare a camerii" "%1$d schimbări ale camerei" diff --git a/features/messages/impl/src/main/res/values-zh-rTW/translations.xml b/features/messages/impl/src/main/res/values-zh-rTW/translations.xml index e8cd285b5e..db7d96cd97 100644 --- a/features/messages/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/messages/impl/src/main/res/values-zh-rTW/translations.xml @@ -7,6 +7,17 @@ "由未知或已刪除的裝置加密。" "由未經其擁有者驗證的裝置加密。" "由未經驗證的使用者加密。" + "水平翻轉圖片" + "水平翻轉" + "原始狀態" + "垂直翻轉圖片" + "垂直翻轉" + "原始狀態" + "向左旋轉圖片" + + "%1$d 度" + + "編輯照片" "使用舊應用程式的使用者可能看不到標題。" "輕點即可變更影片上傳品質" "無法上傳檔案。" @@ -17,6 +28,7 @@ "第 %1$d 個項目,共 %2$d 個" "最佳化影像品質" "正在處理……" + "新增媒體" "封鎖使用者" "檢查您是否要隱藏所有來自此使用者的目前及未來的訊息" "此訊息將會回報給您的家伺服器管理員。他們將無法讀取任何已加密的訊息。" @@ -55,6 +67,9 @@ "更多" "顯示反應摘要" "新訊息" + + "%1$d 則已移除的訊息" + "%1$d 個聊天室變更" diff --git a/features/messages/impl/src/main/res/values/localazy.xml b/features/messages/impl/src/main/res/values/localazy.xml index 556ab00ee0..e29b83af41 100644 --- a/features/messages/impl/src/main/res/values/localazy.xml +++ b/features/messages/impl/src/main/res/values/localazy.xml @@ -7,6 +7,11 @@ "Encrypted by an unknown or deleted device." "Encrypted by a device not verified by its owner." "Encrypted by an unverified user." + "Invalid mime type: %s" + "Missing media content" + "Error details: %s" + "Sending from unverified device" + "Unknown error" "Flip image horizontally" "Flipped horizontally" "Original" diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesPresenterTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesPresenterTest.kt index 0a0d310b16..227088f78c 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesPresenterTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesPresenterTest.kt @@ -72,6 +72,7 @@ import io.element.android.libraries.matrix.api.room.tombstone.SuccessorRoom import io.element.android.libraries.matrix.api.timeline.Timeline import io.element.android.libraries.matrix.api.timeline.item.TimelineItemDebugInfo import io.element.android.libraries.matrix.api.timeline.item.event.EventOrTransactionId +import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState import io.element.android.libraries.matrix.api.timeline.item.event.toEventOrTransactionId import io.element.android.libraries.matrix.test.AN_AVATAR_URL import io.element.android.libraries.matrix.test.AN_EVENT_ID @@ -83,6 +84,7 @@ import io.element.android.libraries.matrix.test.A_SESSION_ID_2 import io.element.android.libraries.matrix.test.A_THREAD_ID import io.element.android.libraries.matrix.test.A_USER_ID import io.element.android.libraries.matrix.test.A_USER_ID_2 +import io.element.android.libraries.matrix.test.core.FakeSendHandle import io.element.android.libraries.matrix.test.core.aBuildMeta import io.element.android.libraries.matrix.test.encryption.FakeEncryptionService import io.element.android.libraries.matrix.test.permalink.FakePermalinkParser @@ -1043,6 +1045,56 @@ class MessagesPresenterTest { } } + @Test + fun `present - handle action retry sending`() = runTest { + val retryLambda = lambdaRecorder> { Result.success(Unit) } + val messageEvent = aMessageEvent( + sendState = LocalEventSendState.Failed.Unknown("Error"), + sendHandleProvider = { FakeSendHandle(retryLambda = retryLambda) }, + ) + val presenter = createMessagesPresenter() + presenter.testWithLifecycleOwner { + skipItems(1) + val initialState = awaitItem() + initialState.eventSink(MessagesEvent.HandleAction(TimelineItemAction.RetrySending, messageEvent)) + advanceUntilIdle() + retryLambda.assertions().isCalledOnce() + } + } + + @Test + fun `present - handle action retry sending - failure is ignored`() = runTest { + val retryLambda = lambdaRecorder> { Result.failure(AN_EXCEPTION) } + val messageEvent = aMessageEvent( + sendState = LocalEventSendState.Failed.Unknown("Error"), + sendHandleProvider = { FakeSendHandle(retryLambda = retryLambda) }, + ) + val presenter = createMessagesPresenter() + presenter.testWithLifecycleOwner { + skipItems(1) + val initialState = awaitItem() + initialState.eventSink(MessagesEvent.HandleAction(TimelineItemAction.RetrySending, messageEvent)) + advanceUntilIdle() + retryLambda.assertions().isCalledOnce() + } + } + + @Test + fun `present - handle action retry sending - no send handle, it should have no effect`() = runTest { + val messageEvent = aMessageEvent( + sendState = LocalEventSendState.Failed.Unknown("Error"), + sendHandleProvider = { null }, + ) + val presenter = createMessagesPresenter() + presenter.testWithLifecycleOwner { + skipItems(1) + val initialState = awaitItem() + initialState.eventSink(MessagesEvent.HandleAction(TimelineItemAction.RetrySending, messageEvent)) + advanceUntilIdle() + // No op! + } + } + @Test fun `present - handle action view in timeline, it should have no effect`() = runTest { val messageEvent = aMessageEvent( diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesViewTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesViewTest.kt index 2800c737ad..f662da0eb0 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesViewTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/MessagesViewTest.kt @@ -55,12 +55,14 @@ import io.element.android.features.messages.impl.timeline.components.receipt.aRe import io.element.android.features.messages.impl.timeline.components.receipt.bottomsheet.ReadReceiptBottomSheetEvent import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemTextContent +import io.element.android.features.messages.impl.timeline.sendfailure.SendFailureDialogState import io.element.android.features.roomcall.api.aStandByCallState import io.element.android.libraries.emoji.impl.picker.DefaultEmojiPickerRenderer import io.element.android.libraries.emoji.impl.picker.anEmojiPickerState import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.room.tombstone.SuccessorRoom +import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState import io.element.android.libraries.matrix.api.timeline.item.event.getAvatarUrl import io.element.android.libraries.matrix.api.timeline.item.event.getDisplayName import io.element.android.libraries.matrix.api.user.MatrixUser @@ -88,6 +90,7 @@ import org.junit.Test import org.robolectric.annotation.Config import kotlin.time.Duration.Companion.milliseconds +@Suppress("LargeClass") class MessagesViewTest : RobolectricTest() { @Test fun `clicking on back invoke expected callback`() = runAndroidComposeUiTest { @@ -176,6 +179,33 @@ class MessagesViewTest : RobolectricTest() { callback.assertSuccess() } + @Test + fun `clicking on an Event which has not been sent yet invoke expected callback`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder(expectEvents = false) + val localEcho = aTimelineItemEvent( + isMine = true, + content = aTimelineItemTextContent(), + ).copy(eventId = null) + val state = aMessagesState( + timelineState = aTimelineState( + timelineItems = persistentListOf(localEcho), + ), + eventSink = eventsRecorder + ) + val callback = EnsureCalledOnceWithTwoParamsAndResult( + expectedParam1 = true, + expectedParam2 = localEcho, + result = true, + ) + setMessagesView( + state = state, + onEventClick = callback, + ) + // Cannot perform click on "Text", it's not detected. Use tag instead + onAllNodesWithTag(TestTags.messageBubble.value).onFirst().performClick() + callback.assertSuccess() + } + @Test fun `long clicking on an Event emits the expected Event userHasPermissionToSendMessage`() { `long clicking on an Event emits the expected Event`(userHasPermissionToSendMessage = true) @@ -531,6 +561,80 @@ class MessagesViewTest : RobolectricTest() { eventsRecorder.assertSingle(TimelineEvent.ComputeVerifiedUserSendFailure(timelineItem)) } + @Test + fun `clicking on retry in the send failure dialog emits the expected Events`() = runAndroidComposeUiTest { + val messagesEventsRecorder = EventsRecorder() + val timelineEventsRecorder = EventsRecorder() + val timelineItem = aTimelineItemEvent(sendState = LocalEventSendState.Failed.Unknown("Error")) + setMessagesView( + state = aMessagesState( + timelineState = aTimelineState( + sendFailureDialogState = SendFailureDialogState.Show( + event = timelineItem, + sendFailureType = SendFailureDialogState.SendFailureType.Error("Error"), + ), + eventSink = timelineEventsRecorder, + ), + eventSink = messagesEventsRecorder, + ), + ) + // Clear initial 'LoadMore' event emitted when setting the state + timelineEventsRecorder.clear() + + clickOn(CommonStrings.action_retry) + messagesEventsRecorder.assertSingle(MessagesEvent.HandleAction(TimelineItemAction.RetrySending, timelineItem)) + timelineEventsRecorder.assertSingle(TimelineEvent.HideSendFailureDialog) + } + + @Test + fun `clicking on remove message in the send failure dialog emits the expected Events`() = runAndroidComposeUiTest { + val messagesEventsRecorder = EventsRecorder() + val timelineEventsRecorder = EventsRecorder() + val timelineItem = aTimelineItemEvent(sendState = LocalEventSendState.Failed.Unknown("Error")) + setMessagesView( + state = aMessagesState( + timelineState = aTimelineState( + sendFailureDialogState = SendFailureDialogState.Show( + event = timelineItem, + sendFailureType = SendFailureDialogState.SendFailureType.Error("Error"), + ), + eventSink = timelineEventsRecorder, + ), + eventSink = messagesEventsRecorder, + ), + ) + // Clear initial 'LoadMore' event emitted when setting the state + timelineEventsRecorder.clear() + + clickOn(CommonStrings.action_remove_message) + messagesEventsRecorder.assertSingle(MessagesEvent.HandleAction(TimelineItemAction.Redact, timelineItem)) + timelineEventsRecorder.assertSingle(TimelineEvent.HideSendFailureDialog) + } + + @Test + fun `cancelling the send failure dialog emits the expected Event`() = runAndroidComposeUiTest { + val messagesEventsRecorder = EventsRecorder(expectEvents = false) + val timelineEventsRecorder = EventsRecorder() + val timelineItem = aTimelineItemEvent(sendState = LocalEventSendState.Failed.Unknown("Error")) + setMessagesView( + state = aMessagesState( + timelineState = aTimelineState( + sendFailureDialogState = SendFailureDialogState.Show( + event = timelineItem, + sendFailureType = SendFailureDialogState.SendFailureType.Error("Error"), + ), + eventSink = timelineEventsRecorder, + ), + eventSink = messagesEventsRecorder, + ), + ) + // Clear initial 'LoadMore' event emitted when setting the state + timelineEventsRecorder.clear() + + clickOn(CommonStrings.action_cancel) + timelineEventsRecorder.assertSingle(TimelineEvent.HideSendFailureDialog) + } + @Test fun `clicking on a custom emoji emits the expected Events`() = runAndroidComposeUiTest { val aUnicode = "🙈" diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/actionlist/ActionListPresenterTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/actionlist/ActionListPresenterTest.kt index fb597df290..e987a32480 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/actionlist/ActionListPresenterTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/actionlist/ActionListPresenterTest.kt @@ -21,7 +21,10 @@ import io.element.android.features.messages.impl.timeline.model.event.RtcNotific import io.element.android.features.messages.impl.timeline.model.event.TimelineItemRedactedContent import io.element.android.features.messages.impl.timeline.model.event.TimelineItemRtcNotificationContent import io.element.android.features.messages.impl.timeline.model.event.TimelineItemTextContent +import io.element.android.features.messages.impl.timeline.model.event.aLiveLocationMode +import io.element.android.features.messages.impl.timeline.model.event.aStaticLocationMode import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemImageContent +import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemLocationContent import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemPollContent import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemStateEventContent import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemVoiceContent @@ -601,6 +604,123 @@ class ActionListPresenterTest { } } + @Test + fun `present - compute for a static location item`() = runTest { + val presenter = createActionListPresenter(isDeveloperModeEnabled = true) + presenter.test { + val initialState = awaitItem() + val messageEvent = aMessageEvent( + isMine = true, + isEditable = false, + content = aTimelineItemLocationContent(mode = aStaticLocationMode()), + ) + initialState.eventSink.invoke( + ActionListEvent.ComputeForMessage( + event = messageEvent, + userEventPermissions = aUserEventPermissions( + canRedactOwn = true, + canRedactOther = false, + canSendMessage = true, + canSendReaction = true, + canPinUnpin = true, + ), + ) + ) + val successState = awaitItem() + assertThat(successState.target).isEqualTo( + ActionListState.Target.Success( + event = messageEvent, + sentTimeFull = "0 Full true", + displayEmojiReactions = true, + verifiedUserSendFailure = VerifiedUserSendFailure.None, + actions = persistentListOf( + TimelineItemAction.Reply, + TimelineItemAction.Forward, + TimelineItemAction.CopyLink, + TimelineItemAction.Pin, + TimelineItemAction.ViewSource, + TimelineItemAction.Redact, + ), + recentEmojis = suggestedEmojis, + ) + ) + initialState.eventSink.invoke(ActionListEvent.Clear) + assertThat(awaitItem().target).isEqualTo(ActionListState.Target.None) + } + } + + @Test + fun `present - compute for a live location item does not offer to forward it`() = runTest { + val presenter = createActionListPresenter(isDeveloperModeEnabled = true) + presenter.test { + val initialState = awaitItem() + val messageEvent = aMessageEvent( + isMine = true, + isEditable = false, + content = aTimelineItemLocationContent(mode = aLiveLocationMode(isActive = true)), + ) + initialState.eventSink.invoke( + ActionListEvent.ComputeForMessage( + event = messageEvent, + userEventPermissions = aUserEventPermissions( + canRedactOwn = true, + canRedactOther = false, + canSendMessage = true, + canSendReaction = true, + canPinUnpin = true, + ), + ) + ) + val successState = awaitItem() + assertThat(successState.target).isEqualTo( + ActionListState.Target.Success( + event = messageEvent, + sentTimeFull = "0 Full true", + displayEmojiReactions = true, + verifiedUserSendFailure = VerifiedUserSendFailure.None, + actions = persistentListOf( + TimelineItemAction.Reply, + TimelineItemAction.CopyLink, + TimelineItemAction.Pin, + TimelineItemAction.ViewSource, + TimelineItemAction.Redact, + ), + recentEmojis = suggestedEmojis, + ) + ) + initialState.eventSink.invoke(ActionListEvent.Clear) + assertThat(awaitItem().target).isEqualTo(ActionListState.Target.None) + } + } + + @Test + fun `present - compute for an ended live location item does not offer to forward it`() = runTest { + val presenter = createActionListPresenter(isDeveloperModeEnabled = true) + presenter.test { + val initialState = awaitItem() + val messageEvent = aMessageEvent( + isMine = true, + isEditable = false, + content = aTimelineItemLocationContent(mode = aLiveLocationMode(isActive = false)), + ) + initialState.eventSink.invoke( + ActionListEvent.ComputeForMessage( + event = messageEvent, + userEventPermissions = aUserEventPermissions( + canRedactOwn = true, + canRedactOther = false, + canSendMessage = true, + canSendReaction = true, + canPinUnpin = true, + ), + ) + ) + val successState = awaitItem() + assertThat((successState.target as ActionListState.Target.Success).actions) + .doesNotContain(TimelineItemAction.Forward) + } + } + @Test fun `present - compute for a media with caption item`() = runTest { val presenter = createActionListPresenter(isDeveloperModeEnabled = true) diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenterTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenterTest.kt index fda8621087..4170ae41ab 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenterTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/messagecomposer/MessageComposerPresenterTest.kt @@ -61,6 +61,7 @@ import io.element.android.libraries.matrix.test.A_CAPTION import io.element.android.libraries.matrix.test.A_MESSAGE import io.element.android.libraries.matrix.test.A_REPLY import io.element.android.libraries.matrix.test.A_ROOM_ID +import io.element.android.libraries.matrix.test.A_THREAD_ID import io.element.android.libraries.matrix.test.A_TRANSACTION_ID import io.element.android.libraries.matrix.test.A_USER_ID import io.element.android.libraries.matrix.test.A_USER_ID_2 @@ -148,12 +149,25 @@ class MessageComposerPresenterTest : RobolectricTest() { assertThat(initialState.isFullScreen).isFalse() assertThat(initialState.textEditorState.messageHtml()).isEqualTo("") assertThat(initialState.mode).isEqualTo(MessageComposerMode.Normal) + assertThat(initialState.isInThreadTimeline).isFalse() assertThat(initialState.showAttachmentSourcePicker).isFalse() assertThat(initialState.canShareLocation).isTrue() assertThat(initialState.slashCommandAction).isEqualTo(AsyncAction.Uninitialized) } } + @Test + fun `present - when a threadRoot is provided, isInThreadTimeline is true`() = runTest { + val presenter = createPresenter( + threadRoot = A_THREAD_ID, + ) + presenter.test { + val initialState = awaitFirstItem() + assertThat(initialState.mode).isEqualTo(MessageComposerMode.Normal) + assertThat(initialState.isInThreadTimeline).isTrue() + } + } + @Test fun `present - toggle fullscreen`() = runTest { val presenter = createPresenter() @@ -1042,7 +1056,8 @@ class MessageComposerPresenterTest : RobolectricTest() { baseRoom = FakeBaseRoom( roomPermissions = FakeRoomPermissions( canTriggerRoomNotification = true, - ) + ), + updateMembersResult = {}, ), typingNoticeResult = { Result.success(Unit) } ).apply { @@ -1089,6 +1104,55 @@ class MessageComposerPresenterTest : RobolectricTest() { } } + @Test + fun `present - mention suggestions refresh the room members`() = runTest { + val currentUser = aRoomMember(userId = A_USER_ID, membership = RoomMembershipState.JOIN) + val bob = aRoomMember(userId = A_USER_ID_2, membership = RoomMembershipState.JOIN) + val updateMembersResult = lambdaRecorder { } + val room = FakeJoinedRoom( + baseRoom = FakeBaseRoom( + roomPermissions = FakeRoomPermissions( + canTriggerRoomNotification = true, + ), + updateMembersResult = updateMembersResult, + ), + typingNoticeResult = { Result.success(Unit) } + ).apply { + givenRoomMembersState( + RoomMembersState.Ready( + persistentListOf(currentUser, bob), + ) + ) + givenRoomInfo(aRoomInfo(isDirect = false)) + } + val presenter = createPresenter( + room = room, + slashCommandService = FakeSlashCommandService( + getSuggestionsResult = { _, _ -> emptyList() }, + ), + ) + presenter.test { + val initialState = awaitItem() + initialState.eventSink(MessageComposerEvent.SuggestionReceived(Suggestion(0, 0, SuggestionType.Mention, ""))) + skipItems(1) + assertThat(awaitItem().suggestions).containsExactly(ResolvedSuggestion.AtRoom, ResolvedSuggestion.Member(bob)) + updateMembersResult.assertions().isCalledOnce() + + // Typing after the `@` must not refresh the members again + initialState.eventSink(MessageComposerEvent.SuggestionReceived(Suggestion(0, 1, SuggestionType.Mention, "b"))) + initialState.eventSink(MessageComposerEvent.SuggestionReceived(Suggestion(0, 2, SuggestionType.Mention, "bo"))) + advanceUntilIdle() + updateMembersResult.assertions().isCalledOnce() + + // Starting a new mention refreshes them again + initialState.eventSink(MessageComposerEvent.SuggestionReceived(null)) + initialState.eventSink(MessageComposerEvent.SuggestionReceived(Suggestion(0, 0, SuggestionType.Mention, ""))) + advanceUntilIdle() + updateMembersResult.assertions().isCalledExactly(2) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `present - room mention suggestions no permission`() = runTest { val currentUser = aRoomMember(userId = A_USER_ID, membership = RoomMembershipState.JOIN) @@ -1099,7 +1163,8 @@ class MessageComposerPresenterTest : RobolectricTest() { baseRoom = FakeBaseRoom( roomPermissions = FakeRoomPermissions( canTriggerRoomNotification = false, - ) + ), + updateMembersResult = {}, ), typingNoticeResult = { Result.success(Unit) } ).apply { @@ -1130,6 +1195,7 @@ class MessageComposerPresenterTest : RobolectricTest() { val room = FakeJoinedRoom( baseRoom = FakeBaseRoom( roomPermissions = FakeRoomPermissions(canTriggerRoomNotification = true), + updateMembersResult = {}, ), typingNoticeResult = { Result.success(Unit) } ).apply { diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerItemFactoryTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerItemFactoryTest.kt new file mode 100644 index 0000000000..114eed98d9 --- /dev/null +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerItemFactoryTest.kt @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.pinned.banner + +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.eventformatter.test.FakePinnedMessagesBannerFormatter +import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem +import io.element.android.libraries.matrix.api.timeline.item.event.EventContent +import io.element.android.libraries.matrix.api.timeline.item.event.FailedToParseMessageLikeContent +import io.element.android.libraries.matrix.api.timeline.item.event.FailedToParseStateContent +import io.element.android.libraries.matrix.api.timeline.item.event.UnknownContent +import io.element.android.libraries.matrix.api.timeline.item.virtual.VirtualTimelineItem +import io.element.android.libraries.matrix.test.AN_EVENT_ID +import io.element.android.libraries.matrix.test.A_UNIQUE_ID +import io.element.android.libraries.matrix.test.timeline.aMessageContent +import io.element.android.libraries.matrix.test.timeline.anEventTimelineItem +import io.element.android.tests.testutils.testCoroutineDispatchers +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import org.junit.Test + +class PinnedMessagesBannerItemFactoryTest { + @Test + fun `create - returns an item for an event which can be displayed`() = runTest { + val factory = createPinnedMessagesBannerItemFactory() + val item = factory.create(anEventTimelineItemOf(aMessageContent("A message"))) + assertThat(item?.eventId).isEqualTo(AN_EVENT_ID) + } + + @Test + fun `create - returns null for events which cannot be displayed`() = runTest { + val factory = createPinnedMessagesBannerItemFactory() + val contents = listOf( + UnknownContent, + FailedToParseMessageLikeContent(eventType = "m.room.message", error = "an error"), + FailedToParseStateContent(eventType = "m.room.topic", stateKey = "", error = "an error"), + ) + for (content in contents) { + assertThat(factory.create(anEventTimelineItemOf(content))).isNull() + } + } + + @Test + fun `create - returns null for virtual items`() = runTest { + val factory = createPinnedMessagesBannerItemFactory() + val item = factory.create( + MatrixTimelineItem.Virtual( + uniqueId = A_UNIQUE_ID, + virtual = VirtualTimelineItem.DayDivider(timestamp = 0L), + ) + ) + assertThat(item).isNull() + } + + private fun anEventTimelineItemOf(content: EventContent) = MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID, + event = anEventTimelineItem( + eventId = AN_EVENT_ID, + content = content, + ), + ) + + private fun TestScope.createPinnedMessagesBannerItemFactory() = PinnedMessagesBannerItemFactory( + coroutineDispatchers = testCoroutineDispatchers(), + formatter = FakePinnedMessagesBannerFormatter( + formatLambda = { event -> "${event.content}" } + ), + ) +} diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerPresenterTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerPresenterTest.kt index 1f95baccc9..256837e5f7 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerPresenterTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/banner/PinnedMessagesBannerPresenterTest.kt @@ -14,6 +14,7 @@ import io.element.android.libraries.eventformatter.test.FakePinnedMessagesBanner import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.api.sync.SyncService import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem +import io.element.android.libraries.matrix.api.timeline.item.event.UnknownContent import io.element.android.libraries.matrix.test.AN_EVENT_ID import io.element.android.libraries.matrix.test.AN_EVENT_ID_2 import io.element.android.libraries.matrix.test.A_UNIQUE_ID @@ -24,6 +25,7 @@ import io.element.android.libraries.matrix.test.sync.FakeSyncService import io.element.android.libraries.matrix.test.timeline.FakeTimeline import io.element.android.libraries.matrix.test.timeline.aMessageContent import io.element.android.libraries.matrix.test.timeline.anEventTimelineItem +import io.element.android.tests.testutils.consumeItemsUntilPredicate import io.element.android.tests.testutils.test import io.element.android.tests.testutils.testCoroutineDispatchers import kotlinx.coroutines.flow.flowOf @@ -90,6 +92,46 @@ class PinnedMessagesBannerPresenterTest { } } + @Test + fun `present - loaded state - events which cannot be displayed are not rendered`() = runTest { + val messageContent = aMessageContent("A message") + val pinnedEventsTimeline = FakeTimeline( + timelineItems = flowOf( + listOf( + MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID, + event = anEventTimelineItem( + eventId = AN_EVENT_ID, + content = messageContent, + ), + ), + MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID_2, + event = anEventTimelineItem( + eventId = AN_EVENT_ID_2, + content = UnknownContent, + ), + ) + ) + ) + ) + val room = FakeJoinedRoom( + createTimelineResult = { Result.success(pinnedEventsTimeline) } + ).apply { + givenRoomInfo(aRoomInfo(pinnedEventIds = listOf(AN_EVENT_ID, AN_EVENT_ID_2))) + } + val presenter = createPinnedMessagesBannerPresenter(room = room) + presenter.test { + val loadedState = consumeItemsUntilPredicate { state -> + state is PinnedMessagesBannerState.Loaded + }.last() as PinnedMessagesBannerState.Loaded + assertThat(loadedState.loadedPinnedMessagesCount).isEqualTo(1) + assertThat(loadedState.currentPinnedMessageIndex).isEqualTo(0) + assertThat(loadedState.currentPinnedMessage.formatted.text).isEqualTo(messageContent.toString()) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `present - loaded state - multiple pinned messages`() = runTest { val messageContent1 = aMessageContent("A message") diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenterTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenterTest.kt index 8b2da2cefd..cafb16c41f 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenterTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListPresenterTest.kt @@ -10,6 +10,8 @@ package io.element.android.features.messages.impl.pinned.list import com.google.common.truth.Truth.assertThat import im.vector.app.features.analytics.plan.PinUnpinAction +import io.element.android.features.messages.impl.aCustomReactionState +import io.element.android.features.messages.impl.aReactionSummaryState import io.element.android.features.messages.impl.actionlist.anActionListState import io.element.android.features.messages.impl.actionlist.model.TimelineItemAction import io.element.android.features.messages.impl.fixtures.aTimelineItemsFactoryCreator @@ -21,13 +23,19 @@ import io.element.android.features.messages.test.timeline.FakeHtmlConverterProvi import io.element.android.libraries.designsystem.utils.snackbar.SnackbarDispatcher import io.element.android.libraries.featureflag.test.FakeFeatureFlagService import io.element.android.libraries.matrix.api.core.EventId +import io.element.android.libraries.matrix.api.core.UniqueId import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.api.sync.SyncService import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem import io.element.android.libraries.matrix.api.timeline.item.TimelineItemDebugInfo +import io.element.android.libraries.matrix.api.timeline.item.event.FailedToParseMessageLikeContent +import io.element.android.libraries.matrix.api.timeline.item.event.UnknownContent +import io.element.android.libraries.matrix.api.timeline.item.virtual.VirtualTimelineItem import io.element.android.libraries.matrix.test.AN_EVENT_ID +import io.element.android.libraries.matrix.test.AN_EVENT_ID_2 import io.element.android.libraries.matrix.test.AN_EXCEPTION import io.element.android.libraries.matrix.test.A_UNIQUE_ID +import io.element.android.libraries.matrix.test.A_UNIQUE_ID_2 import io.element.android.libraries.matrix.test.room.FakeBaseRoom import io.element.android.libraries.matrix.test.room.FakeJoinedRoom import io.element.android.libraries.matrix.test.room.aRoomInfo @@ -38,6 +46,7 @@ import io.element.android.libraries.matrix.test.timeline.aMessageContent import io.element.android.libraries.matrix.test.timeline.anEventTimelineItem import io.element.android.services.analytics.api.AnalyticsService import io.element.android.services.analytics.test.FakeAnalyticsService +import io.element.android.tests.testutils.consumeItemsUntilPredicate import io.element.android.tests.testutils.lambda.assert import io.element.android.tests.testutils.lambda.lambdaRecorder import io.element.android.tests.testutils.lambda.value @@ -131,6 +140,90 @@ class PinnedMessagesListPresenterTest { } } + @Test + fun `present - filled state - events which cannot be displayed are not rendered`() = runTest { + val pinnedEventsTimeline = createPinnedMessagesTimeline( + items = listOf( + MatrixTimelineItem.Virtual( + uniqueId = UniqueId("aDayDivider"), + virtual = VirtualTimelineItem.DayDivider(timestamp = 0L), + ), + MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID, + event = anEventTimelineItem( + eventId = AN_EVENT_ID, + content = aMessageContent("A message"), + ), + ), + MatrixTimelineItem.Virtual( + uniqueId = UniqueId("anotherDayDivider"), + virtual = VirtualTimelineItem.DayDivider(timestamp = 1L), + ), + MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID_2, + event = anEventTimelineItem( + eventId = AN_EVENT_ID_2, + content = UnknownContent, + ), + ), + ), + ) + val room = FakeJoinedRoom( + baseRoom = FakeBaseRoom( + roomPermissions = roomPermissions(), + ).apply { + givenRoomInfo(aRoomInfo(pinnedEventIds = listOf(AN_EVENT_ID, AN_EVENT_ID_2))) + }, + createTimelineResult = { Result.success(pinnedEventsTimeline) }, + ) + val presenter = createPinnedMessagesListPresenter(room = room) + presenter.test { + val filledState = consumeItemsUntilPredicate { state -> + state is PinnedMessagesListState.Filled + }.last() as PinnedMessagesListState.Filled + assertThat(filledState.loadedPinnedMessagesCount).isEqualTo(1) + assertThat(filledState.timelineItems).hasSize(2) + assertThat(filledState.timelineItems.filterIsInstance().map { it.eventId }).containsExactly(AN_EVENT_ID) + assertThat(filledState.timelineItems.filterIsInstance()).hasSize(1) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - empty state when no pinned event can be displayed`() = runTest { + val pinnedEventsTimeline = createPinnedMessagesTimeline( + items = listOf( + MatrixTimelineItem.Virtual( + uniqueId = A_UNIQUE_ID, + virtual = VirtualTimelineItem.DayDivider(timestamp = 0L), + ), + MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID_2, + event = anEventTimelineItem( + eventId = AN_EVENT_ID, + content = FailedToParseMessageLikeContent(eventType = "m.room.message", error = "an error"), + ), + ), + ), + ) + val room = FakeJoinedRoom( + baseRoom = FakeBaseRoom( + roomPermissions = roomPermissions(), + ).apply { + givenRoomInfo(aRoomInfo(pinnedEventIds = listOf(AN_EVENT_ID))) + }, + createTimelineResult = { Result.success(pinnedEventsTimeline) }, + ) + val presenter = createPinnedMessagesListPresenter(room = room) + presenter.test { + val emptyState = consumeItemsUntilPredicate { state -> + state is PinnedMessagesListState.Empty + }.last() + assertThat(emptyState).isEqualTo(PinnedMessagesListState.Empty) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `present - unpin event`() = runTest { val successUnpinEventLambda = lambdaRecorder { _: EventId? -> Result.success(true) } @@ -263,21 +356,18 @@ class PinnedMessagesListPresenterTest { } } - private fun createPinnedMessagesTimeline(): FakeTimeline { - val messageContent = aMessageContent("A message") - return FakeTimeline( - timelineItems = flowOf( - listOf( - MatrixTimelineItem.Event( - uniqueId = A_UNIQUE_ID, - event = anEventTimelineItem( - eventId = AN_EVENT_ID, - content = messageContent, - ), - ) - ) + private fun createPinnedMessagesTimeline( + items: List = listOf( + MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID, + event = anEventTimelineItem( + eventId = AN_EVENT_ID, + content = aMessageContent("A message"), + ), ) - ) + ), + ): FakeTimeline { + return FakeTimeline(timelineItems = flowOf(items)) } private fun roomPermissions( @@ -312,6 +402,8 @@ class PinnedMessagesListPresenterTest { snackbarDispatcher = SnackbarDispatcher(), actionListPresenter = { anActionListState() }, linkPresenter = { aLinkState() }, + customReactionPresenter = { aCustomReactionState() }, + reactionSummaryPresenter = { aReactionSummaryState() }, analyticsService = analyticsService, featureFlagService = featureFlagService, sessionCoroutineScope = this, diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListViewTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListViewTest.kt index 35e60684a9..856f74e33a 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListViewTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/pinned/list/PinnedMessagesListViewTest.kt @@ -24,6 +24,7 @@ import io.element.android.features.messages.impl.actionlist.anActionListState import io.element.android.features.messages.impl.timeline.aTimelineItemList import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.model.event.aTimelineItemFileContent +import io.element.android.libraries.emoji.api.picker.NoOpEmojiPickerRenderer import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.tests.testutils.EnsureNeverCalled import io.element.android.tests.testutils.EnsureNeverCalledWithParam @@ -111,6 +112,7 @@ private fun AndroidComposeUiTest.setPinnedMessagesListView( onUserDataClick = onUserDataClick, onLinkClick = onLinkClick, onLinkLongClick = onLinkLongClick, + emojiPickerRenderer = NoOpEmojiPickerRenderer, ) } } diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenterTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenterTest.kt index 2a0f9115fe..9956729ecb 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenterTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelinePresenterTest.kt @@ -12,6 +12,8 @@ import app.cash.turbine.ReceiveTurbine import com.google.common.truth.Truth.assertThat import io.element.android.features.location.test.FakeActiveLiveLocationShareManager import io.element.android.features.messages.impl.FakeMessagesNavigator +import io.element.android.features.messages.impl.crypto.sendfailure.resolve.ResolveVerifiedUserSendFailureEvent +import io.element.android.features.messages.impl.crypto.sendfailure.resolve.ResolveVerifiedUserSendFailureState import io.element.android.features.messages.impl.crypto.sendfailure.resolve.aResolveVerifiedUserSendFailureState import io.element.android.features.messages.impl.fixtures.aMessageEvent import io.element.android.features.messages.impl.fixtures.aTimelineItemsFactoryCreator @@ -21,6 +23,7 @@ import io.element.android.features.messages.impl.timeline.model.NewEventState import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.protection.TimelineProtectionState import io.element.android.features.messages.impl.timeline.protection.aTimelineProtectionState +import io.element.android.features.messages.impl.timeline.sendfailure.SendFailureDialogState import io.element.android.features.messages.impl.typing.aTypingNotificationState import io.element.android.features.messages.impl.voicemessages.timeline.FakeRedactedVoiceMessageManager import io.element.android.features.messages.impl.voicemessages.timeline.RedactedVoiceMessageManager @@ -45,6 +48,7 @@ import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem import io.element.android.libraries.matrix.api.timeline.ReceiptType import io.element.android.libraries.matrix.api.timeline.Timeline import io.element.android.libraries.matrix.api.timeline.item.event.EventReaction +import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState import io.element.android.libraries.matrix.api.timeline.item.event.ReactionSender import io.element.android.libraries.matrix.api.timeline.item.event.Receipt import io.element.android.libraries.matrix.api.timeline.item.event.RedactedContent @@ -1059,6 +1063,169 @@ class TimelinePresenterTest { } } + @Test + fun `present - a forward pagination while the focused event is not rendered yet is ignored`() = runTest { + val paginateLambda = lambdaRecorder(ensureNeverCalled = true) { _: Timeline.PaginationDirection -> + Result.success(true) + } + val room = aRoomWithDetachedTimeline(paginateLambda = paginateLambda) + val presenter = createTimelinePresenter( + room = room, + timeline = room.liveTimeline, + ) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink.invoke(TimelineEvent.FocusOnEvent(AN_EVENT_ID)) + val focusedState = consumeItemsUntilPredicate { it.focusRequestState == FocusRequestState.Success(AN_EVENT_ID) }.last() + assertThat(focusedState.isLive).isFalse() + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.FORWARDS)) + advanceUntilIdle() + assert(paginateLambda).isNeverCalled() + assertThat(expectMostRecentItem().isLive).isFalse() + } + } + + @Test + fun `present - a forward pagination is performed once the focused event has been rendered`() = runTest { + val paginateLambda = lambdaRecorder { _: Timeline.PaginationDirection -> + Result.success(true) + } + val room = aRoomWithDetachedTimeline(paginateLambda = paginateLambda) + val presenter = createTimelinePresenter( + room = room, + timeline = room.liveTimeline, + ) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink.invoke(TimelineEvent.FocusOnEvent(AN_EVENT_ID)) + consumeItemsUntilPredicate { it.focusRequestState == FocusRequestState.Success(AN_EVENT_ID) } + initialState.eventSink.invoke(TimelineEvent.OnFocusEventRender) + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.FORWARDS)) + advanceUntilIdle() + assert(paginateLambda) + .isCalledOnce() + .with(value(Timeline.PaginationDirection.FORWARDS)) + assertThat(expectMostRecentItem().isLive).isTrue() + } + } + + @Test + fun `present - a backward pagination while the focused event is not rendered yet is performed`() = runTest { + val paginateLambda = lambdaRecorder { _: Timeline.PaginationDirection -> + Result.success(false) + } + val room = aRoomWithDetachedTimeline(paginateLambda = paginateLambda) + val presenter = createTimelinePresenter( + room = room, + timeline = room.liveTimeline, + ) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink.invoke(TimelineEvent.FocusOnEvent(AN_EVENT_ID)) + consumeItemsUntilPredicate { it.focusRequestState == FocusRequestState.Success(AN_EVENT_ID) } + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.BACKWARDS)) + advanceUntilIdle() + assert(paginateLambda) + .isCalledOnce() + .with(value(Timeline.PaginationDirection.BACKWARDS)) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - a forward pagination while the focus request is debounced is ignored`() = runTest { + val paginateLambda = lambdaRecorder(ensureNeverCalled = true) { _: Timeline.PaginationDirection -> + Result.success(true) + } + val room = aRoomWithDetachedTimeline(paginateLambda = paginateLambda) + val presenter = createTimelinePresenter( + room = room, + timeline = room.liveTimeline, + ) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink.invoke(TimelineEvent.FocusOnEvent(AN_EVENT_ID, debounce = 1.seconds)) + // The focus request has started and is now waiting for the debounce to elapse + consumeItemsUntilPredicate { it.focusRequestState is FocusRequestState.Requested } + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.FORWARDS)) + advanceUntilIdle() + assert(paginateLambda).isNeverCalled() + assertThat(expectMostRecentItem().isLive).isFalse() + } + } + + @Test + fun `present - a forward pagination while the focused timeline is loading is ignored`() = runTest { + val paginateLambda = lambdaRecorder(ensureNeverCalled = true) { _: Timeline.PaginationDirection -> + Result.success(true) + } + val room = aRoomWithDetachedTimeline(paginateLambda = paginateLambda) + val presenter = createTimelinePresenter( + room = room, + timeline = room.liveTimeline, + ) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink.invoke(TimelineEvent.FocusOnEvent(AN_EVENT_ID)) + // The focused timeline is being created, the focus request has not resolved yet + consumeItemsUntilPredicate { it.focusRequestState is FocusRequestState.Loading } + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.FORWARDS)) + advanceUntilIdle() + assert(paginateLambda).isNeverCalled() + assertThat(expectMostRecentItem().isLive).isFalse() + } + } + + @Test + fun `present - a forward pagination after a failed focus request is performed`() = runTest { + val paginateLambda = lambdaRecorder { _: Timeline.PaginationDirection -> + Result.success(false) + } + val room = aRoomWithDetachedTimeline( + paginateLambda = paginateLambda, + createTimelineResult = { Result.failure(RuntimeException("An error")) }, + ) + val presenter = createTimelinePresenter( + room = room, + timeline = room.liveTimeline, + ) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink.invoke(TimelineEvent.FocusOnEvent(AN_EVENT_ID)) + consumeItemsUntilPredicate { it.focusRequestState is FocusRequestState.Failure } + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.FORWARDS)) + advanceUntilIdle() + assert(paginateLambda) + .isCalledOnce() + .with(value(Timeline.PaginationDirection.FORWARDS)) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - a forward pagination in a thread timeline is ignored`() = runTest { + val paginateLambda = lambdaRecorder { _: Timeline.PaginationDirection -> + Result.success(true) + } + val timeline = FakeTimeline(mode = Timeline.Mode.Thread(A_THREAD_ID)).apply { + this.paginateLambda = paginateLambda + } + val presenter = createTimelinePresenter(timeline = timeline) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.FORWARDS)) + advanceUntilIdle() + assert(paginateLambda).isNeverCalled() + // A backward pagination is still performed in a thread timeline + initialState.eventSink.invoke(TimelineEvent.LoadMore(Timeline.PaginationDirection.BACKWARDS)) + advanceUntilIdle() + assert(paginateLambda) + .isCalledOnce() + .with(value(Timeline.PaginationDirection.BACKWARDS)) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `present - focus on known event retrieves the event from cache`() = runTest { val timelineItemIndexer = TimelineItemIndexer() @@ -1390,6 +1557,112 @@ class TimelinePresenterTest { } } + @Test + fun `present - show and hide send failure dialog`() = runTest { + val presenter = createTimelinePresenter() + val event = aMessageEvent(sendState = LocalEventSendState.Failed.Unknown("An error")) + presenter.test { + val initialState = awaitFirstItem() + assertThat(initialState.sendFailureDialogState).isEqualTo(SendFailureDialogState.Hidden) + initialState.eventSink(TimelineEvent.ShowSendFailureDialog(event)) + awaitItem().also { state -> + assertThat(state.sendFailureDialogState).isEqualTo( + SendFailureDialogState.Show( + event = event, + sendFailureType = SendFailureDialogState.SendFailureType.Error("An error"), + ) + ) + state.eventSink(TimelineEvent.HideSendFailureDialog) + } + awaitItem().also { state -> + assertThat(state.sendFailureDialogState).isEqualTo(SendFailureDialogState.Hidden) + } + } + } + + @Test + fun `present - show send failure dialog - unknown error with a blank reason`() { + assertSendFailureType( + sendState = LocalEventSendState.Failed.Unknown(error = ""), + expectedSendFailureType = SendFailureDialogState.SendFailureType.Unknown, + ) + } + + @Test + fun `present - show send failure dialog - invalid mime type`() { + assertSendFailureType( + sendState = LocalEventSendState.Failed.InvalidMimeType(mimeType = "invalid/mimeType"), + expectedSendFailureType = SendFailureDialogState.SendFailureType.InvalidMimeType("invalid/mimeType"), + ) + } + + @Test + fun `present - show send failure dialog - missing media content`() { + assertSendFailureType( + sendState = LocalEventSendState.Failed.MissingMediaContent, + expectedSendFailureType = SendFailureDialogState.SendFailureType.MissingMediaContent, + ) + } + + @Test + fun `present - show send failure dialog - sending from unverified device`() { + assertSendFailureType( + sendState = LocalEventSendState.Failed.SendingFromUnverifiedDevice, + expectedSendFailureType = SendFailureDialogState.SendFailureType.SendingFromUnverifiedDevice, + ) + } + + private fun assertSendFailureType( + sendState: LocalEventSendState.Failed, + expectedSendFailureType: SendFailureDialogState.SendFailureType, + ) = runTest { + val presenter = createTimelinePresenter() + val event = aMessageEvent(sendState = sendState) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink(TimelineEvent.ShowSendFailureDialog(event)) + assertThat(awaitItem().sendFailureDialogState).isEqualTo( + SendFailureDialogState.Show(event = event, sendFailureType = expectedSendFailureType) + ) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - show send failure dialog - verified user failure is delegated to the resolve presenter`() = runTest { + val resolveEventSinkRecorder = lambdaRecorder { } + val presenter = createTimelinePresenter( + resolveVerifiedUserSendFailurePresenter = { + aResolveVerifiedUserSendFailureState(eventSink = resolveEventSinkRecorder) + }, + ) + val event = aMessageEvent( + sendState = LocalEventSendState.Failed.VerifiedUserChangedIdentity(users = listOf(A_USER_ID)), + ) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink(TimelineEvent.ShowSendFailureDialog(event)) + // The generic dialog is not displayed, the dedicated one is. + assertThat(consumeItemsUntilTimeout()).isEmpty() + assertThat(initialState.sendFailureDialogState).isEqualTo(SendFailureDialogState.Hidden) + resolveEventSinkRecorder.assertions() + .isCalledOnce() + .with(value(ResolveVerifiedUserSendFailureEvent.ComputeForMessage(event))) + } + } + + @Test + fun `present - show send failure dialog - no effect if the event did not fail to send`() = runTest { + val presenter = createTimelinePresenter() + val event = aMessageEvent(sendState = LocalEventSendState.Sending.Event) + presenter.test { + val initialState = awaitFirstItem() + initialState.eventSink(TimelineEvent.ShowSendFailureDialog(event)) + assertThat(consumeItemsUntilTimeout()).isEmpty() + assertThat(initialState.sendFailureDialogState).isEqualTo(SendFailureDialogState.Hidden) + } + } + @Test fun `present - when room member info is loaded, read receipts info should be updated`() = runTest { val timeline = FakeTimeline( @@ -1552,6 +1825,37 @@ class TimelinePresenterTest { return awaitItem() } + private fun aRoomWithDetachedTimeline( + paginateLambda: (Timeline.PaginationDirection) -> Result, + createTimelineResult: () -> Result = { Result.success(aDetachedTimeline(paginateLambda)) }, + ): FakeJoinedRoom { + return FakeJoinedRoom( + liveTimeline = FakeTimeline(timelineItems = flowOf(emptyList())).apply { + this.paginateLambda = paginateLambda + }, + createTimelineResult = { createTimelineResult() }, + baseRoom = FakeBaseRoom( + roomPermissions = roomPermissions(), + threadRootIdForEventResult = { _ -> Result.success(null) }, + ), + ) + } + + private fun aDetachedTimeline( + paginateLambda: (Timeline.PaginationDirection) -> Result, + ) = FakeTimeline( + timelineItems = flowOf( + listOf( + MatrixTimelineItem.Event( + uniqueId = A_UNIQUE_ID, + event = anEventTimelineItem(eventId = AN_EVENT_ID), + ) + ) + ) + ).apply { + this.paginateLambda = paginateLambda + } + private fun roomPermissions( canRedactOther: Boolean = false, canRedactOwn: Boolean = true, @@ -1589,6 +1893,7 @@ class TimelinePresenterTest { liveLocationShareManager: FakeActiveLiveLocationShareManager = FakeActiveLiveLocationShareManager(), markAsFullyRead: MarkAsFullyRead = FakeMarkAsFullyRead { _, _ -> }, timelineProtectionPresenter: Presenter = { aTimelineProtectionState() }, + resolveVerifiedUserSendFailurePresenter: Presenter = { aResolveVerifiedUserSendFailureState() }, ): TimelinePresenter { return TimelinePresenter( timelineItemsFactoryCreator = aTimelineItemsFactoryCreator(), @@ -1602,7 +1907,7 @@ class TimelinePresenterTest { sessionPreferencesStore = sessionPreferencesStore, timelineItemIndexer = timelineItemIndexer, timelineController = TimelineController(room, timeline), - resolveVerifiedUserSendFailurePresenter = { aResolveVerifiedUserSendFailureState() }, + resolveVerifiedUserSendFailurePresenter = resolveVerifiedUserSendFailurePresenter, typingNotificationPresenter = { aTypingNotificationState() }, roomCallStatePresenter = { aStandByCallState() }, featureFlagService = featureFlagService, diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelineViewTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelineViewTest.kt index bcddc37a74..ac84d48c95 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelineViewTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/TimelineViewTest.kt @@ -13,8 +13,12 @@ package io.element.android.features.messages.impl.timeline import androidx.activity.ComponentActivity import androidx.compose.ui.test.AndroidComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onFirst import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToIndex import androidx.compose.ui.test.v2.runAndroidComposeUiTest @@ -29,8 +33,15 @@ import io.element.android.features.messages.impl.timeline.protection.aTimelinePr import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.UniqueId import io.element.android.libraries.matrix.api.timeline.Timeline +import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState +import io.element.android.libraries.matrix.api.timeline.item.event.MessageContent import io.element.android.libraries.matrix.api.timeline.item.event.MessageShield +import io.element.android.libraries.matrix.api.timeline.item.event.TextMessageType import io.element.android.libraries.matrix.api.user.MatrixUser +import io.element.android.libraries.matrix.test.AN_EVENT_ID +import io.element.android.libraries.matrix.test.A_USER_ID +import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetails +import io.element.android.libraries.matrix.ui.messages.reply.aProfileDetailsReady import io.element.android.libraries.ui.strings.CommonStrings import io.element.android.tests.testutils.EnsureNeverCalledWithParam import io.element.android.tests.testutils.EnsureNeverCalledWithTwoParams @@ -168,6 +179,101 @@ class TimelineViewTest : RobolectricTest() { eventsRecorder.assertSingle(TimelineEvent.HideShieldDialog) } + @Test + fun `clicking on the send failure indicator emits the expected Event`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder() + val timelineItem = aTimelineItemEvent( + content = aTimelineItemTextContent(), + sendState = LocalEventSendState.Failed.Unknown("Error"), + ) + setTimelineView( + state = aTimelineState( + timelineItems = persistentListOf(timelineItem), + eventSink = eventsRecorder, + ), + ) + eventsRecorder.clear() + + val contentDescription = activity!!.getString(CommonStrings.common_sending_failed) + onNodeWithContentDescription(contentDescription).performClick() + eventsRecorder.assertSingle(TimelineEvent.ShowSendFailureDialog(timelineItem)) + } + + @Test + fun `clicking on the send failure indicator of a verified user failure emits the expected Event`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder() + val timelineItem = aTimelineItemEvent( + content = aTimelineItemTextContent(), + sendState = LocalEventSendState.Failed.VerifiedUserChangedIdentity(users = listOf(A_USER_ID)), + ) + setTimelineView( + state = aTimelineState( + timelineItems = persistentListOf(timelineItem), + eventSink = eventsRecorder, + ), + ) + eventsRecorder.clear() + + val contentDescription = activity!!.getString(CommonStrings.common_sending_failed) + onNodeWithContentDescription(contentDescription).performClick() + eventsRecorder.assertSingle(TimelineEvent.ShowSendFailureDialog(timelineItem)) + } + + @Test + fun `clicking on a reply to a loaded event emits the expected Event`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder() + setTimelineView( + state = aTimelineState( + timelineItems = persistentListOf( + aTimelineItemEvent( + content = aTimelineItemTextContent(), + inReplyTo = InReplyToDetails.Ready( + eventId = AN_EVENT_ID, + senderId = A_USER_ID, + senderProfile = aProfileDetailsReady(), + eventContent = MessageContent( + body = "Replied message", + inReplyTo = null, + isEdited = false, + threadInfo = null, + type = TextMessageType("Replied message", null), + ), + textContent = "Replied message", + ), + ), + ), + eventSink = eventsRecorder, + ), + ) + eventsRecorder.clear() + + onAllNodesWithText("Replied message").onFirst().performClick() + eventsRecorder.assertSingle(TimelineEvent.FocusOnEvent(AN_EVENT_ID)) + } + + @Test + fun `a reply to an event which could not be loaded renders a placeholder and does not emit any Event when clicked`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder() + setTimelineView( + state = aTimelineState( + timelineItems = persistentListOf( + aTimelineItemEvent( + content = aTimelineItemTextContent(), + inReplyTo = InReplyToDetails.Error(eventId = AN_EVENT_ID, message = "Failed to fetch the event"), + ), + ), + eventSink = eventsRecorder, + ), + onMessageClick = {}, + ) + eventsRecorder.assertSingle(TimelineEvent.OnScrollFinished(firstIndex = 0)) + eventsRecorder.clear() + + onNodeWithText("Failed to fetch the event").assertDoesNotExist() + onNodeWithText(activity!!.getString(CommonStrings.error_message_not_found)).assertIsDisplayed().performClick() + eventsRecorder.assertEmpty() + } + @Ignore( "performScrollToIndex in compose tests no longer sets LazyListState.isScrollInProgress to true, so the LoadMore event is not emitted." + "This needs to be reworked to use a different approach to check the LoadMore event was emitted." diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/components/customreaction/ExpandSheetWhenImeIsVisibleTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/components/customreaction/ExpandSheetWhenImeIsVisibleTest.kt new file mode 100644 index 0000000000..3f5805a0b4 --- /dev/null +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/components/customreaction/ExpandSheetWhenImeIsVisibleTest.kt @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalTestApi::class) + +package io.element.android.features.messages.impl.timeline.components.customreaction + +import android.view.View +import androidx.activity.ComponentActivity +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.SheetState +import androidx.compose.material3.SheetValue +import androidx.compose.material3.rememberBottomSheetState +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.test.AndroidComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.v2.runAndroidComposeUiTest +import androidx.core.graphics.Insets +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import com.google.common.truth.Truth.assertThat +import io.element.android.tests.testutils.robolectric.RobolectricTest +import org.junit.Test + +class ExpandSheetWhenImeIsVisibleTest : RobolectricTest() { + @Test + fun `the sheet is left alone while the keyboard is hidden`() = runAndroidComposeUiTest { + val sheetState = renderWithIme(isImeVisible = false) + assertThat(sheetState.currentValue).isEqualTo(SheetValue.PartiallyExpanded) + } + + @Test + fun `the sheet is expanded when the keyboard is shown`() = runAndroidComposeUiTest { + val sheetState = renderWithIme(isImeVisible = true) + assertThat(sheetState.currentValue).isEqualTo(SheetValue.Expanded) + } +} + +private fun AndroidComposeUiTest.renderWithIme(isImeVisible: Boolean): SheetState { + lateinit var sheetState: SheetState + lateinit var view: View + setContent { + view = LocalView.current + sheetState = rememberBottomSheetState(initialValue = SheetValue.PartiallyExpanded) + ExpandSheetWhenImeIsVisible(sheetState) + } + runOnIdle { + ViewCompat.dispatchApplyWindowInsets( + view, + WindowInsetsCompat.Builder() + .setVisible(WindowInsetsCompat.Type.ime(), isImeVisible) + .setInsets(WindowInsetsCompat.Type.ime(), if (isImeVisible) Insets.of(0, 0, 0, 300) else Insets.NONE) + .build() + ) + } + waitForIdle() + return sheetState +} diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/factories/TimelineItemsFactoryTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/factories/TimelineItemsFactoryTest.kt new file mode 100644 index 0000000000..f93c8f196e --- /dev/null +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/factories/TimelineItemsFactoryTest.kt @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.messages.impl.timeline.factories + +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import io.element.android.features.messages.impl.fixtures.aTimelineItemsFactory +import io.element.android.features.messages.impl.timeline.model.TimelineItem +import io.element.android.features.messages.impl.timeline.model.TimelineItemGroupPosition +import io.element.android.features.messages.impl.timeline.model.event.TimelineItemTextContent +import io.element.android.libraries.matrix.api.core.UniqueId +import io.element.android.libraries.matrix.api.timeline.MatrixTimelineItem +import io.element.android.libraries.matrix.api.timeline.item.event.OtherMessageType +import io.element.android.libraries.matrix.test.A_USER_ID +import io.element.android.libraries.matrix.test.timeline.aMessageContent +import io.element.android.libraries.matrix.test.timeline.anEventTimelineItem +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import org.junit.Test + +class TimelineItemsFactoryTest { + @Test + fun `messages sent close together are grouped`() = runTest { + val positions = groupPositionsOf( + timestamps = listOf(0L, ONE_MINUTE, 2 * ONE_MINUTE), + ) + assertThat(positions).containsExactly( + TimelineItemGroupPosition.First, + TimelineItemGroupPosition.Middle, + TimelineItemGroupPosition.Last, + ).inOrder() + } + + @Test + fun `messages sent more than five minutes apart are not grouped`() = runTest { + val positions = groupPositionsOf( + timestamps = listOf(0L, 6 * ONE_MINUTE, 12 * ONE_MINUTE), + ) + assertThat(positions).containsExactly( + TimelineItemGroupPosition.None, + TimelineItemGroupPosition.None, + TimelineItemGroupPosition.None, + ).inOrder() + } + + @Test + fun `a gap of more than five minutes splits the group`() = runTest { + val positions = groupPositionsOf( + timestamps = listOf(0L, ONE_MINUTE, 8 * ONE_MINUTE, 9 * ONE_MINUTE), + ) + assertThat(positions).containsExactly( + TimelineItemGroupPosition.First, + TimelineItemGroupPosition.Last, + TimelineItemGroupPosition.First, + TimelineItemGroupPosition.Last, + ).inOrder() + } + + @Test + fun `a gap of exactly five minutes still groups`() = runTest { + val positions = groupPositionsOf( + timestamps = listOf(0L, FIVE_MINUTES), + ) + assertThat(positions).containsExactly( + TimelineItemGroupPosition.First, + TimelineItemGroupPosition.Last, + ).inOrder() + } + + @Test + fun `messages with the same timestamp are grouped`() = runTest { + val positions = groupPositionsOf( + timestamps = listOf(0L, 0L, 0L), + ) + assertThat(positions).containsExactly( + TimelineItemGroupPosition.First, + TimelineItemGroupPosition.Middle, + TimelineItemGroupPosition.Last, + ).inOrder() + } + + @Test + fun `a key verification request is not rendered`() = runTest { + val factory = aTimelineItemsFactory( + config = TimelineItemsFactoryConfig( + computeReadReceipts = false, + computeReactions = false, + ) + ) + val items = listOf( + MatrixTimelineItem.Event( + uniqueId = UniqueId("event-0"), + event = anEventTimelineItem( + sender = A_USER_ID, + content = aMessageContent( + body = "Alice is requesting to verify your key, but your client does not support in-chat key verification.", + messageType = OtherMessageType( + msgType = "m.key.verification.request", + body = "Alice is requesting to verify your key, but your client does not support in-chat key verification.", + ), + ), + ), + ), + MatrixTimelineItem.Event( + uniqueId = UniqueId("event-1"), + event = anEventTimelineItem( + sender = A_USER_ID, + content = aMessageContent(body = "A regular message"), + ), + ), + ) + factory.timelineItems.test { + factory.replaceWith( + timelineItems = items, + roomMembers = emptyList(), + renderReadReceipts = false, + ) + val bodies = awaitItem() + .filterIsInstance() + .map { (it.content as TimelineItemTextContent).body } + assertThat(bodies).containsExactly("A regular message") + cancelAndIgnoreRemainingEvents() + } + } + + private suspend fun TestScope.groupPositionsOf(timestamps: List): List { + val factory = aTimelineItemsFactory( + config = TimelineItemsFactoryConfig( + computeReadReceipts = false, + computeReactions = false, + ) + ) + val items = timestamps.mapIndexed { index, timestamp -> + MatrixTimelineItem.Event( + uniqueId = UniqueId("event-$index"), + event = anEventTimelineItem( + sender = A_USER_ID, + timestamp = timestamp, + content = aMessageContent(body = "Message $index"), + ), + ) + } + var positions: List = emptyList() + factory.timelineItems.test { + factory.replaceWith( + timelineItems = items, + roomMembers = emptyList(), + renderReadReceipts = false, + ) + positions = awaitItem() + .filterIsInstance() + .map { it.groupPosition } + .reversed() + cancelAndIgnoreRemainingEvents() + } + return positions + } + + private companion object { + const val ONE_MINUTE = 60 * 1000L + const val FIVE_MINUTES = 5 * ONE_MINUTE + } +} diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogViewTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogViewTest.kt new file mode 100644 index 0000000000..05388e7227 --- /dev/null +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/timeline/sendfailure/SendFailureDialogViewTest.kt @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +@file:OptIn(ExperimentalTestApi::class) + +package io.element.android.features.messages.impl.timeline.sendfailure + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.AndroidComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.v2.runAndroidComposeUiTest +import io.element.android.features.messages.impl.R +import io.element.android.features.messages.impl.timeline.aTimelineItemEvent +import io.element.android.features.messages.impl.timeline.model.TimelineItem +import io.element.android.libraries.matrix.api.timeline.item.event.LocalEventSendState +import io.element.android.libraries.ui.strings.CommonStrings +import io.element.android.tests.testutils.EnsureNeverCalled +import io.element.android.tests.testutils.EnsureNeverCalledWithParam +import io.element.android.tests.testutils.assertNodeWithTextIsDisplayed +import io.element.android.tests.testutils.clickOn +import io.element.android.tests.testutils.ensureCalledOnce +import io.element.android.tests.testutils.ensureCalledOnceWithParam +import io.element.android.tests.testutils.robolectric.RobolectricTest +import io.element.android.tests.testutils.setSafeContent +import org.junit.Test + +class SendFailureDialogViewTest : RobolectricTest() { + @Test + fun `hidden state renders nothing`() = runAndroidComposeUiTest { + setSendFailureDialogView( + sendFailureDialogState = SendFailureDialogState.Hidden, + ) + onNodeWithText(activity!!.getString(CommonStrings.common_sending_failed)).assertDoesNotExist() + } + + @Test + fun `show state renders the error failure reason`() = runAndroidComposeUiTest { + setSendFailureDialogView( + sendFailureDialogState = aSendFailureDialogStateShow( + sendFailureType = SendFailureDialogState.SendFailureType.Error("A failure reason"), + ), + ) + assertNodeWithTextIsDisplayed(CommonStrings.common_sending_failed) + onNodeWithText(activity!!.getString(R.string.error_sending_failure_other, "A failure reason")).assertExists() + } + + @Test + fun `show state renders the invalid mime type failure reason`() = runAndroidComposeUiTest { + setSendFailureDialogView( + sendFailureDialogState = aSendFailureDialogStateShow( + sendFailureType = SendFailureDialogState.SendFailureType.InvalidMimeType("invalid/mimeType"), + ), + ) + onNodeWithText(activity!!.getString(R.string.error_sending_failure_invalid_mime_type, "invalid/mimeType")).assertExists() + } + + @Test + fun `show state renders the missing media content failure reason`() = runAndroidComposeUiTest { + setSendFailureDialogView( + sendFailureDialogState = aSendFailureDialogStateShow( + sendFailureType = SendFailureDialogState.SendFailureType.MissingMediaContent, + ), + ) + onNodeWithText(activity!!.getString(R.string.error_sending_failure_missing_media_content)).assertExists() + } + + @Test + fun `show state renders the sending from unverified device failure reason`() = runAndroidComposeUiTest { + setSendFailureDialogView( + sendFailureDialogState = aSendFailureDialogStateShow( + sendFailureType = SendFailureDialogState.SendFailureType.SendingFromUnverifiedDevice, + ), + ) + onNodeWithText(activity!!.getString(R.string.error_sending_failure_sending_from_unverified_device)).assertExists() + } + + @Test + fun `show state renders the unknown failure reason`() = runAndroidComposeUiTest { + setSendFailureDialogView( + sendFailureDialogState = aSendFailureDialogStateShow( + sendFailureType = SendFailureDialogState.SendFailureType.Unknown, + ), + ) + onNodeWithText(activity!!.getString(R.string.error_sending_failure_unknown)).assertExists() + } + + @Test + fun `clicking on retry invokes the expected callback`() = runAndroidComposeUiTest { + val state = aSendFailureDialogStateShow() + ensureCalledOnceWithParam(state.event) { callback -> + setSendFailureDialogView( + sendFailureDialogState = state, + onRetry = callback, + ) + clickOn(CommonStrings.action_retry) + } + } + + @Test + fun `clicking on remove message invokes the expected callback`() = runAndroidComposeUiTest { + val state = aSendFailureDialogStateShow() + ensureCalledOnceWithParam(state.event) { callback -> + setSendFailureDialogView( + sendFailureDialogState = state, + onRemoveMessage = callback, + ) + clickOn(CommonStrings.action_remove_message) + } + } + + @Test + fun `clicking on cancel invokes the expected callback`() = runAndroidComposeUiTest { + ensureCalledOnce { callback -> + setSendFailureDialogView( + sendFailureDialogState = aSendFailureDialogStateShow(), + onDismiss = callback, + ) + clickOn(CommonStrings.action_cancel) + } + } + + private fun aSendFailureDialogStateShow( + sendFailureType: SendFailureDialogState.SendFailureType = SendFailureDialogState.SendFailureType.Unknown, + ) = SendFailureDialogState.Show( + event = aTimelineItemEvent(sendState = LocalEventSendState.Failed.Unknown("")), + sendFailureType = sendFailureType, + ) + + private fun AndroidComposeUiTest.setSendFailureDialogView( + sendFailureDialogState: SendFailureDialogState, + onDismiss: () -> Unit = EnsureNeverCalled(), + onRetry: (TimelineItem.Event) -> Unit = EnsureNeverCalledWithParam(), + onRemoveMessage: (TimelineItem.Event) -> Unit = EnsureNeverCalledWithParam(), + ) { + setSafeContent { + SendFailureDialogView( + sendFailureDialogState = sendFailureDialogState, + onDismiss = onDismiss, + onRetry = onRetry, + onRemoveMessage = onRemoveMessage, + ) + } + } +} diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/utils/DefaultTextPillificationHelperTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/utils/DefaultTextPillificationHelperTest.kt index 6390c2ba48..2590c9fc5c 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/utils/DefaultTextPillificationHelperTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/utils/DefaultTextPillificationHelperTest.kt @@ -9,6 +9,9 @@ package io.element.android.features.messages.impl.utils import android.net.Uri +import android.text.Spanned +import android.text.style.URLSpan +import androidx.core.text.getSpans import com.google.common.truth.Truth.assertThat import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomAlias @@ -30,6 +33,75 @@ import io.element.android.tests.testutils.robolectric.RobolectricTest import org.junit.Test class DefaultTextPillificationHelperTest : RobolectricTest() { + @Test + fun `pillify - adds pills for matrix uri user links`() { + val text = "Hello matrix:u/someone:example.com" + val userId = UserId("@someone:example.com") + val helper = aTextPillificationHelper( + permalinkParser = FakePermalinkParser(result = { PermalinkData.UserLink(userId) }), + permalinkBuilder = FakePermalinkBuilder(permalinkForUserLambda = { + Result.success("https://matrix.to/#/@someone:example.com") + }), + ) + val pillified = helper.pillify(text) + val mentionSpans = pillified.getMentionSpans() + assertThat(mentionSpans).hasSize(1) + assertThat(mentionSpans.first().type).isInstanceOf(MentionType.User::class.java) + val spanned = pillified as Spanned + assertThat(spanned.getSpanStart(mentionSpans.first())).isEqualTo(text.indexOf("matrix:")) + assertThat(spanned.getSpanEnd(mentionSpans.first())).isEqualTo(text.length) + val urlSpans = spanned.getSpans(0, spanned.length) + assertThat(urlSpans).hasLength(1) + assertThat(urlSpans.first().url).isEqualTo("matrix:u/someone:example.com") + } + + @Test + fun `pillify - adds pills for matrix uri room links`() { + val text = "Join matrix:r/room:example.com now" + val roomAlias = RoomAlias("#room:example.com") + val helper = aTextPillificationHelper( + permalinkParser = FakePermalinkParser(result = { + PermalinkData.RoomLink(roomIdOrAlias = roomAlias.toRoomIdOrAlias()) + }), + permalinkBuilder = FakePermalinkBuilder(permalinkForRoomAliasLambda = { + Result.success("https://matrix.to/#/#room:example.com") + }), + ) + val mentionSpans = helper.pillify(text).getMentionSpans() + assertThat(mentionSpans).hasSize(1) + assertThat(mentionSpans.first().type).isInstanceOf(MentionType.Room::class.java) + } + + @Test + fun `pillify - a matrix uri does not swallow trailing punctuation`() { + val text = "See matrix:u/someone:example.com." + val userId = UserId("@someone:example.com") + val helper = aTextPillificationHelper( + permalinkParser = FakePermalinkParser(result = { PermalinkData.UserLink(userId) }), + permalinkBuilder = FakePermalinkBuilder(permalinkForUserLambda = { + Result.success("https://matrix.to/#/@someone:example.com") + }), + ) + val pillified = helper.pillify(text) + val mentionSpans = pillified.getMentionSpans() + assertThat(mentionSpans).hasSize(1) + assertThat((pillified as Spanned).getSpanEnd(mentionSpans.first())).isEqualTo(text.length - 1) + } + + @Test + fun `pillify - does not pillify matrix uris when permalinks are disabled`() { + val text = "Hello matrix:u/someone:example.com" + val userId = UserId("@someone:example.com") + val helper = aTextPillificationHelper( + permalinkParser = FakePermalinkParser(result = { PermalinkData.UserLink(userId) }), + permalinkBuilder = FakePermalinkBuilder(permalinkForUserLambda = { + Result.success("https://matrix.to/#/@someone:example.com") + }), + ) + val pillified = helper.pillify(text, pillifyPermalinks = false) + assertThat(pillified.getMentionSpans()).isEmpty() + } + @Test fun `pillify - adds pills for user ids`() { val text = "A @user:server.com" diff --git a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/voicemessages/composer/DefaultVoiceMessageComposerPresenterTest.kt b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/voicemessages/composer/DefaultVoiceMessageComposerPresenterTest.kt index 7d3b6cf647..fb44bb4e80 100644 --- a/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/voicemessages/composer/DefaultVoiceMessageComposerPresenterTest.kt +++ b/features/messages/impl/src/test/kotlin/io/element/android/features/messages/impl/voicemessages/composer/DefaultVoiceMessageComposerPresenterTest.kt @@ -60,6 +60,7 @@ import org.junit.Rule import org.junit.Test import java.io.File import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds @Suppress("LargeClass") @@ -67,8 +68,14 @@ class DefaultVoiceMessageComposerPresenterTest { @get:Rule val warmUpRule = WarmUpRule() + private val startRecordResult = lambdaRecorder { } + private val stopRecordResult = lambdaRecorder { } + private val deleteRecordingResult = lambdaRecorder { } private val voiceRecorder = FakeVoiceRecorder( - recordingDuration = RECORDING_DURATION + recordingDuration = RECORDING_DURATION, + startRecordResult = startRecordResult, + stopRecordResult = stopRecordResult, + deleteRecordingResult = deleteRecordingResult, ) private val analyticsService = FakeAnalyticsService() private val sendVoiceMessageResult = @@ -97,7 +104,9 @@ class DefaultVoiceMessageComposerPresenterTest { companion object { private val RECORDING_DURATION = 1.seconds + private val FIRST_LEVEL_DURATION = 500.milliseconds private val RECORDING_STATE = VoiceMessageState.Recording(RECORDING_DURATION, listOf(0.1f, 0.2f).toImmutableList()) + private val FIRST_RECORDING_STATE = VoiceMessageState.Recording(FIRST_LEVEL_DURATION, listOf(0.1f).toImmutableList()) } @Test @@ -106,7 +115,7 @@ class DefaultVoiceMessageComposerPresenterTest { presenter.test { val initialState = awaitItem() assertThat(initialState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) - voiceRecorder.assertCalls(started = 0) + startRecordResult.assertions().isNeverCalled() testPauseAndDestroy(initialState) } @@ -118,9 +127,10 @@ class DefaultVoiceMessageComposerPresenterTest { presenter.test { awaitItem().eventSink(VoiceMessageComposerEvent.RecorderEvent(VoiceMessageRecorderEvent.Start)) + assertThat(awaitItem().voiceMessageState).isEqualTo(FIRST_RECORDING_STATE) val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(RECORDING_STATE) - voiceRecorder.assertCalls(started = 1) + startRecordResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -133,13 +143,18 @@ class DefaultVoiceMessageComposerPresenterTest { val voiceRecorder = FakeVoiceRecorder( levels = levels, recordingDuration = RECORDING_DURATION, + startRecordResult = { }, + stopRecordResult = { }, + deleteRecordingResult = { }, ) val presenter = createDefaultVoiceMessageComposerPresenter( voiceRecorder = voiceRecorder, ) presenter.test { awaitItem().eventSink(VoiceMessageComposerEvent.RecorderEvent(VoiceMessageRecorderEvent.Start)) - skipItems(numberOfLevels / 2 - 1) + + // Skip until we reach the final state, which should have the last 128 levels + skipItems(numberOfLevels - 1) val finalState = awaitItem() assertThat(finalState.voiceMessageState).isInstanceOf(VoiceMessageState.Recording::class.java) val recordingState = finalState.voiceMessageState as VoiceMessageState.Recording @@ -221,7 +236,8 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(aPreviewState()) - voiceRecorder.assertCalls(started = 1, stopped = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) cancelAndIgnoreRemainingEvents() } @@ -235,7 +251,9 @@ class DefaultVoiceMessageComposerPresenterTest { awaitItem().eventSink(VoiceMessageComposerEvent.RecorderEvent(VoiceMessageRecorderEvent.Cancel)) val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(true)) + deleteRecordingResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } } @@ -249,7 +267,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(aPreviewState()) - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 0) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isNeverCalled() testPauseAndDestroy(finalState) } @@ -265,8 +285,10 @@ class DefaultVoiceMessageComposerPresenterTest { } // Nothing should happen - assertThat(finalState.voiceMessageState).isEqualTo(RECORDING_STATE) - voiceRecorder.assertCalls(started = 1, stopped = 0, deleted = 0) + assertThat(finalState.voiceMessageState).isEqualTo(FIRST_RECORDING_STATE) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isNeverCalled() + deleteRecordingResult.assertions().isNeverCalled() testPauseAndDestroy(finalState) } @@ -282,7 +304,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem().also { assertThat(it.voiceMessageState).isEqualTo(aPlayingState()) } - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 0) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isNeverCalled() testPauseAndDestroy(finalState) } @@ -299,7 +323,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem().also { assertThat(it.voiceMessageState).isEqualTo(aPausedState()) } - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 0) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isNeverCalled() testPauseAndDestroy(finalState) } @@ -340,7 +366,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -360,7 +388,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -377,7 +407,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) sendVoiceMessageResult.assertions().isCalledOnce() - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -455,7 +487,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) sendVoiceMessageResult.assertions().isCalledOnce() - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -476,7 +510,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) sendVoiceMessageResult.assertions().isCalledOnce() - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -499,7 +535,9 @@ class DefaultVoiceMessageComposerPresenterTest { assertThat(finalState.voiceMessageState).isEqualTo(aPreviewState(isSending = true)) sendVoiceMessageResult.assertions().isNeverCalled() assertThat(analyticsService.trackedErrors).isEmpty() - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 0) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isNeverCalled() testPauseAndDestroy(finalState) } @@ -527,7 +565,9 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = awaitItem() assertThat(finalState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) sendVoiceMessageResult.assertions().isCalledOnce() - voiceRecorder.assertCalls(started = 1, stopped = 1, deleted = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) + deleteRecordingResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -577,7 +617,7 @@ class DefaultVoiceMessageComposerPresenterTest { assertThat(initialState.voiceMessageState).isEqualTo(VoiceMessageState.Idle) sendVoiceMessageResult.assertions().isNeverCalled() assertThat(analyticsService.trackedErrors).hasSize(1) - voiceRecorder.assertCalls(started = 0) + startRecordResult.assertions().isNeverCalled() testPauseAndDestroy(initialState) } @@ -586,8 +626,14 @@ class DefaultVoiceMessageComposerPresenterTest { @Test fun `present - record error - security exceptions are tracked`() = runTest { val exception = SecurityException("") - voiceRecorder.givenThrowsSecurityException(exception) - val presenter = createDefaultVoiceMessageComposerPresenter() + val startRecordResult = lambdaRecorder { throw exception } + val voiceRecorder = FakeVoiceRecorder( + recordingDuration = RECORDING_DURATION, + startRecordResult = startRecordResult, + ) + val presenter = createDefaultVoiceMessageComposerPresenter( + voiceRecorder = voiceRecorder, + ) presenter.test { val initialState = awaitItem() initialState.eventSink(VoiceMessageComposerEvent.RecorderEvent(VoiceMessageRecorderEvent.Start)) @@ -596,7 +642,7 @@ class DefaultVoiceMessageComposerPresenterTest { assertThat(analyticsService.trackedErrors).containsExactly( VoiceMessageException.PermissionMissing(message = "Expected permission to record but none", cause = exception) ) - voiceRecorder.assertCalls(started = 1) + startRecordResult.assertions().isCalledOnce() testPauseAndDestroy(initialState) } @@ -616,7 +662,8 @@ class DefaultVoiceMessageComposerPresenterTest { assertThat(awaitItem().voiceMessageState).isEqualTo(VoiceMessageState.Idle) initialState.eventSink(VoiceMessageComposerEvent.RecorderEvent(VoiceMessageRecorderEvent.Stop)) - voiceRecorder.assertCalls(stopped = 1) + startRecordResult.assertions().isNeverCalled() + stopRecordResult.assertions().isCalledOnce().with(value(false)) permissionsPresenter.setPermissionGranted() @@ -625,7 +672,8 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = expectMostRecentItem() assertThat(finalState.voiceMessageState).isEqualTo(RECORDING_STATE) - voiceRecorder.assertCalls(stopped = 1, started = 1) + startRecordResult.assertions().isCalledOnce() + stopRecordResult.assertions().isCalledOnce().with(value(false)) testPauseAndDestroy(finalState) } @@ -659,7 +707,7 @@ class DefaultVoiceMessageComposerPresenterTest { val finalState = expectMostRecentItem() assertThat(finalState.voiceMessageState).isEqualTo(RECORDING_STATE) - voiceRecorder.assertCalls(started = 1) + startRecordResult.assertions().isCalledOnce() testPauseAndDestroy(finalState) } @@ -696,7 +744,7 @@ class DefaultVoiceMessageComposerPresenterTest { assertThat(it.voiceMessageState).isEqualTo(VoiceMessageState.Idle) assertThat(it.showPermissionRationaleDialog).isTrue() } - voiceRecorder.assertCalls(started = 0) + startRecordResult.assertions().isNeverCalled() cancelAndIgnoreRemainingEvents() testPauseAndDestroy(finalState) diff --git a/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationStateProvider.kt b/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationStatePreviewParam.kt similarity index 90% rename from features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationStateProvider.kt rename to features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationStatePreviewParam.kt index 8f738d3207..de25284867 100644 --- a/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationStateProvider.kt +++ b/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.api.MigrationState import io.element.android.libraries.architecture.AsyncData -internal class MigrationStateProvider : PreviewParameterProvider { +internal class MigrationStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMigrationState(), diff --git a/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationView.kt b/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationView.kt index a294c32534..c7f4dd678a 100644 --- a/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationView.kt +++ b/features/migration/impl/src/main/kotlin/io/element/android/features/migration/impl/MigrationView.kt @@ -49,7 +49,7 @@ fun MigrationView( @PreviewsDayNight @Composable internal fun MigrationViewPreview( - @PreviewParameter(MigrationStateProvider::class) state: MigrationState, + @PreviewParameter(MigrationStatePreviewParam::class) state: MigrationState, ) = ElementPreview { MigrationView( migrationState = state, diff --git a/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/EndPollAction.kt b/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/EndPollAction.kt index a46a2db781..b33a00c165 100644 --- a/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/EndPollAction.kt +++ b/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/EndPollAction.kt @@ -11,6 +11,13 @@ package io.element.android.features.poll.api.actions import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.timeline.Timeline +/** + * Closes a poll so no further answers are accepted, wrapping the timeline call so the analytics are captured in one place. + */ interface EndPollAction { + /** + * @param timeline the timeline the poll lives in. + * @param pollStartId the poll start event to close. + */ suspend fun execute(timeline: Timeline, pollStartId: EventId): Result } diff --git a/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/SendPollResponseAction.kt b/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/SendPollResponseAction.kt index ac70718c57..6cfc46a754 100644 --- a/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/SendPollResponseAction.kt +++ b/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/actions/SendPollResponseAction.kt @@ -11,7 +11,15 @@ package io.element.android.features.poll.api.actions import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.timeline.Timeline +/** + * Sends the current user's answer to a poll, wrapping the timeline call so the analytics are captured in one place. + */ interface SendPollResponseAction { + /** + * @param timeline the timeline the poll lives in. + * @param pollStartId the poll start event being answered. + * @param answerId the id of the chosen answer. + */ suspend fun execute( timeline: Timeline, pollStartId: EventId, diff --git a/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/pollcontent/PollContentStateFactory.kt b/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/pollcontent/PollContentStateFactory.kt index c9bd31ea4f..f9b4a56efc 100644 --- a/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/pollcontent/PollContentStateFactory.kt +++ b/features/poll/api/src/main/kotlin/io/element/android/features/poll/api/pollcontent/PollContentStateFactory.kt @@ -12,7 +12,16 @@ import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.timeline.item.event.EventTimelineItem import io.element.android.libraries.matrix.api.timeline.item.event.PollContent +/** + * Turns the poll content of a timeline event into the state the poll UI renders. + */ interface PollContentStateFactory { + /** + * Convenience overload that reads the editability and ownership from the timeline item itself. + * + * @param eventTimelineItem the timeline item carrying the poll. + * @param content the poll content of that item. + */ suspend fun create(eventTimelineItem: EventTimelineItem, content: PollContent): PollContentState { return create( eventId = eventTimelineItem.eventId, @@ -21,5 +30,12 @@ interface PollContentStateFactory { content = content, ) } + + /** + * @param eventId the poll start event, or `null` while the poll is still a local echo. + * @param isEditable whether the current user may still edit the poll. + * @param isOwn whether the poll was created by the current user. + * @param content the poll question, answers and votes. + */ suspend fun create(eventId: EventId?, isEditable: Boolean, isOwn: Boolean, content: PollContent): PollContentState } diff --git a/features/poll/api/src/main/res/values-ar/translations.xml b/features/poll/api/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..e55d1c8710 --- /dev/null +++ b/features/poll/api/src/main/res/values-ar/translations.xml @@ -0,0 +1,13 @@ + + + + "%1$d بالمئة من إجمالي الأصوات" + "%1$d بالمئة من إجمالي الأصوات" + "%1$d بالمئة من إجمالي الأصوات" + "%1$d بالمئة من إجمالي الأصوات" + "%1$d بالمئة من إجمالي الأصوات" + "%1$d بالمئة من إجمالي الأصوات" + + "ٍسيتم حذف الإختيار السابق" + "هذه هي الإجابة الفائزة" + diff --git a/features/poll/api/src/main/res/values-es/translations.xml b/features/poll/api/src/main/res/values-es/translations.xml index 10e1193163..b69a550320 100644 --- a/features/poll/api/src/main/res/values-es/translations.xml +++ b/features/poll/api/src/main/res/values-es/translations.xml @@ -1,4 +1,9 @@ + + "%1$d por ciento de todos los votos" + "%1$d por ciento de todos los votos" + + "Eliminará la selección anterior" "Esta es la respuesta ganadora" diff --git a/features/poll/api/src/main/res/values-fa/translations.xml b/features/poll/api/src/main/res/values-fa/translations.xml index af9620c7e8..1885c72e1b 100644 --- a/features/poll/api/src/main/res/values-fa/translations.xml +++ b/features/poll/api/src/main/res/values-fa/translations.xml @@ -1,5 +1,9 @@ + + "درصد %1$d از کل آرا" + "درصد %1$d از کل آرا" + "گزینش پیشین را برخواهد داشت" "این پاسخ برنده است" diff --git a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollStateProvider.kt b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollStatePreviewParam.kt similarity index 99% rename from features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollStateProvider.kt rename to features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollStatePreviewParam.kt index 13c1ca0a50..793f415828 100644 --- a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollStateProvider.kt +++ b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.matrix.api.poll.PollKind import kotlinx.collections.immutable.toImmutableList -class CreatePollStateProvider : PreviewParameterProvider { +class CreatePollStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aCreatePollState( diff --git a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollView.kt b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollView.kt index 9800af5b88..602466b582 100644 --- a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollView.kt +++ b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/create/CreatePollView.kt @@ -294,7 +294,7 @@ private fun MaxSelectionsStepper( @PreviewsDayNight @Composable internal fun CreatePollViewPreview( - @PreviewParameter(CreatePollStateProvider::class) state: CreatePollState + @PreviewParameter(CreatePollStatePreviewParam::class) state: CreatePollState ) = ElementPreview { CreatePollView( state = state, diff --git a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryStateProvider.kt b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryStatePreviewParam.kt similarity index 96% rename from features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryStateProvider.kt rename to features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryStatePreviewParam.kt index a08550f2a1..ff07eaee37 100644 --- a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryStateProvider.kt +++ b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.features.poll.impl.history.model.PollHistoryItem import io.element.android.features.poll.impl.history.model.PollHistoryItems import kotlinx.collections.immutable.toImmutableList -class PollHistoryStateProvider : PreviewParameterProvider { +class PollHistoryStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aPollHistoryState(), diff --git a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryView.kt b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryView.kt index 0210f1efcb..87b9b0dca3 100644 --- a/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryView.kt +++ b/features/poll/impl/src/main/kotlin/io/element/android/features/poll/impl/history/PollHistoryView.kt @@ -255,7 +255,7 @@ private fun PollHistoryItemRow( @PreviewsDayNight @Composable internal fun PollHistoryViewPreview( - @PreviewParameter(PollHistoryStateProvider::class) state: PollHistoryState + @PreviewParameter(PollHistoryStatePreviewParam::class) state: PollHistoryState ) = ElementPreview { PollHistoryView( state = state, diff --git a/features/poll/impl/src/main/res/values-ar/translations.xml b/features/poll/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..02c12f72d8 --- /dev/null +++ b/features/poll/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,20 @@ + + + "إضافة خيار" + "أظهر النتائج فقط حين انتهاء الاستفتاء" + "إخفاء الأصوات" + "الخيار %1$d" + "لم تُحفظ تغييراتك. هل أنت متأكد من أنك تريد الرجوع؟" + "حذف الخيار %1$s" + "السؤال أو الموضوع" + "عن ماذا يدور هذا الاستفتاء؟" + "إنشاء استفتاء" + "هل أنت متأكد من رغبتك في حذف هذا الاستطلاع؟" + "حذف الاستطلاع" + "تعديل الاستفتاء" + "تعذّر العثور على أي استطلاعات جارية." + "تعذّر العثور على أي استطلاعات مغلقة." + "جارية" + "مغلقة" + "الاستطلاعات" + diff --git a/features/poll/impl/src/main/res/values-fa/translations.xml b/features/poll/impl/src/main/res/values-fa/translations.xml index eeedc6c7a0..fd6469a389 100644 --- a/features/poll/impl/src/main/res/values-fa/translations.xml +++ b/features/poll/impl/src/main/res/values-fa/translations.xml @@ -5,6 +5,7 @@ "نهفتن رأی‌ها" "گزینهٔ %1$d" "تغییراتتان ذخیره نشده‌اند. مطمئنید که می‌خواهید برگردید؟" + "حذف گزینه %1$s" "پرسش یا موضوع" "این نظرسنجی دربارهٔ چیست؟" "ایجاد نظرسنجی" diff --git a/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/CacheService.kt b/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/CacheService.kt index 82fcd1053f..9dc3eb1877 100644 --- a/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/CacheService.kt +++ b/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/CacheService.kt @@ -11,6 +11,9 @@ package io.element.android.features.preferences.api import io.element.android.libraries.matrix.api.core.SessionId import kotlinx.coroutines.flow.Flow +/** + * Announces that a session's cache has been cleared, since clearing it destroys the client and the app has to react. + */ interface CacheService { /** * A flow of [SessionId], can let the app to know when the diff --git a/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/ExtraDeveloperOptionsRenderer.kt b/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/ExtraDeveloperOptionsRenderer.kt index 7d7eec9d8b..3acb2c9057 100644 --- a/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/ExtraDeveloperOptionsRenderer.kt +++ b/features/preferences/api/src/main/kotlin/io/element/android/features/preferences/api/ExtraDeveloperOptionsRenderer.kt @@ -14,6 +14,11 @@ import androidx.compose.ui.Modifier * Component for rendering extra developer options in the preferences screen. */ interface ExtraDeveloperOptionsRenderer { + /** + * Draws the extra options. The standard build binds a no-op implementation, so only the builds that actually add options provide a real one. + * + * @param modifier layout modifier for the container. + */ @Composable fun Render(modifier: Modifier) } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutStatePreviewParam.kt similarity index 90% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutStatePreviewParam.kt index 561fe53a49..a15a457302 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.preferences.impl.about import androidx.compose.ui.tooling.preview.PreviewParameterProvider import kotlinx.collections.immutable.toImmutableList -open class AboutStateProvider : PreviewParameterProvider { +open class AboutStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAboutState(), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutView.kt index 3a6671f692..79a17b3e5a 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/about/AboutView.kt @@ -51,7 +51,7 @@ fun AboutView( @PreviewsDayNight @Composable -internal fun AboutViewPreview(@PreviewParameter(AboutStateProvider::class) state: AboutState) = ElementPreview { +internal fun AboutViewPreview(@PreviewParameter(AboutStatePreviewParam::class) state: AboutState) = ElementPreview { AboutView( state = state, onElementLegalClick = {}, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsStatePreviewParam.kt similarity index 96% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsStatePreviewParam.kt index 2df59e3ced..c41df427cc 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.preferences.api.store.VideoCompressionPreset import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList -open class AdvancedSettingsStateProvider : PreviewParameterProvider { +open class AdvancedSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aAdvancedSettingsState(), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsView.kt index 438b20049a..de6ce5c9f6 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/advanced/AdvancedSettingsView.kt @@ -410,17 +410,17 @@ private fun LiveLocationUpdatesSection( @PreviewWithLargeHeight @Composable -internal fun AdvancedSettingsViewLightPreview(@PreviewParameter(AdvancedSettingsStateProvider::class) state: AdvancedSettingsState) = +internal fun AdvancedSettingsViewLightPreview(@PreviewParameter(AdvancedSettingsStatePreviewParam::class) state: AdvancedSettingsState) = ElementPreviewLight { ContentToPreview(state) } @PreviewWithLargeHeight @Composable -internal fun AdvancedSettingsViewDarkPreview(@PreviewParameter(AdvancedSettingsStateProvider::class) state: AdvancedSettingsState) = +internal fun AdvancedSettingsViewDarkPreview(@PreviewParameter(AdvancedSettingsStatePreviewParam::class) state: AdvancedSettingsState) = ElementPreviewDark { ContentToPreview(state) } @PreviewWithLargeHeight @Composable -internal fun AdvancedSettingsViewBlackPreview(@PreviewParameter(AdvancedSettingsStateProvider::class) state: AdvancedSettingsState) = +internal fun AdvancedSettingsViewBlackPreview(@PreviewParameter(AdvancedSettingsStatePreviewParam::class) state: AdvancedSettingsState) = ElementPreviewBlack { ContentToPreview(state) } @ExcludeFromCoverage diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsStatePreviewParam.kt similarity index 87% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsStatePreviewParam.kt index 9e15ea2f35..ab7a8aae3d 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.preferences.impl.analytics import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.analytics.api.preferences.aAnalyticsPreferencesState -open class AnalyticsSettingsStateProvider : PreviewParameterProvider { +open class AnalyticsSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aAnalyticsSettingsState(), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsView.kt index ef84600e2e..61fc3216f2 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsView.kt @@ -37,7 +37,7 @@ fun AnalyticsSettingsView( @PreviewsDayNight @Composable -internal fun AnalyticsSettingsViewPreview(@PreviewParameter(AnalyticsSettingsStateProvider::class) state: AnalyticsSettingsState) = ElementPreview { +internal fun AnalyticsSettingsViewPreview(@PreviewParameter(AnalyticsSettingsStatePreviewParam::class) state: AnalyticsSettingsState) = ElementPreview { AnalyticsSettingsView( state = state, onBackClick = {}, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersEvents.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersEvents.kt index 0db5c4c576..31e516e730 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersEvents.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersEvents.kt @@ -12,6 +12,7 @@ import io.element.android.libraries.matrix.api.core.UserId sealed interface BlockedUsersEvents { data class Unblock(val userId: UserId) : BlockedUsersEvents + data class CopyToClipboard(val userId: UserId) : BlockedUsersEvents data object ConfirmUnblock : BlockedUsersEvents data object Cancel : BlockedUsersEvents } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenter.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenter.kt index fc150d0bfc..2944089fa1 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenter.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenter.kt @@ -18,14 +18,19 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import dev.zacsweers.metro.Inject +import io.element.android.libraries.androidutils.clipboard.ClipboardHelper import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.architecture.runUpdatingState +import io.element.android.libraries.designsystem.utils.snackbar.SnackbarDispatcher +import io.element.android.libraries.designsystem.utils.snackbar.SnackbarMessage +import io.element.android.libraries.designsystem.utils.snackbar.collectSnackbarMessageAsState import io.element.android.libraries.featureflag.api.FeatureFlagService import io.element.android.libraries.featureflag.api.FeatureFlags import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.user.MatrixUser +import io.element.android.libraries.ui.strings.CommonStrings import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @@ -34,6 +39,8 @@ import kotlinx.coroutines.launch class BlockedUsersPresenter( private val matrixClient: MatrixClient, private val featureFlagService: FeatureFlagService, + private val clipboardHelper: ClipboardHelper, + private val snackbarDispatcher: SnackbarDispatcher, ) : Presenter { @Composable override fun present(): BlockedUsersState { @@ -65,12 +72,18 @@ class BlockedUsersPresenter( } } + val snackbarMessage by snackbarDispatcher.collectSnackbarMessageAsState() + fun handleEvent(event: BlockedUsersEvents) { when (event) { is BlockedUsersEvents.Unblock -> { pendingUserToUnblock = event.userId unblockUserAction.value = AsyncAction.ConfirmingNoParams } + is BlockedUsersEvents.CopyToClipboard -> { + clipboardHelper.copyPlainText(event.userId.value) + snackbarDispatcher.post(SnackbarMessage(CommonStrings.common_copied_to_clipboard)) + } BlockedUsersEvents.ConfirmUnblock -> { pendingUserToUnblock?.let { coroutineScope.unblockUser(it, unblockUserAction) @@ -86,6 +99,7 @@ class BlockedUsersPresenter( return BlockedUsersState( blockedUsers = ignoredMatrixUser.toImmutableList(), unblockUserAction = unblockUserAction.value, + snackbarMessage = snackbarMessage, eventSink = ::handleEvent, ) } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersState.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersState.kt index 8c478371ad..e4b07386c7 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersState.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersState.kt @@ -9,11 +9,13 @@ package io.element.android.features.preferences.impl.blockedusers import io.element.android.libraries.architecture.AsyncAction +import io.element.android.libraries.designsystem.utils.snackbar.SnackbarMessage import io.element.android.libraries.matrix.api.user.MatrixUser import kotlinx.collections.immutable.ImmutableList data class BlockedUsersState( val blockedUsers: ImmutableList, val unblockUserAction: AsyncAction, + val snackbarMessage: SnackbarMessage?, val eventSink: (BlockedUsersEvents) -> Unit, ) diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersStatePreviewParam.kt similarity index 86% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersStatePreviewParam.kt index 92cc8a0936..b1a9a2224d 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersStatePreviewParam.kt @@ -10,11 +10,12 @@ package io.element.android.features.preferences.impl.blockedusers import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction +import io.element.android.libraries.designsystem.utils.snackbar.SnackbarMessage import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.ui.components.aMatrixUserList import kotlinx.collections.immutable.toImmutableList -class BlockedUsersStateProvider : PreviewParameterProvider { +class BlockedUsersStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aBlockedUsersState(), @@ -30,11 +31,13 @@ class BlockedUsersStateProvider : PreviewParameterProvider { internal fun aBlockedUsersState( blockedUsers: List = aMatrixUserList(), unblockUserAction: AsyncAction = AsyncAction.Uninitialized, + snackbarMessage: SnackbarMessage? = null, eventSink: (BlockedUsersEvents) -> Unit = {}, ): BlockedUsersState { return BlockedUsersState( blockedUsers = blockedUsers.toImmutableList(), unblockUserAction = unblockUserAction, + snackbarMessage = snackbarMessage, eventSink = eventSink, ) } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersView.kt index 40e58022bd..be0c9d4937 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersView.kt @@ -8,7 +8,7 @@ package io.element.android.features.preferences.impl.blockedusers -import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding @@ -31,6 +31,8 @@ import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.designsystem.theme.components.Scaffold import io.element.android.libraries.designsystem.theme.components.TopAppBar +import io.element.android.libraries.designsystem.utils.snackbar.SnackbarHost +import io.element.android.libraries.designsystem.utils.snackbar.rememberSnackbarHostState import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.ui.components.MatrixUserRow @@ -43,6 +45,7 @@ fun BlockedUsersView( onBackClick: () -> Unit, modifier: Modifier = Modifier, ) { + val snackbarHostState = rememberSnackbarHostState(snackbarMessage = state.snackbarMessage) Box(modifier = modifier) { Scaffold( topBar = { @@ -52,7 +55,8 @@ fun BlockedUsersView( BackButton(onClick = onBackClick) } ) - } + }, + snackbarHost = { SnackbarHost(snackbarHostState) }, ) { padding -> LazyColumn( modifier = Modifier.padding(padding) @@ -60,7 +64,8 @@ fun BlockedUsersView( items(state.blockedUsers) { matrixUser -> BlockedUserItem( matrixUser = matrixUser, - onClick = { state.eventSink(BlockedUsersEvents.Unblock(it)) } + onClick = { state.eventSink(BlockedUsersEvents.Unblock(it)) }, + onLongClick = { state.eventSink(BlockedUsersEvents.CopyToClipboard(it)) }, ) } } @@ -107,16 +112,21 @@ fun BlockedUsersView( private fun BlockedUserItem( matrixUser: MatrixUser, onClick: (UserId) -> Unit, + onLongClick: (UserId) -> Unit, ) { MatrixUserRow( - modifier = Modifier.clickable { onClick(matrixUser.userId) }, + modifier = Modifier.combinedClickable( + onClick = { onClick(matrixUser.userId) }, + onLongClick = { onLongClick(matrixUser.userId) }, + onLongClickLabel = stringResource(CommonStrings.action_copy), + ), matrixUser = matrixUser, ) } @PreviewsDayNight @Composable -internal fun BlockedUsersViewPreview(@PreviewParameter(BlockedUsersStateProvider::class) state: BlockedUsersState) { +internal fun BlockedUsersViewPreview(@PreviewParameter(BlockedUsersStatePreviewParam::class) state: BlockedUsersState) { ElementPreview { BlockedUsersView( state = state, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenter.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenter.kt index ac1ba06cf6..c5a9b430ee 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenter.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenter.kt @@ -30,6 +30,7 @@ import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.architecture.runCatchingUpdatingState import io.element.android.libraries.core.data.ByteUnit +import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.matrix.api.analytics.GetDatabaseSizesUseCase import io.element.android.libraries.matrix.api.core.DeviceId import io.element.android.libraries.matrix.api.core.SessionId @@ -50,6 +51,7 @@ class DeveloperSettingsPresenter( private val databaseSizesUseCase: GetDatabaseSizesUseCase, private val fileSizeFormatter: FileSizeFormatter, private val markAllRoomsAsRead: MarkAllRoomsAsRead, + private val buildMeta: BuildMeta, ) : Presenter { @Composable override fun present(): DeveloperSettingsState { @@ -117,7 +119,7 @@ class DeveloperSettingsPresenter( databaseSizes = databaseSizes.value, clearCacheAction = clearCacheAction.value, markAllRoomsAsReadAction = markAllRoomsAsReadAction.value, - isEnterpriseBuild = enterpriseService.isEnterpriseBuild, + isEnterpriseBuild = buildMeta.isEnterpriseBuild, showColorPicker = showColorPicker, deviceId = deviceId, eventSink = ::handleEvent, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsStatePreviewParam.kt similarity index 96% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsStatePreviewParam.kt index b14446d11c..8cc6ad7dce 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.core.DeviceId import kotlinx.collections.immutable.persistentMapOf -open class DeveloperSettingsStateProvider : PreviewParameterProvider { +open class DeveloperSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDeveloperSettingsState(), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsView.kt index 2fd2137451..66a478a4e5 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsView.kt @@ -231,7 +231,7 @@ private fun NotificationCategory(onPushHistoryClick: () -> Unit) { @PreviewsDayNight @Composable internal fun DeveloperSettingsViewPreview( - @PreviewParameter(DeveloperSettingsStateProvider::class) state: DeveloperSettingsState + @PreviewParameter(DeveloperSettingsStatePreviewParam::class) state: DeveloperSettingsState ) = ElementPreview { DeveloperSettingsView( state = state, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsStatePreviewParam.kt similarity index 94% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsStatePreviewParam.kt index e4536f4dba..480b8426d7 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.featureflag.ui.model.aFeatureUiModelList import io.element.android.libraries.matrix.api.tracing.TraceLogPack import kotlinx.collections.immutable.toImmutableList -open class AppDeveloperSettingsStateProvider : PreviewParameterProvider { +open class AppDeveloperSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAppDeveloperSettingsState(), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsView.kt index a4f41edb4a..7b1401b5e5 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/appsettings/AppDeveloperSettingsView.kt @@ -182,7 +182,7 @@ private fun FeatureListContent( @PreviewsDayNight @Composable internal fun AppDeveloperSettingsViewPreview( - @PreviewParameter(AppDeveloperSettingsStateProvider::class) state: AppDeveloperSettingsState + @PreviewParameter(AppDeveloperSettingsStatePreviewParam::class) state: AppDeveloperSettingsState ) = ElementPreview { AppDeveloperSettingsView( state = state, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/di/DeveloperSettingsModule.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/di/DeveloperSettingsBindingContainer.kt similarity index 94% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/di/DeveloperSettingsModule.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/di/DeveloperSettingsBindingContainer.kt index bad0ccae0f..c95b608853 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/di/DeveloperSettingsModule.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/developer/di/DeveloperSettingsBindingContainer.kt @@ -17,7 +17,7 @@ import io.element.android.libraries.architecture.Presenter @ContributesTo(AppScope::class) @BindingContainer -interface DeveloperSettingsModule { +interface DeveloperSettingsBindingContainer { @Binds fun bindAppDeveloperSettingsPresenter(presenter: AppDeveloperSettingsPresenter): Presenter } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsStatePreviewParam.kt similarity index 95% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsStatePreviewParam.kt index 08e251dcfa..f0b5705376 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.designsystem.theme.components.IconSource import io.element.android.libraries.featureflag.ui.model.FeatureUiModel import kotlinx.collections.immutable.toImmutableList -internal class LabsStateProvider : PreviewParameterProvider { +internal class LabsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLabsState(features = aFeatureList()), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsView.kt index 7a6703e3bc..7c7f2482e3 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/labs/LabsView.kt @@ -101,7 +101,7 @@ fun LabsView( @PreviewsDayNight @Composable -internal fun LabsViewPreview(@PreviewParameter(LabsStateProvider::class) state: LabsState) { +internal fun LabsViewPreview(@PreviewParameter(LabsStatePreviewParam::class) state: LabsState) { ElementPreview { LabsView(state = state, onBack = {}) } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsStatePreviewParam.kt similarity index 98% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsStatePreviewParam.kt index 905f869dbe..38c83153ea 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsStatePreviewParam.kt @@ -19,7 +19,7 @@ import io.element.android.libraries.pushproviders.api.Distributor import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -open class NotificationSettingsStateProvider : PreviewParameterProvider { +open class NotificationSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aValidNotificationSettingsState(systemNotificationsEnabled = false), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsView.kt index 9ede5138cf..a15f991f95 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/NotificationSettingsView.kt @@ -500,7 +500,9 @@ private fun InvalidNotificationSettingsView( @PreviewsDayNight @Composable -internal fun NotificationSettingsViewPreview(@PreviewParameter(NotificationSettingsStateProvider::class) state: NotificationSettingsState) = ElementPreview { +internal fun NotificationSettingsViewPreview(@PreviewParameter( + NotificationSettingsStatePreviewParam::class +) state: NotificationSettingsState) = ElementPreview { NotificationSettingsView( state = state, onBackClick = {}, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingStatePreviewParam.kt similarity index 95% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingStatePreviewParam.kt index 389554d2e0..819cd0d1f3 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.room.RoomNotificationMode import kotlinx.collections.immutable.persistentListOf -open class EditDefaultNotificationSettingStateProvider : PreviewParameterProvider { +open class EditDefaultNotificationSettingStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anEditDefaultNotificationSettingsState(), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingView.kt index 24da141a48..3d4256f65d 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/notifications/edit/EditDefaultNotificationSettingView.kt @@ -125,7 +125,7 @@ fun EditDefaultNotificationSettingView( @PreviewsDayNight @Composable internal fun EditDefaultNotificationSettingViewPreview( - @PreviewParameter(EditDefaultNotificationSettingStateProvider::class) state: EditDefaultNotificationSettingState + @PreviewParameter(EditDefaultNotificationSettingStatePreviewParam::class) state: EditDefaultNotificationSettingState ) = ElementPreview { EditDefaultNotificationSettingView( state = state, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootPresenter.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootPresenter.kt index 9ccd8b9116..3a720fc7a8 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootPresenter.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootPresenter.kt @@ -74,8 +74,11 @@ class PreferencesRootPresenter( val showLinkNewDevice by remember { featureFlagService.isFeatureEnabledFlow(FeatureFlags.QrCodeLogin) }.collectAsState(initial = false) - val isUserStatusEnabled by featureFlagService.isFeatureEnabledFlow(FeatureFlags.UserStatus).collectAsState(initial = false) - val userStatusState = if (isUserStatusEnabled) userStatusPresenter.present() else null + + val isUserStatusSupported by produceState(false) { + value = matrixClient.isUserStatusSupported().getOrDefault(false) + } + val userStatusState = if (isUserStatusSupported) userStatusPresenter.present() else null val otherSessions by remember { sessionStore.sessionsFlow().map { list -> diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootStatePreviewParam.kt similarity index 98% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootStatePreviewParam.kt index 86f984f254..80c47a33b2 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootStatePreviewParam.kt @@ -21,7 +21,7 @@ import io.element.android.libraries.matrix.ui.components.aMatrixUserList import io.element.android.libraries.ui.strings.CommonStrings import kotlinx.collections.immutable.toImmutableList -open class PreferencesRootStateProvider : PreviewParameterProvider { +open class PreferencesRootStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( // Nominal state, that a regular user will see if multi account is enabled diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootView.kt index 5727712bc3..82c88b16fa 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/root/PreferencesRootView.kt @@ -8,10 +8,14 @@ package io.element.android.features.preferences.impl.root +import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -25,7 +29,10 @@ import io.element.android.features.preferences.impl.R import io.element.android.features.preferences.impl.user.UserPreferences import io.element.android.features.preferences.impl.userstatus.UserStatusState import io.element.android.features.preferences.impl.userstatus.UserStatusView +import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.architecture.coverage.ExcludeFromCoverage +import io.element.android.libraries.designsystem.components.async.AsyncActionIndicator +import io.element.android.libraries.designsystem.components.async.AsyncIndicator import io.element.android.libraries.designsystem.components.avatar.AvatarSize import io.element.android.libraries.designsystem.components.list.ListItemContent import io.element.android.libraries.designsystem.components.preferences.PreferencePage @@ -71,71 +78,87 @@ fun PreferencesRootView( ) { val snackbarHostState = rememberSnackbarHostState(snackbarMessage = state.snackbarMessage) - // Include pref from other modules - PreferencePage( - modifier = modifier, - onBackClick = onBackClick, - title = stringResource(id = CommonStrings.common_settings), - snackbarHost = { SnackbarHost(snackbarHostState) } - ) { - UserPreferences( - modifier = Modifier.clickable { - onOpenUserProfile(state.myUser) - }, - matrixUser = state.myUser, - ) - if (state.isMultiAccountEnabled) { - MultiAccountSection( - state = state, - onAddAccountClick = onAddAccountClick, + Box(modifier = modifier) { + // Include pref from other modules + PreferencePage( + onBackClick = onBackClick, + title = stringResource(id = CommonStrings.common_settings), + snackbarHost = { SnackbarHost(snackbarHostState) } + ) { + UserPreferences( + modifier = Modifier.clickable { + onOpenUserProfile(state.myUser) + }, + matrixUser = state.myUser, ) - } - if (state.userStatusState != null) { - UserStatusSection( - userStatusState = state.userStatusState, - emojiPickerRenderer = emojiPickerRenderer, - showTopDivider = !state.isMultiAccountEnabled, - ) - } - // 'Account' section - ManageAccountSection( - state = state, - onManageAccountClick = onManageAccountClick, - onLinkNewDeviceClick = onLinkNewDeviceClick, - onOpenBlockedUsers = onOpenBlockedUsers - ) - // 'Manage my app' section - ManageAppSection( - state = state, - onOpenNotificationSettings = onOpenNotificationSettings, - onOpenLockScreenSettings = onOpenLockScreenSettings, - onSecureBackupClick = onSecureBackupClick, - ) - - // General section - GeneralSection( - state = state, - onOpenAbout = onOpenAbout, - onOpenAnalytics = onOpenAnalytics, - onOpenRageShake = onOpenRageShake, - onOpenAdvancedSettings = onOpenAdvancedSettings, - onOpenDeveloperSettings = onOpenDeveloperSettings, - onOpenLabs = onOpenLabs, - onSignOutClick = onSignOutClick, - onDeactivateClick = onDeactivateClick, - ) - // Version - Footer( - version = state.version, - onClick = if (!state.showDeveloperSettings) { - { state.eventSink(PreferencesRootEvent.OnVersionInfoClick) } - } else { - null + if (state.isMultiAccountEnabled) { + MultiAccountSection( + state = state, + onAddAccountClick = onAddAccountClick, + ) } - ) + if (state.userStatusState != null) { + UserStatusSection( + userStatusState = state.userStatusState, + emojiPickerRenderer = emojiPickerRenderer, + showTopDivider = !state.isMultiAccountEnabled, + ) + } + // 'Account' section + ManageAccountSection( + state = state, + onManageAccountClick = onManageAccountClick, + onLinkNewDeviceClick = onLinkNewDeviceClick, + onOpenBlockedUsers = onOpenBlockedUsers + ) + // 'Manage my app' section + ManageAppSection( + state = state, + onOpenNotificationSettings = onOpenNotificationSettings, + onOpenLockScreenSettings = onOpenLockScreenSettings, + onSecureBackupClick = onSecureBackupClick, + ) + + // General section + GeneralSection( + state = state, + onOpenAbout = onOpenAbout, + onOpenAnalytics = onOpenAnalytics, + onOpenRageShake = onOpenRageShake, + onOpenAdvancedSettings = onOpenAdvancedSettings, + onOpenDeveloperSettings = onOpenDeveloperSettings, + onOpenLabs = onOpenLabs, + onSignOutClick = onSignOutClick, + onDeactivateClick = onDeactivateClick, + ) + // Version + Footer( + version = state.version, + onClick = if (!state.showDeveloperSettings) { + { state.eventSink(PreferencesRootEvent.OnVersionInfoClick) } + } else { + null + } + ) + } + state.userStatusState?.let { + UserStatusUpdateIndicator(it.updateStatusAction) + } } } +@Composable +private fun BoxScope.UserStatusUpdateIndicator(updateStatusAction: AsyncAction) { + AsyncActionIndicator( + asyncAction = updateStatusAction, + modifier = Modifier + .align(Alignment.TopCenter) + .statusBarsPadding(), + loading = { AsyncIndicator.Loading(text = stringResource(CommonStrings.common_saving)) }, + failure = { _ -> AsyncIndicator.Failure(text = stringResource(CommonStrings.common_failed)) }, + ) +} + @Composable private fun ColumnScope.UserStatusSection( userStatusState: UserStatusState, @@ -315,7 +338,9 @@ private fun ColumnScope.GeneralSection( ) } // Put developer settings at the end, so nothing bad happens if the user clicks 8 times to enable the entry - if (state.showDeveloperSettings) { + AnimatedVisibility( + visible = state.showDeveloperSettings, + ) { DeveloperPreferencesView(onOpenDeveloperSettings) } } @@ -348,14 +373,14 @@ private fun DeveloperPreferencesView(onOpenDeveloperSettings: () -> Unit) { @PreviewWithLargeHeight @Composable -internal fun PreferencesRootViewLightPreview(@PreviewParameter(PreferencesRootStateProvider::class) state: PreferencesRootState) = +internal fun PreferencesRootViewLightPreview(@PreviewParameter(PreferencesRootStatePreviewParam::class) state: PreferencesRootState) = ElementPreviewLight( drawableFallbackForImages = CommonDrawables.sample_avatar, ) { ContentToPreview(state) } @PreviewWithLargeHeight @Composable -internal fun PreferencesRootViewDarkPreview(@PreviewParameter(PreferencesRootStateProvider::class) state: PreferencesRootState) = +internal fun PreferencesRootViewDarkPreview(@PreviewParameter(PreferencesRootStatePreviewParam::class) state: PreferencesRootState) = ElementPreviewDark( drawableFallbackForImages = CommonDrawables.sample_avatar, ) { ContentToPreview(state) } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/UserPreferences.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/UserPreferences.kt index 43c7e8dacf..066b9ac73e 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/UserPreferences.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/UserPreferences.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.ui.components.MatrixUserHeader -import io.element.android.libraries.matrix.ui.components.MatrixUserProvider +import io.element.android.libraries.matrix.ui.components.MatrixUserPreviewParam @Composable fun UserPreferences( @@ -30,6 +30,6 @@ fun UserPreferences( @PreviewsDayNight @Composable -internal fun UserPreferencesPreview(@PreviewParameter(MatrixUserProvider::class) matrixUser: MatrixUser) = ElementPreview { +internal fun UserPreferencesPreview(@PreviewParameter(MatrixUserPreviewParam::class) matrixUser: MatrixUser) = ElementPreview { UserPreferences(matrixUser) } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileStatePreviewParam.kt similarity index 95% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileStatePreviewParam.kt index 2f238f9935..8b711cba51 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileStatePreviewParam.kt @@ -17,7 +17,7 @@ import io.element.android.libraries.permissions.api.PermissionsState import io.element.android.libraries.permissions.api.aPermissionsState import kotlinx.collections.immutable.toImmutableList -open class EditUserProfileStateProvider : PreviewParameterProvider { +open class EditUserProfileStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aEditUserProfileState(), diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileView.kt index d4571d7be5..89e739fe56 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/user/editprofile/EditUserProfileView.kt @@ -178,7 +178,7 @@ fun EditUserProfileView( @PreviewsDayNight @Composable -internal fun EditUserProfileViewPreview(@PreviewParameter(EditUserProfileStateProvider::class) state: EditUserProfileState) = +internal fun EditUserProfileViewPreview(@PreviewParameter(EditUserProfileStatePreviewParam::class) state: EditUserProfileState) = ElementPreview { EditUserProfileView( onEditProfileSuccess = {}, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenter.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenter.kt index 60f02ad05a..2358b3502d 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenter.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenter.kt @@ -18,7 +18,9 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import dev.zacsweers.metro.Inject +import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.architecture.Presenter +import io.element.android.libraries.architecture.runUpdatingState import io.element.android.libraries.emoji.api.picker.EmojiPickerPresenter import io.element.android.libraries.emoji.api.recentemojis.EmptyGetRecentEmojis import io.element.android.libraries.matrix.api.MatrixClient @@ -38,6 +40,7 @@ class UserStatusPresenter( var isEmojiPickerVisible by remember { mutableStateOf(false) } val customTextFieldState = rememberTextFieldState() val coroutineScope = rememberCoroutineScope() + val updateStatusAction = remember { mutableStateOf>(AsyncAction.Uninitialized) } fun handleEvent(event: UserStatusEvent) { when (event) { @@ -47,11 +50,15 @@ class UserStatusPresenter( UserStatusEvent.CancelCustomInput -> pickerState = UserStatusPickerState.Hidden is UserStatusEvent.SetStatus -> { pickerState = UserStatusPickerState.Hidden - coroutineScope.launch { matrixClient.setUserStatus(event.status) } + coroutineScope.launch { + updateStatusAction.runUpdatingState { matrixClient.setUserStatus(event.status) } + } } UserStatusEvent.ClearStatus -> { pickerState = UserStatusPickerState.Hidden - coroutineScope.launch { matrixClient.clearUserStatus() } + coroutineScope.launch { + updateStatusAction.runUpdatingState { matrixClient.clearUserStatus() } + } } UserStatusEvent.OpenCustomInput -> { val raw = userProfile.rawStatus @@ -93,6 +100,7 @@ class UserStatusPresenter( displayedStatus = userProfile.displayedStatus, rawStatus = userProfile.rawStatus, pickerState = effectivePickerState, + updateStatusAction = updateStatusAction.value, eventSink = ::handleEvent, ) } diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusState.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusState.kt index fa225ae277..6189ee6dd0 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusState.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusState.kt @@ -11,6 +11,7 @@ import androidx.annotation.StringRes import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.Immutable import io.element.android.features.preferences.impl.R +import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.emoji.api.picker.EmojiPickerState import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.UserStatus @@ -19,6 +20,7 @@ data class UserStatusState( val displayedStatus: DisplayedStatus?, val rawStatus: UserStatus?, val pickerState: UserStatusPickerState, + val updateStatusAction: AsyncAction, val eventSink: (UserStatusEvent) -> Unit, ) diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusStateProvider.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusStatePreviewParam.kt similarity index 88% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusStateProvider.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusStatePreviewParam.kt index 13a1d31743..34a12c604e 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusStateProvider.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusStatePreviewParam.kt @@ -9,10 +9,11 @@ package io.element.android.features.preferences.impl.userstatus import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.ui.tooling.preview.PreviewParameterProvider +import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.UserStatus -internal class UserStatusStateProvider : PreviewParameterProvider { +internal class UserStatusStatePreviewParam : PreviewParameterProvider { override val values get() = sequenceOf( aUserStatusState(), aUserStatusState(displayedStatus = DisplayedStatus.UserSet(UserStatus("🌴", "Away"))), @@ -44,10 +45,12 @@ fun aUserStatusState( displayedStatus: DisplayedStatus? = null, rawStatus: UserStatus? = null, pickerState: UserStatusPickerState = UserStatusPickerState.Hidden, + updateStatusAction: AsyncAction = AsyncAction.Uninitialized, eventSink: (UserStatusEvent) -> Unit = {}, ) = UserStatusState( displayedStatus = displayedStatus, rawStatus = rawStatus, pickerState = pickerState, + updateStatusAction = updateStatusAction, eventSink = eventSink, ) diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusView.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusView.kt index 19cc43d3d7..c25c159f33 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusView.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusView.kt @@ -354,7 +354,7 @@ private fun EmojiPickerBottomSheet( @PreviewsDayNight @Composable -internal fun UserStatusViewPreview(@PreviewParameter(UserStatusStateProvider::class) state: UserStatusState) = ElementPreview { +internal fun UserStatusViewPreview(@PreviewParameter(UserStatusStatePreviewParam::class) state: UserStatusState) = ElementPreview { UserStatusView( state = state, emojiPickerRenderer = NoOpEmojiPickerRenderer, diff --git a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusBindingContainer.kt b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/di/UserStatusBindingContainer.kt similarity index 73% rename from features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusBindingContainer.kt rename to features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/di/UserStatusBindingContainer.kt index dfa77483f8..0e6f1bdc2f 100644 --- a/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusBindingContainer.kt +++ b/features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/userstatus/di/UserStatusBindingContainer.kt @@ -5,11 +5,13 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.features.preferences.impl.userstatus +package io.element.android.features.preferences.impl.userstatus.di import dev.zacsweers.metro.BindingContainer import dev.zacsweers.metro.Binds import dev.zacsweers.metro.ContributesTo +import io.element.android.features.preferences.impl.userstatus.UserStatusPresenter +import io.element.android.features.preferences.impl.userstatus.UserStatusState import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.di.SessionScope diff --git a/features/preferences/impl/src/main/res/values-ar/translations.xml b/features/preferences/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..92f4539cd3 --- /dev/null +++ b/features/preferences/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,115 @@ + + + "للتأكد من عدم تفويت أي مكالمة مهمة، يُرجى تغيير إعداداتك للسماح بإشعارات ملء الشاشة عندما يكون هاتفك مقفلاً." + "حسّن تجربة مكالماتك" + "اختر طريقة استقبال الإشعارات" + "وضع المطوّر" + "فعّله للوصول إلى الميزات والوظائف الخاصة بالمطورين." + "عنوان URL الأساسي المخصص لـ Element Call" + "عيّن عنوان URL أساسيًا مخصصًا لـ Element Call." + "عنوان URL غير صالح، يُرجى التأكد من تضمين البروتوكول (http/https) والعنوان الصحيح." + "إخفاء الصور الرمزية في طلبات الدعوة إلى الغرف" + "إخفاء معاينات الوسائط في المخطط الزمني" + "المختبرات" + "المسافة التي يجب أن تتحركها ليتم إرسال تحديث." + "تأكد من تفعيل \"الموقع الدقيق\" لهذا التطبيق. لتغيير الإذن، انتقل إلى %1$s." + "إعدادات التطبيق" + "تحديثات الموقع المباشر" + + "كل %1$d أمتار" + "كل %1$d متر" + "كل %1$d مترين" + "كل %1$d أمتار" + "كل %1$d مترًا" + "كل %1$d متر" + + "رفع الصور ومقاطع الفيديو بسرعة أكبر وتقليل استخدام البيانات" + "تحسين جودة الوسائط" + "الإشراف والسلامة" + "تحسين الصور تلقائيًا لرفعها بسرعة أكبر وتقليل أحجام الملفات." + "تحسين جودة رفع الصور" + "%1$s. اضغط هنا للتغيير." + "عالية (1080p)" + "منخفضة (480p)" + "قياسية (720p)" + "جودة رفع الفيديو" + "موفّر الإشعارات الفورية" + "عطّل محرر النص المنسق لكتابة Markdown يدويًا." + "إيصالات القراءة" + "إذا كان هذا الخيار متوقفًا، فلن تُرسل إيصالات القراءة الخاصة بك إلى أي شخص. ستظل تتلقى إيصالات القراءة من المستخدمين الآخرين." + "مشاركة حالة التواجد" + "إذا كان هذا الخيار متوقفًا، فلن تتمكن من إرسال أو تلقي إيصالات القراءة أو إشعارات الكتابة." + "إخفاء دائمًا" + "إظهار دائمًا" + "في الغرف الخاصة" + "يمكن دائمًا إظهار الوسائط المخفية بالضغط عليها" + "إظهار الوسائط في المخطط الزمني" + "فعّل خيار عرض مصدر الرسالة في الخط الزمني." + "ليس لديك أي مستخدمين محظورين" + "إلغاء الحظر" + "ستتمكن من رؤية كل رسائلهم مجدّداً." + "إلغاء حظر المستخدم" + "جارٍ إلغاء الحظر…" + "الاسم" + "اسمك" + "حدث خطأ غير معروف وتعذّر تغيير المعلومات." + "غير قادر على تحديث الملف الشخصي" + "تعديل الملف الشخصي" + "يتم تحديث الملف الشخصي…" + "تفعيل الردود في السلاسل" + "سيُعاد تشغيل التطبيق لتطبيق هذا التغيير." + "جرّب أحدث أفكارنا قيد التطوير. هذه الميزات ليست نهائية؛ قد تكون غير مستقرة وقد تتغير." + "هل ترغب في التجربة؟" + "المختبرات" + "إعدادات إضافية" + "نغمة رنين المكالمات" + "المكالمات الصوتية والفيديو" + "عدم تطابق الإعدادات" + "لقد بسّطنا إعدادات الإشعارات لتكون الخيارات أسهل للإيجاد. بعض الإعدادات المخصصة التي كنت قد طبّقتها في السابق ليست ظاهرة هنا، ولكنها ما تزال مفعّلة. + +إذا ما تقدّمت، فبعض إعداداتك قد تتغير." + "المحادثات الخاصة" + "إعدادات خاصة لكل محادثة" + "حدث خطأ أثناء تحديث إعدادات الإشعارات." + "كل الرسائل" + "الإشارات والكلمات الرئيسية فقط" + "في المحادثات الخاصة، أرسل لي إشعارات لـ" + "في المحادثات الجماعية، أرسل لي إشعارات لـ" + "تفعيل الإشعارات على هذا الجهاز" + "تعذّر تصحيح الإعدادات، يُرجى المحاولة مرة أخرى." + "المحادثات الجماعية" + "الدعوات" + "لا يدعم خادمك المنزلي هذا الخيار في الغرف المشفّرة، وقد لا تتلقى إشعارات في بعض الغرف." + "الإشارات" + "اختيار صوت آخر…" + "يُستخدم حاليًا %1$s" + "صوت الرسائل" + "صوت الرسائل" + "الكل" + "الإشارات" + "أرسل لي إشعارات لـ" + "أرسل لي إشعاراً عندما يُكتب @room" + "مخصص" + "صوت مخصص…" + "خطأ في حذف الملف" + "افتراضي Element" + "Element Fade" + "خطأ في استيراد الملف" + "مشكلة في معاينة صوت التنبيه" + "الصوت" + "إغلاق خطأ صوت التنبيه" + "مشكلة في تعيين صوت التنبيه" + "صامت" + "افتراضي النظام" + "لتلقي الإشعارات يرجى تغيير الـ %1$s خاصتك" + "إعدادات النظام" + "إشعارات النظام مُطفأة" + "الإشعارات" + "أسود" + "داكن" + "فاتح" + "النظام" + "سجل الإشعارات الفورية" + "استكشاف الأخطاء وإصلاحها" + "استكشاف أخطاء الإشعارات وإصلاحها" + diff --git a/features/preferences/impl/src/main/res/values-de/translations.xml b/features/preferences/impl/src/main/res/values-de/translations.xml index e35cf871a1..31add7855a 100644 --- a/features/preferences/impl/src/main/res/values-de/translations.xml +++ b/features/preferences/impl/src/main/res/values-de/translations.xml @@ -11,6 +11,12 @@ "Avatare in Chateinladungen ausblenden" "Medienvorschau im Nachrichtenverlauf ausblenden" "Labs" + "Die Entfernung, die du zurücklegen musst, um ein Update auszulösen." + "Live-Standort-Updates" + + "Alle %1$d Meter" + "Alle %1$d Meter" + "Lade Fotos und Videos schneller hoch und reduziere den Datenverbrauch" "Optimiere die Medienqualität" "Moderation und Sicherheit" diff --git a/features/preferences/impl/src/main/res/values-es/translations.xml b/features/preferences/impl/src/main/res/values-es/translations.xml index dd496a1273..60ff403b41 100644 --- a/features/preferences/impl/src/main/res/values-es/translations.xml +++ b/features/preferences/impl/src/main/res/values-es/translations.xml @@ -10,9 +10,25 @@ "URL no válida, asegúrate de incluir el protocolo (http/https) y la dirección correcta." "Ocultar avatares en las invitaciones a salas" "Ocultar vistas previas de multimedia en la cronología" + "Experimental" + "La distancia que debes recorrer para que se active una actualización." + "Asegúrate de que la «Ubicación precisa» está activada para esta aplicación. Para cambiar el permiso, ve a %1$s." + "Ajustes de la aplicación" + "Actualizaciones de ubicación en tiempo real" + + "Cada %1$d metros" + "Cada %1$d metros" + "Sube fotos y vídeos más rápido y reduce el uso de datos" - "Optimizar la calidad de los medios" + "Optimizar la calidad multimedia" "Moderación y seguridad" + "Optimizar automáticamente las imágenes para subidas más rápidas y tamaños de archivo más pequeños." + "Optimizar la calidad de subida de imágenes" + "%1$s. Toca aquí para cambiar." + "Alta (1080p)" + "Baja (480p)" + "Estándar (720p)" + "Calidad de subida de vídeos" "Proveedor de notificaciones push" "Desactiva el editor de texto enriquecido para escribir Markdown manualmente." "Confirmaciones de lectura" @@ -36,7 +52,13 @@ "No se puede actualizar el perfil" "Editar perfil" "Actualizando perfil…" + "Activar respuestas en hilo" + "La aplicación se reiniciará para aplicar este cambio." + "Prueba nuestras últimas ideas en desarrollo. Estas funciones aún no están terminadas; pueden ser inestables y están sujetas a cambios." + "¿Ganas de experimentar?" + "Experimental" "Ajustes adicionales" + "Tono de llamada" "Llamadas de audio y vídeo" "La configuración no coincide" "Hemos simplificado la Configuración de Notificaciones para hacer las opciones más fáciles de encontrar. Algunas configuraciones personalizadas que has elegido en el pasado no se muestran aquí, pero siguen activas. @@ -55,14 +77,39 @@ Si continúas, es posible que algunos de tus ajustes cambien." "Invitaciones" "Tu servidor base no admite esta opción en salas cifradas, puede que no recibas notificaciones de algunas salas." "Menciones" + "Elegir otro sonido…" + "Usando actualmente %1$s" + "Sonido de mensaje" + "Sonido de mensaje" "Todos" "Menciones" "Notificarme para" "Notificarme con @room" + "Personalizado" + "Sonido personalizado…" + "Error al eliminar el archivo" + "Predeterminado de Element" + "Desvanecimiento de Element" + "Error al importar el archivo" + "Problema al previsualizar el sonido de alerta" + "Sonido" + "Ignorar el error del sonido de alerta" + "Problema al establecer el sonido de alerta" + "Silencioso" + "Predeterminado del sistema" "Para recibir notificaciones, cambia tus %1$s." "ajustes del sistema" "Notificaciones del sistema desactivadas" "Notificaciones" + "Ausente" + "Vuelvo enseguida" + "Personalizado…" + "Estado personalizado…" + "Hora de concentrarse" + "En una reunión" + "En la carretera" + "¿Cuál es tu estado?" + "Negro" "Oscuro" "Claro" "Sistema" diff --git a/features/preferences/impl/src/main/res/values-fa/translations.xml b/features/preferences/impl/src/main/res/values-fa/translations.xml index df42ca953c..167bf022ca 100644 --- a/features/preferences/impl/src/main/res/values-fa/translations.xml +++ b/features/preferences/impl/src/main/res/values-fa/translations.xml @@ -1,5 +1,6 @@ + "برای اطمینان از اینکه هرگز تماس مهمی را از دست نمی‌دهید، لطفاً تنظیمات خود را تغییر دهید تا وقتی تلفنتان قفل است، اعلان‌ها به صورت تمام صفحه نمایش داده شوند." "بهبود تجریهٔ تماستان" "گزینش چگونگی دریافت آگاهی" "حالت توسعه‌دهنده" @@ -10,8 +11,20 @@ "نهفتن چهرک‌ها در درخواست‌های دعوت اتاق" "نهفتن رسانه در خط زمانی" "آزمایشگاه‌ها" + "مسافتی که باید طی کنید تا به‌روزرسانی انجام شود." + "مطمئن شوید که «موقعیت مکانی دقیق» برای این برنامه فعال شده است. برای تغییر مجوز به %1$s بروید." + "تنظیمات برنامه" + "به‌روزرسانی‌های مکان زنده" + + "هر کنتور %1$d" + "هر کنتور %1$d" + + "عکس‌ها و ویدیوها را سریع‌تر آپلود کنید و مصرف اینترنت را کاهش دهید" "بهینه سازی کیفیت رسانه" "نظارت و امنیت" + "بهینه‌سازی خودکار تصاویر برای آپلود سریع‌تر و حجم کمتر فایل‌ها." + "بهینه سازی کیفیت آپلود تصاویر" + "%1$s. برای تغییر، اینجا را لمس کنید." "زیاد (۱۰۸۰ت)" "کم (۴۸۰ت)" "استاندارد (۷۲۰ت)" @@ -39,8 +52,13 @@ "ناتوان در به‌روز کردن نمایه" "ویرایش نمایه" "به‌روز کردن نمایه…" + "فعال کردن پاسخ‌های تاپیک" + "برنامه برای اعمال این تغییر مجدداً راه‌اندازی خواهد شد." + "آخرین ایده‌های در حال توسعه ما را امتحان کنید. این ویژگی‌ها هنوز نهایی نشده‌اند؛ ممکن است ناپایدار باشند، ممکن است تغییر کنند." + "احساس تجربی دارید؟" "آزمایشگاه‌ها" "تنظیمات اضافی" + "آهنگ زنگ تماس" "تماس‌های صوتی و تصویری" "نامتطابقت در پیکربندی" "تنظمیات آگاهی را ساده کرده‌ایم تا یافتن انتخاب‌ها را ساده‌تر کنیم. برهی تنظمیات سفارسی که در گذشته گزیده‌اید این‌جا نشان داده نمی‌شوند؛ ولی همچنن فعّالند. @@ -59,14 +77,39 @@ "دعوت‌ها" "کارساز خانگیتان از این گزینه در اتاق‌های رمز شده پشتیبانی نمی‌کند. ممکن است در برخی اتاق‌ها آگاه نشوید." "اشاره‌ها" + "صدای دیگری انتخاب کنید…" + "در حال حاضر از %1$s استفاده می‌شود." + "صدای پیام" + "صدای پیام" "همه" "اشاره‌ها" "آگاه کردنم برای" "آگاه کردنم برای ‪@room" + "سفارشی" + "صدای سفارشی…" + "خطا در حذف فایل" + "Element پیش‌فرض" + "Element فید" + "خطا در وارد کردن فایل" + "مشکل در پیش‌نمایش صدای هشدار" + "صدا" + "خطای صدای هشدار را رد کنید" + "مشکل در تنظیم صدای هشدار" + "بی‌صدا" + "پیش‌فرض سیستم" "برای گرفتن آگاهی‌ها لطفاً%1$sتان را تغییر دهید." "تنظیمات سامانه" "آگاهی‌های سامانه‌ای خاموش شدند" "آگاهی‌ها" + "بعدا" + "همین الان برگرد" + "سفارشی…" + "وضعیت سفارشی…" + "زمان تمرکز" + "در یک جلسه" + "در جاده" + "وضعیتت چطوره؟" + "سیاه" "تیره" "روشن" "سامانه" diff --git a/features/preferences/impl/src/main/res/values-fi/translations.xml b/features/preferences/impl/src/main/res/values-fi/translations.xml index f37673427f..c50989e526 100644 --- a/features/preferences/impl/src/main/res/values-fi/translations.xml +++ b/features/preferences/impl/src/main/res/values-fi/translations.xml @@ -68,7 +68,7 @@ Jos jatkat, jotkin asetukset saattavat muuttua." "Keskustelukohtaiset asetukset" "Ilmoitusasetusten muokkaamisessa tapahtui virhe." "Kaikista viesteistä" - "Vain maininnoista ja avainsanoista" + "Vain maininnoista ja vastauksista" "Yksityiskeskusteluissa, ilmoita minulle" "Ryhmäkeskusteluissa, ilmoita minulle" "Ota ilmoitukset käyttöön tällä laitteella" @@ -101,6 +101,14 @@ Jos jatkat, jotkin asetukset saattavat muuttua." "järjestelmäsi asetuksia" "Järjestelmän ilmoitukset on poissa päältä" "Ilmoitukset" + "Poissa" + "Palaan pian" + "Mukautettu…" + "Mukautettu tila…" + "Keskittymisaika" + "Kokouksessa" + "Tien päällä" + "Mikä on tilasi?" "Musta" "Tumma" "Vaalea" diff --git a/features/preferences/impl/src/main/res/values-fr/translations.xml b/features/preferences/impl/src/main/res/values-fr/translations.xml index fc57491f4a..06fe3be814 100644 --- a/features/preferences/impl/src/main/res/values-fr/translations.xml +++ b/features/preferences/impl/src/main/res/values-fr/translations.xml @@ -101,6 +101,14 @@ Si vous continuez, il est possible que certains de vos paramètres soient modifi "paramètres du système" "Les notifications du système sont désactivées" "Notifications" + "Absent" + "Je reviens tout de suite" + "Personnalisé…" + "Statut personnalisé…" + "Concentré" + "En réunion" + "Sur la route" + "Quel est votre statut ?" "Noir" "Sombre" "Clair" diff --git a/features/preferences/impl/src/main/res/values-hu/translations.xml b/features/preferences/impl/src/main/res/values-hu/translations.xml index f4a9616321..67afac50a1 100644 --- a/features/preferences/impl/src/main/res/values-hu/translations.xml +++ b/features/preferences/impl/src/main/res/values-hu/translations.xml @@ -101,6 +101,14 @@ Ha folytatja, egyes beállítások megváltozhatnak." "rendszerbeállításokat" "A rendszerértesítések ki vannak kapcsolva" "Értesítések" + "Távol" + "Rögtön visszajövök" + "Egyedi…" + "Egyéni állapot…" + "Feladatra koncentrál" + "Értekezleten" + "Úton" + "Mi az állapota?" "Fekete" "Sötét" "Világos" diff --git a/features/preferences/impl/src/main/res/values-pl/translations.xml b/features/preferences/impl/src/main/res/values-pl/translations.xml index fb1750e056..93c02d9f95 100644 --- a/features/preferences/impl/src/main/res/values-pl/translations.xml +++ b/features/preferences/impl/src/main/res/values-pl/translations.xml @@ -33,15 +33,15 @@ "Dostawca powiadomień push" "Wyłącz edytor tekstu bogatego, aby pisać tekst Markdown ręcznie." "Potwierdzenia odczytania" - "Gdy wyłączona, Twoje potwierdzenia odczytania nie zostaną wysłane. Potwierdzenia od innych wciąż będą odbierane." + "Po wyłączeniu potwierdzenia odczytu nie będą wysyłane. Nadal będziesz otrzymywać potwierdzenia od innych użytkowników." "Udostępnij obecność" - "Gdy wyłączona, nie będziesz mógł wysyłać lub odbierać potwierdzeń odczytu ani powiadomień pisania." + "Po wyłączeniu nie będzie można wysyłać ani odbierać potwierdzeń odczytu i powiadomień o pisaniu." "Zawsze ukrywaj" "Zawsze pokazuj" "W pokojach prywatnych" "Ukryte media można zawsze wyświetlić, dotykając ich" "Pokaż media na osi czasu" - "Włącz opcję, aby wyświetlić źródło wiadomości na osi czasu." + "Włącz, aby móc wyświetlać źródło wiadomości na osi czasu." "Nie blokujesz żadnych użytkowników" "Odblokuj" "Będziesz mógł ponownie zobaczyć wszystkie wiadomości od tego użytkownika." diff --git a/features/preferences/impl/src/main/res/values-ro/translations.xml b/features/preferences/impl/src/main/res/values-ro/translations.xml index 69eddf05f5..9c261d75fb 100644 --- a/features/preferences/impl/src/main/res/values-ro/translations.xml +++ b/features/preferences/impl/src/main/res/values-ro/translations.xml @@ -59,6 +59,7 @@ "Doriți experiențe noi?" "Laboratoare" "Setări adiționale" + "Ton de apel" "Apeluri audio și video" "Nepotrivire de configurație" "Am simplificat Setările pentru notificări pentru a face opțiunile mai ușor de găsit. @@ -79,14 +80,38 @@ Dacă continuați, unele dintre setările dumneavoastră pot fi modificate.""Invitații" "Serverul dumneavoastră nu acceptă această opțiune în camerele criptate, este posibil să nu primiți notificări în unele camere." "Mențiuni" + "Alegeți un alt sunet…" + "Se utilizează în prezent %1$s" + "Sunet de mesaj" + "Sunet de mesaj" "Toate" "Mențiuni" "Anunță-mă pentru" "Anunțați-mă pentru @room" + "Personalizat" + "Sunet personalizat…" + "Eroare la ștergerea fișierului" + "Element Implicit" + "Element Fade" + "Eroare la importul fișierului" + "A fost intâmpinată o problemă la previzualizarea sunetului de alertă" + "Sunet" + "Ignorați eroarea privind sunetul de alertă" + "A fost întâmpinată o problemă la setarea sunetului de alertă" + "Silențios" + "Implicit sistem" "Pentru a primi notificări, vă rugăm să vă schimbați %1$s." "Setări de sistem" "Notificările de sistem sunt dezactivate" "Notificări" + "Plecat" + "Revin imediat" + "Personalizat…" + "Status personalizat…" + "Timp de concentrare" + "Într-o ședință" + "Pe drum" + "Care este statusul dumneavoastră?" "Negru" "Întunecat" "Deschis" diff --git a/features/preferences/impl/src/main/res/values-zh-rTW/translations.xml b/features/preferences/impl/src/main/res/values-zh-rTW/translations.xml index 03892ce980..e9e973fde8 100644 --- a/features/preferences/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/preferences/impl/src/main/res/values-zh-rTW/translations.xml @@ -11,6 +11,13 @@ "在聊天室邀請請求中隱藏大頭貼" "在時間軸中隱藏媒體預覽" "實驗室" + "觸發更新所需的移動距離。" + "請確保已為此應用程式啟用「精確位置」功能。若要變更此權限,請前往 %1$s。" + "應用程式設定" + "即時位置更新" + + "每 %1$d 公尺" + "上傳照片與影片更快且減少資料使用量" "最佳化媒體品質" "管理與安全" @@ -50,6 +57,7 @@ "想不想來點新花樣?" "實驗室" "其他設定" + "通話鈴聲" "音訊與視訊通話" "組態錯誤" "我們簡化了通知設定,讓選項更容易搜尋。您過去選擇的某些自訂設定將不會在此顯示,但它們仍有作用。 @@ -68,14 +76,39 @@ "邀請" "您的家伺服器在加密聊天室中不支援此選項,可能無法收到部份聊天室的通知。" "提及" + "選擇其他音效⋯⋯" + "目前正在使用 %1$s" + "訊息音效" + "訊息音效" "全部" "提及" "通知我" "於 @room 通知我" + "自訂" + "自訂音效⋯⋯" + "刪除檔案時發生錯誤" + "Element 預設值" + "Element Fade" + "匯入檔案時發生錯誤" + "預覽警示音時發生問題" + "音效" + "忽略警示音錯誤" + "設定警示音時發生問題" + "靜音" + "系統預設值" "要收到通知,請變更您的 %1$s。" "系統設定" "已關閉系統通知" "通知" + "離開" + "稍後回來" + "自訂⋯⋯" + "自訂狀態⋯⋯" + "專注時間" + "在會議中" + "在路上" + "您的狀態如何?" + "黑色" "深色" "淺色" "系統" diff --git a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUserViewTest.kt b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUserViewTest.kt index 467ace4675..58e0cf467f 100644 --- a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUserViewTest.kt +++ b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUserViewTest.kt @@ -13,8 +13,10 @@ package io.element.android.features.preferences.impl.blockedusers import androidx.activity.ComponentActivity import androidx.compose.ui.test.AndroidComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.longClick import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.v2.runAndroidComposeUiTest import io.element.android.features.preferences.impl.R import io.element.android.libraries.architecture.AsyncAction @@ -57,6 +59,20 @@ class BlockedUserViewTest : RobolectricTest() { eventsRecorder.assertSingle(BlockedUsersEvents.Unblock(userList.first().userId)) } + @Test + fun `long clicking on a user emits the expected Event`() = runAndroidComposeUiTest { + val eventsRecorder = EventsRecorder() + val userList = aMatrixUserList() + setBlockedUsersView( + aBlockedUsersState( + blockedUsers = userList, + eventSink = eventsRecorder + ), + ) + onNodeWithText(userList.first().displayName.orEmpty()).performTouchInput { longClick() } + eventsRecorder.assertSingle(BlockedUsersEvents.CopyToClipboard(userList.first().userId)) + } + @Test fun `clicking on cancel sends a BlockedUsersEvents`() = runAndroidComposeUiTest { val eventsRecorder = EventsRecorder() diff --git a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenterTest.kt b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenterTest.kt index d3ac29df9a..4e0164b2a0 100644 --- a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenterTest.kt +++ b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/blockedusers/BlockedUsersPresenterTest.kt @@ -12,7 +12,9 @@ import app.cash.molecule.RecompositionMode import app.cash.molecule.moleculeFlow import app.cash.turbine.test import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.androidutils.clipboard.FakeClipboardHelper import io.element.android.libraries.architecture.AsyncAction +import io.element.android.libraries.designsystem.utils.snackbar.SnackbarDispatcher import io.element.android.libraries.featureflag.api.FeatureFlagService import io.element.android.libraries.featureflag.api.FeatureFlags import io.element.android.libraries.featureflag.test.FakeFeatureFlagService @@ -21,6 +23,7 @@ import io.element.android.libraries.matrix.test.AN_EXCEPTION import io.element.android.libraries.matrix.test.A_USER_ID import io.element.android.libraries.matrix.test.A_USER_ID_2 import io.element.android.libraries.matrix.test.FakeMatrixClient +import io.element.android.libraries.ui.strings.CommonStrings import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.runTest @@ -169,6 +172,29 @@ class BlockedUsersPresenterTest { } } + @Test + fun `present - copy user id to clipboard`() = runTest { + val clipboardHelper = FakeClipboardHelper() + val matrixClient = FakeMatrixClient( + ignoredUsersFlow = MutableStateFlow(persistentListOf(A_USER_ID)) + ) + val presenter = aBlockedUsersPresenter( + matrixClient = matrixClient, + clipboardHelper = clipboardHelper, + ) + moleculeFlow(RecompositionMode.Immediate) { + presenter.present() + }.test { + val initialState = awaitItem() + assertThat(initialState.snackbarMessage).isNull() + initialState.eventSink(BlockedUsersEvents.CopyToClipboard(A_USER_ID)) + + assertThat(clipboardHelper.clipboardContents).isEqualTo(A_USER_ID.value) + assertThat(awaitItem().snackbarMessage?.messageResId).isEqualTo(CommonStrings.common_copied_to_clipboard) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `present - confirm unblock without a pending blocked user does nothing`() = runTest { val presenter = aBlockedUsersPresenter() @@ -183,8 +209,12 @@ class BlockedUsersPresenterTest { private fun aBlockedUsersPresenter( matrixClient: FakeMatrixClient = FakeMatrixClient(), featureFlagService: FeatureFlagService = FakeFeatureFlagService(), + clipboardHelper: FakeClipboardHelper = FakeClipboardHelper(), + snackbarDispatcher: SnackbarDispatcher = SnackbarDispatcher(), ) = BlockedUsersPresenter( matrixClient = matrixClient, featureFlagService = featureFlagService, + clipboardHelper = clipboardHelper, + snackbarDispatcher = snackbarDispatcher, ) } diff --git a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenterTest.kt b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenterTest.kt index bb688f498d..3b2645783f 100644 --- a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenterTest.kt +++ b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/developer/DeveloperSettingsPresenterTest.kt @@ -23,12 +23,14 @@ import io.element.android.libraries.androidutils.filesize.FakeFileSizeFormatter import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.core.data.megaBytes +import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.matrix.api.analytics.GetDatabaseSizesUseCase import io.element.android.libraries.matrix.api.analytics.SdkStoreSizes import io.element.android.libraries.matrix.api.core.DeviceId import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.matrix.test.A_DEVICE_ID import io.element.android.libraries.matrix.test.A_SESSION_ID +import io.element.android.libraries.matrix.test.core.aBuildMeta import io.element.android.tests.testutils.WarmUpRule import io.element.android.tests.testutils.lambda.lambdaRecorder import io.element.android.tests.testutils.lambda.value @@ -108,10 +110,8 @@ class DeveloperSettingsPresenterTest { fun `present - enterprise build can change the brand color`() = runTest { val overrideBrandColorResult = lambdaRecorder { _, _ -> } val presenter = createDeveloperSettingsPresenter( - enterpriseService = FakeEnterpriseService( - isEnterpriseBuild = true, - overrideBrandColorResult = overrideBrandColorResult, - ) + enterpriseService = FakeEnterpriseService(overrideBrandColorResult = overrideBrandColorResult), + buildMeta = aBuildMeta(isEnterpriseBuild = true), ) presenter.test { skipItems(1) @@ -179,6 +179,7 @@ class DeveloperSettingsPresenterTest { vacuumStoresUseCase: VacuumStoresUseCase = VacuumStoresUseCase {}, databaseSizesUseCase: GetDatabaseSizesUseCase = GetDatabaseSizesUseCase { Result.success(SdkStoreSizes(null, null, null, null)) }, markAllRoomsAsRead: FakeMarkAllRoomsAsRead = FakeMarkAllRoomsAsRead(), + buildMeta: BuildMeta = aBuildMeta(), ): DeveloperSettingsPresenter { return DeveloperSettingsPresenter( appDeveloperSettingsPresenter = { anAppDeveloperSettingsState() }, @@ -191,6 +192,7 @@ class DeveloperSettingsPresenterTest { databaseSizesUseCase = databaseSizesUseCase, fileSizeFormatter = FakeFileSizeFormatter(), markAllRoomsAsRead = markAllRoomsAsRead, + buildMeta = buildMeta, ) } } diff --git a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenterTest.kt b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenterTest.kt index a09afdeb6f..e9897259ae 100644 --- a/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenterTest.kt +++ b/features/preferences/impl/src/test/kotlin/io/element/android/features/preferences/impl/userstatus/UserStatusPresenterTest.kt @@ -8,9 +8,11 @@ package io.element.android.features.preferences.impl.userstatus import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.emoji.test.fakeEmojiPickerPresenterFactory import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.UserStatus +import io.element.android.libraries.matrix.test.AN_EXCEPTION import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.tests.testutils.test import kotlinx.coroutines.test.runTest @@ -61,6 +63,24 @@ class UserStatusPresenterTest { val newState = awaitItem() assertThat(newState.pickerState).isEqualTo(UserStatusPickerState.Hidden) assertThat(newState.displayedStatus).isEqualTo(DisplayedStatus.UserSet(status)) + assertThat(newState.updateStatusAction).isInstanceOf(AsyncAction.Success::class.java) + assertThat(client.setUserStatusCalled).isTrue() + } + } + + @Test + fun `Set event failure surfaces a Failure action`() = runTest { + val client = FakeMatrixClient().apply { + setUserStatusResult = Result.failure(AN_EXCEPTION) + } + createPresenter(client).test { + val status = UserStatus(emoji = "💬", text = "In a meeting") + awaitItem().eventSink(UserStatusEvent.SetStatus(status)) + val newState = awaitItem() + assertThat(newState.pickerState).isEqualTo(UserStatusPickerState.Hidden) + // On failure the SDK does not emit a new profile, so nothing is displayed. + assertThat(newState.displayedStatus).isNull() + assertThat(newState.updateStatusAction).isInstanceOf(AsyncAction.Failure::class.java) assertThat(client.setUserStatusCalled).isTrue() } } @@ -121,6 +141,25 @@ class UserStatusPresenterTest { val clearedState = awaitItem() assertThat(clearedState.pickerState).isEqualTo(UserStatusPickerState.Hidden) assertThat(clearedState.displayedStatus).isNull() + assertThat(clearedState.updateStatusAction).isInstanceOf(AsyncAction.Success::class.java) + assertThat(client.clearUserStatusCalled).isTrue() + } + } + + @Test + fun `Clear event failure surfaces a Failure action`() = runTest { + val client = FakeMatrixClient().apply { + clearUserStatusResult = Result.failure(AN_EXCEPTION) + } + createPresenter(client).test { + val status = UserStatus(emoji = "☕", text = "Be right back") + awaitItem().eventSink(UserStatusEvent.SetStatus(status)) + awaitItem().eventSink(UserStatusEvent.ClearStatus) + val clearedState = awaitItem() + assertThat(clearedState.pickerState).isEqualTo(UserStatusPickerState.Hidden) + // Clear failed, so the previously set status is still displayed. + assertThat(clearedState.displayedStatus).isEqualTo(DisplayedStatus.UserSet(status)) + assertThat(clearedState.updateStatusAction).isInstanceOf(AsyncAction.Failure::class.java) assertThat(client.clearUserStatusCalled).isTrue() } } diff --git a/features/preferences/test/build.gradle.kts b/features/preferences/test/build.gradle.kts index a066fe4707..5b8969796a 100644 --- a/features/preferences/test/build.gradle.kts +++ b/features/preferences/test/build.gradle.kts @@ -16,5 +16,7 @@ android { dependencies { implementation(projects.libraries.architecture) implementation(projects.features.preferences.api) + implementation(projects.libraries.matrix.api) + implementation(libs.coroutines.core) implementation(projects.tests.testutils) } diff --git a/features/preferences/test/src/main/kotlin/io/element/android/features/preferences/test/FakeCacheService.kt b/features/preferences/test/src/main/kotlin/io/element/android/features/preferences/test/FakeCacheService.kt new file mode 100644 index 0000000000..9696a2050b --- /dev/null +++ b/features/preferences/test/src/main/kotlin/io/element/android/features/preferences/test/FakeCacheService.kt @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.preferences.test + +import io.element.android.features.preferences.api.CacheService +import io.element.android.libraries.matrix.api.core.SessionId +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow + +class FakeCacheService( + override val clearedCacheEventFlow: Flow = emptyFlow(), +) : CacheService diff --git a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/RageshakeFeatureAvailability.kt b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/RageshakeFeatureAvailability.kt index bc72e7021b..c4205c1575 100644 --- a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/RageshakeFeatureAvailability.kt +++ b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/RageshakeFeatureAvailability.kt @@ -10,6 +10,10 @@ package io.element.android.features.rageshake.api import kotlinx.coroutines.flow.Flow +/** + * Tells whether bug reporting is available, which an enterprise deployment can turn off. + */ fun interface RageshakeFeatureAvailability { + /** Whether the rageshake and bug report entry points should be offered to the user. */ fun isAvailable(): Flow } diff --git a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/logs/LogFilesRemover.kt b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/logs/LogFilesRemover.kt index f8eee31675..a7b2961ab6 100644 --- a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/logs/LogFilesRemover.kt +++ b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/logs/LogFilesRemover.kt @@ -10,6 +10,9 @@ package io.element.android.features.rageshake.api.logs import java.io.File +/** + * Deletes the log files the app writes, used to keep them from growing without bound and to clear them on request. + */ interface LogFilesRemover { /** * Perform the log files removal. diff --git a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesStateProvider.kt b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesStatePreviewParam.kt similarity index 91% rename from features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesStateProvider.kt rename to features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesStatePreviewParam.kt index 1de65c1a69..28ecc9f187 100644 --- a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesStateProvider.kt +++ b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.rageshake.api.preferences import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class RageshakePreferencesStateProvider : PreviewParameterProvider { +open class RageshakePreferencesStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRageshakePreferencesState(isEnabled = true, isSupported = true, sensitivity = 0.5f), diff --git a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesView.kt b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesView.kt index a227d0ffcf..7b01f62b82 100644 --- a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesView.kt +++ b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/preferences/RageshakePreferencesView.kt @@ -68,6 +68,8 @@ fun RageshakePreferencesView( @PreviewsDayNight @Composable -internal fun RageshakePreferencesViewPreview(@PreviewParameter(RageshakePreferencesStateProvider::class) state: RageshakePreferencesState) = ElementPreview { +internal fun RageshakePreferencesViewPreview(@PreviewParameter( + RageshakePreferencesStatePreviewParam::class +) state: RageshakePreferencesState) = ElementPreview { RageshakePreferencesView(state) } diff --git a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/reporter/BugReporter.kt b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/reporter/BugReporter.kt index 631a51a686..c1611f30b5 100644 --- a/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/reporter/BugReporter.kt +++ b/features/rageshake/api/src/main/kotlin/io/element/android/features/rageshake/api/reporter/BugReporter.kt @@ -10,6 +10,11 @@ package io.element.android.features.rageshake.api.reporter import java.io.File +/** + * Uploads bug reports, including the log files the app has been writing. + * + * Progress and the outcome are reported through the listener passed to [sendBugReport] rather than by returning or throwing. + */ interface BugReporter { /** * Send a bug report. @@ -35,17 +40,21 @@ interface BugReporter { ) /** - * Provide the log directory. + * Provide the log directory, i.e. where the rotating log files are written. */ fun logDirectory(): File /** - * Set the current tracing log level. + * Set the current tracing log level, so it can be reported alongside the bug. + * + * @param logLevel the log level currently in effect. */ fun setCurrentTracingLogLevel(logLevel: String) /** * Save the logcat. + * + * @return the file the logcat was written to, or `null` when it could not be captured. */ fun saveLogCat(): File? } diff --git a/features/rageshake/api/src/main/res/values-ar/translations.xml b/features/rageshake/api/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..13f99159db --- /dev/null +++ b/features/rageshake/api/src/main/res/values-ar/translations.xml @@ -0,0 +1,7 @@ + + + "%1$s أُغلِق قسرياً في آخر مرة استخدمه. أتودّ مشاركة بلاغ إغلاق قسري معنا؟" + "يظهر أنك تهز الهاتز بسرعة. أتودّ فتح شاشة الإبلاغ عن عطل؟" + "رج الهاتف للإبلاغ عن خطأ" + "عتبة الكشف" + diff --git a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportPresenter.kt b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportPresenter.kt index 85731ae959..c7c706fa68 100644 --- a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportPresenter.kt +++ b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportPresenter.kt @@ -86,7 +86,7 @@ class BugReportPresenter( fun handleEvent(event: BugReportEvents) { when (event) { BugReportEvents.SendBugReport -> { - if (formState.value.description.length < 10) { + if (formState.value.description.length < 10 && formState.value.ghIssueNumber == null) { sendingAction.value = AsyncAction.Failure(BugReportFormError.DescriptionTooShort) } else { sendingAction.value = AsyncAction.Loading diff --git a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportStateProvider.kt b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportStatePreviewParam.kt similarity index 94% rename from features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportStateProvider.kt rename to features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportStatePreviewParam.kt index 0afd06f22a..1e08c055b4 100644 --- a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportStateProvider.kt +++ b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.rageshake.impl.bugreport import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class BugReportStateProvider : PreviewParameterProvider { +open class BugReportStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aBugReportState(), diff --git a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportView.kt b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportView.kt index fede373627..2c8dba4af3 100644 --- a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportView.kt +++ b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/bugreport/BugReportView.kt @@ -232,7 +232,7 @@ fun BugReportView( @Preview(heightDp = 1000) @Composable -internal fun BugReportViewDayPreview(@PreviewParameter(BugReportStateProvider::class) state: BugReportState) = ElementPreview { +internal fun BugReportViewDayPreview(@PreviewParameter(BugReportStatePreviewParam::class) state: BugReportState) = ElementPreview { BugReportView( state = state, onSuccess = {}, @@ -243,7 +243,7 @@ internal fun BugReportViewDayPreview(@PreviewParameter(BugReportStateProvider::c @Preview(heightDp = 1000, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable -internal fun BugReportViewNightPreview(@PreviewParameter(BugReportStateProvider::class) state: BugReportState) = ElementPreview { +internal fun BugReportViewNightPreview(@PreviewParameter(BugReportStatePreviewParam::class) state: BugReportState) = ElementPreview { BugReportView( state = state, onSuccess = {}, diff --git a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/di/RageshakeModule.kt b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/di/RageshakeBindingContainer.kt similarity index 97% rename from features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/di/RageshakeModule.kt rename to features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/di/RageshakeBindingContainer.kt index 475127a345..04edb3c0ac 100644 --- a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/di/RageshakeModule.kt +++ b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/di/RageshakeBindingContainer.kt @@ -22,7 +22,7 @@ import io.element.android.libraries.architecture.Presenter @ContributesTo(AppScope::class) @BindingContainer -interface RageshakeModule { +interface RageshakeBindingContainer { @Binds fun bindRageshakePreferencesPresenter(presenter: RageshakePreferencesPresenter): Presenter diff --git a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporter.kt b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporter.kt index 96bd7adfce..c1000784fc 100755 --- a/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporter.kt +++ b/features/rageshake/impl/src/main/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporter.kt @@ -152,7 +152,7 @@ class DefaultBugReporter( append("\n\n\n\n--------------------------------- crash call stack ---------------------------------\n") append(crashCallStack) } - } + }.truncateDescription() val gzippedFiles = mutableListOf() var filesTooBig = emptyList() @@ -494,4 +494,13 @@ class DefaultBugReporter( private fun countLogLines(file: File): Int { return file.reader().useLines { it.count() } } + + private fun String.truncateDescription(): String { + return if (length <= RageshakeConfig.MAX_DESCRIPTION_SIZE) { + this + } else { + take(RageshakeConfig.MAX_DESCRIPTION_SIZE) + + "\n\n--------------------------------- truncated, see the attached logs ---------------------------------" + } + } } diff --git a/features/rageshake/impl/src/main/res/values-ar/translations.xml b/features/rageshake/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..5fd8157467 --- /dev/null +++ b/features/rageshake/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,22 @@ + + + "إرفاق لقطة شاشة" + "لا مانع من التواصل معي إذا كان عندكم أي أسئلة إضافية." + "تواصل معي" + "تعديل لقطة الشاشة" + "صِف مشكلتك رجاءً. ما الذي قمت به؟ ما كنت تتوقع أن يحصل؟ وما الذي حصل فعلياً. زوّدنا بأكبر قدر من المعلومات رجاءً." + "صِف المشكلة…" + "إن كان ممكناً فاكتب الوصف بالإنجليزية." + "الوصف قصير جدًا، يُرجى تقديم مزيد من التفاصيل حول ما حدث. شكرًا!" + "يمكنك إدخال رقم مشكلة مرتبطة على GitHub، إن وجدت." + "مشكلة على GitHub" + "أرسل الـcrash logs" + "السماح بالـLogs" + "سجلاتك كبيرة جدًا، لذلك لا يمكن تضمينها في هذا البلاغ. يرجى إرسالها إلينا بطريقة أخرى." + "إرسال لقطة شاشة" + "سيتمّ تضمين السجلّات (logs) مع رسالتك لنتأكد من أن كل شيء يشتغل كما يجب. لكي ترسل الرسالة بلا سجلّات فأطفئ هذا الخيار." + "%1$s أُغلِق قسرياً في آخر مرة استخدمه. أتودّ مشاركة بلاغ إغلاق قسري معنا؟" + "إذا كنت تواجه مشكلات في الإشعارات، يمكن أن يساعد رفع قواعد الإشعارات الفورية في تحديد السبب الجذري. لاحظ أن هذه القواعد قد تحتوي على معلومات خاصة، مثل اسم العرض الخاص بك أو الكلمات المفتاحية التي تريد تلقي إشعارات عنها." + "إرسال إعدادات الإشعارات" + "عرض السجلات" + diff --git a/features/rageshake/impl/src/main/res/values-es/translations.xml b/features/rageshake/impl/src/main/res/values-es/translations.xml index 5c21e4a9bd..5841d8b29b 100644 --- a/features/rageshake/impl/src/main/res/values-es/translations.xml +++ b/features/rageshake/impl/src/main/res/values-es/translations.xml @@ -8,11 +8,15 @@ "Describe el problema…" "Si es posible, escribe la descripción en inglés." "La descripción es demasiado corta. Proporciona más detalles sobre lo sucedido. ¡Gracias!" + "Puedes introducir el número de una incidencia de GitHub asociada, si la hubiere." + "Incidencia de GitHub" "Enviar registros de fallos" "Permitir registros" "Tus registros de errores son demasiado grandes y no pueden añadirse a este informe, por favor envíanoslos de otra manera." "Enviar captura de pantalla" "Los registros se incluirán con tu mensaje para asegurarse de que todo funciona correctamente. Para enviar tu mensaje sin registros, desactiva esta opción." "%1$s se cerró inesperadamente la última vez que se lo usaste. ¿Quieres compartir un informe de error con nosotros?" + "Si tienes problemas con las notificaciones, enviar las reglas de notificaciones push puede ayudarnos a identificar la causa raíz. Ten en cuenta que estas reglas pueden contener información privada, como tu nombre público o las palabras clave para las que quieres recibir notificaciones." + "Enviar ajustes de notificación" "Ver los registros" diff --git a/features/rageshake/impl/src/main/res/values-fa/translations.xml b/features/rageshake/impl/src/main/res/values-fa/translations.xml index 2e27f97ba6..85d07c41cd 100644 --- a/features/rageshake/impl/src/main/res/values-fa/translations.xml +++ b/features/rageshake/impl/src/main/res/values-fa/translations.xml @@ -8,10 +8,15 @@ "شرح مشکل…" "ترجیحاً توضیحات را به زبان انگلیسی بنویسید." "توضیحات خیلی کوتاه است، لطفاً جزئیات بیشتری در مورد آنچه اتفاق افتاده ارائه دهید. متشکرم!" + "در صورت وجود، می‌توانید شماره مشکل مرتبط با GitHub را وارد کنید." + "مسئله GitHub" "ارسال رخدادنگارهای خطا" "اجازه به گزارش‌ها" + "گزارش‌های شما بیش از حد بزرگ هستند، بنابراین نمی‌توان آنها را در این گزارش گنجاند، لطفاً آنها را از طریق دیگری برای ما ارسال کنید." "ارسال تصویر صفحه" "برای اطمینان از درست کار کردن همه‌چیز گزارش‌ها در پیامتان قرار خواهد گرفت. برای فرستادن پیام بدون گزارش‌ها این تنظیم را خاموش کنید." "%1$sآخرین باری که استفاده شد، از کار افتاد. آیا مایلید گزارش خرابی را با ما به اشتراک بگذارید؟" + "اگر با اعلان‌ها مشکل دارید، آپلود قوانین ارسال اعلان می‌تواند به ما در شناسایی علت اصلی کمک کند. توجه داشته باشید که این قوانین می‌توانند حاوی اطلاعات خصوصی مانند نام نمایشی یا کلمات کلیدی شما باشند که باید برای آنها اعلان دریافت کنید." + "تنظیمات ارسال اعلان" "دیدن گزارش‌ها" diff --git a/features/rageshake/impl/src/main/res/values-ro/translations.xml b/features/rageshake/impl/src/main/res/values-ro/translations.xml index f342ffd4c5..cdcfbdfbc8 100644 --- a/features/rageshake/impl/src/main/res/values-ro/translations.xml +++ b/features/rageshake/impl/src/main/res/values-ro/translations.xml @@ -8,6 +8,8 @@ "Descrieți problema…" "Dacă posibil, vă rugăm să scrieți descrierea în engleză." "Descrierea este prea scurtă, vă rugăm să oferiți mai multe detalii despre ceea ce s-a întâmplat. Vă mulțumim!" + "Puteți introduce numărul unui tichet GitHub asociat, dacă există." + "Tichet GitHub" "Trimiteți log-uri" "Permiteți log-uri" "Jurnalele dumneavoastră sunt prea mari și nu pot fi incluse în acest raport. Vă rugăm să ni le trimiteți prin altă metodă." diff --git a/features/rageshake/impl/src/main/res/values-zh-rTW/translations.xml b/features/rageshake/impl/src/main/res/values-zh-rTW/translations.xml index 10252ab699..2c5c310370 100644 --- a/features/rageshake/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/rageshake/impl/src/main/res/values-zh-rTW/translations.xml @@ -8,6 +8,8 @@ "描述問題…" "如果方便的話,請使用英文。" "您的描述太短了,請提供更多細節。謝謝!" + "若有相關的 GitHub 議題編號,請在此處輸入。" + "GitHub 議題" "傳送當機紀錄" "提供日誌" "您的紀錄檔太大了,無法包含在此報告中,請透過其他方式傳送給我們。" diff --git a/features/rageshake/impl/src/test/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporterTest.kt b/features/rageshake/impl/src/test/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporterTest.kt index ad29e5ed3f..7bb2add0e5 100755 --- a/features/rageshake/impl/src/test/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporterTest.kt +++ b/features/rageshake/impl/src/test/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporterTest.kt @@ -309,6 +309,68 @@ class DefaultBugReporterTest : RobolectricTest() { assertThat(foundValues["label"]).isEqualTo("crash") } + @Test + fun `test sendBugReport truncates a description which is too long`() = runTest { + val server = MockWebServer() + server.enqueue( + MockResponse() + .setResponseCode(200) + ) + server.start() + val hugeCrashCallStack = "a".repeat(RageshakeConfig.MAX_DESCRIPTION_SIZE * 2) + val sut = createDefaultBugReporter( + server = server, + crashDataStore = FakeCrashDataStore(hugeCrashCallStack, true), + ) + + sut.sendBugReport( + withDevicesLogs = true, + withCrashLogs = true, + withScreenshot = true, + problemDescription = "a bug occurred", + canContact = true, + listener = NoopBugReporterListener(), + ) + val request = server.takeRequest() + + val text = collectValuesFromFormData(request)["text"]!! + assertThat(text).startsWith("a bug occurred") + assertThat(text).contains("truncated") + assertThat(text.length).isAtMost(RageshakeConfig.MAX_DESCRIPTION_SIZE + TRUNCATION_MARKER_MAX_SIZE) + assertThat(text.length).isLessThan(GITHUB_MAX_ISSUE_BODY_SIZE) + server.shutdown() + } + + @Test + fun `test sendBugReport does not truncate a description which fits`() = runTest { + val server = MockWebServer() + server.enqueue( + MockResponse() + .setResponseCode(200) + ) + server.start() + val sut = createDefaultBugReporter( + server = server, + crashDataStore = FakeCrashDataStore("I did crash", true), + ) + + sut.sendBugReport( + withDevicesLogs = true, + withCrashLogs = true, + withScreenshot = true, + problemDescription = "a bug occurred", + canContact = true, + listener = NoopBugReporterListener(), + ) + val request = server.takeRequest() + + val text = collectValuesFromFormData(request)["text"]!! + assertThat(text).startsWith("a bug occurred") + assertThat(text).endsWith("I did crash") + assertThat(text).doesNotContain("truncated") + server.shutdown() + } + private fun collectValuesFromFormData(request: RecordedRequest): HashMap { val boundary = request.headers["Content-Type"]!!.split("=").last() val foundValues = HashMap() @@ -535,5 +597,7 @@ class DefaultBugReporterTest : RobolectricTest() { companion object { private const val EXPECTED_NUMBER_OF_PROGRESS_VALUE = 18 + private const val GITHUB_MAX_ISSUE_BODY_SIZE = 65_536 + private const val TRUNCATION_MARKER_MAX_SIZE = 200 } } diff --git a/features/rageshake/test/build.gradle.kts b/features/rageshake/test/build.gradle.kts index afc5e51499..faad812d73 100644 --- a/features/rageshake/test/build.gradle.kts +++ b/features/rageshake/test/build.gradle.kts @@ -14,6 +14,7 @@ android { } dependencies { + implementation(projects.libraries.architecture) implementation(projects.features.rageshake.api) implementation(libs.coroutines.core) implementation(projects.tests.testutils) diff --git a/features/rageshake/test/src/main/kotlin/io/element/android/features/rageshake/test/FakeBugReportEntryPoint.kt b/features/rageshake/test/src/main/kotlin/io/element/android/features/rageshake/test/FakeBugReportEntryPoint.kt new file mode 100644 index 0000000000..d6e1a47368 --- /dev/null +++ b/features/rageshake/test/src/main/kotlin/io/element/android/features/rageshake/test/FakeBugReportEntryPoint.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.rageshake.test + +import com.bumble.appyx.core.modality.BuildContext +import com.bumble.appyx.core.node.Node +import io.element.android.features.rageshake.api.bugreport.BugReportEntryPoint +import io.element.android.tests.testutils.lambda.lambdaError + +class FakeBugReportEntryPoint( + private val createNodeResult: (BuildContext, BugReportEntryPoint.Callback) -> Node = { _, _ -> lambdaError() }, +) : BugReportEntryPoint { + override fun createNode( + parentNode: Node, + buildContext: BuildContext, + callback: BugReportEntryPoint.Callback, + ): Node = createNodeResult(buildContext, callback) +} diff --git a/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomStateProvider.kt b/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomStatePreviewParam.kt similarity index 93% rename from features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomStateProvider.kt rename to features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomStatePreviewParam.kt index 8baae080f5..11d2777446 100644 --- a/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomStateProvider.kt +++ b/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.reportroom.impl import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class ReportRoomStateProvider : PreviewParameterProvider { +open class ReportRoomStatePreviewParam : PreviewParameterProvider { companion object { private const val A_REPORT_ROOM_REASON = "Inappropriate content" } diff --git a/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomView.kt b/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomView.kt index a754825dcc..7b614b13cb 100644 --- a/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomView.kt +++ b/features/reportroom/impl/src/main/kotlin/io/element/android/features/reportroom/impl/ReportRoomView.kt @@ -139,7 +139,7 @@ fun ReportRoomView( @PreviewsDayNight @Composable internal fun ReportRoomViewPreview( - @PreviewParameter(ReportRoomStateProvider::class) state: ReportRoomState + @PreviewParameter(ReportRoomStatePreviewParam::class) state: ReportRoomState ) = ElementPreview { ReportRoomView( state = state, diff --git a/features/reportroom/impl/src/main/res/values-ar/translations.xml b/features/reportroom/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..1068833e9b --- /dev/null +++ b/features/reportroom/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,8 @@ + + + "تم إرسال بلاغك بنجاح، لكننا واجهنا مشكلة أثناء محاولة مغادرة الغرفة. يرجى المحاولة مرة أخرى." + "تعذّرت مغادرة الغرفة" + "أبلغ مسؤولك عن هذه الغرفة. إذا كانت الرسائل مشفّرة، فلن يتمكن مسؤولك من قراءتها." + "صِف سبب الإبلاغ…" + "الإبلاغ عن الغرفة" + diff --git a/features/reportroom/impl/src/main/res/values-fa/translations.xml b/features/reportroom/impl/src/main/res/values-fa/translations.xml index 9930e9ceac..a75095ff90 100644 --- a/features/reportroom/impl/src/main/res/values-fa/translations.xml +++ b/features/reportroom/impl/src/main/res/values-fa/translations.xml @@ -1,6 +1,8 @@ + "گزارش شما با موفقیت ارسال شد، اما هنگام تلاش برای خروج از اتاق با مشکلی مواجه شدیم. لطفاً دوباره امتحان کنید." "ناتوان از ترک اتاق" + "این اتاق را به مدیر خود گزارش دهید. اگر پیام‌ها رمزگذاری شده باشند، مدیر شما قادر به خواندن آنها نخواهد بود." "شرح دلیل گزارش…" "گزارش اتاق" diff --git a/features/rolesandpermissions/api/src/main/kotlin/io/element/android/features/rolesandpermissions/api/ChangeRoomMemberRolesEntryPoint.kt b/features/rolesandpermissions/api/src/main/kotlin/io/element/android/features/rolesandpermissions/api/ChangeRoomMemberRolesEntryPoint.kt index 7cfdfefae0..4f823387f3 100644 --- a/features/rolesandpermissions/api/src/main/kotlin/io/element/android/features/rolesandpermissions/api/ChangeRoomMemberRolesEntryPoint.kt +++ b/features/rolesandpermissions/api/src/main/kotlin/io/element/android/features/rolesandpermissions/api/ChangeRoomMemberRolesEntryPoint.kt @@ -22,8 +22,18 @@ fun interface ChangeRoomMemberRolesEntryPoint : FeatureEntryPoint { listType: ChangeRoomMemberRolesListType, ): Node + /** + * Lets a caller outside this feature wait for the role change to finish, which is needed when leaving a room depends on it. + */ interface NodeProxy { + /** The room whose member roles are being changed. */ val roomId: RoomId + + /** + * Suspends until the user finishes or abandons the flow. + * + * @return true when roles were actually changed, false when the user backed out. + */ suspend fun waitForCompletion(): Boolean } } diff --git a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsStateProvider.kt b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsStatePreviewParam.kt similarity index 96% rename from features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsStateProvider.kt rename to features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsStatePreviewParam.kt index 700a82795e..95e3d48c2a 100644 --- a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsStateProvider.kt +++ b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.matrix.api.room.powerlevels.RoomPowerLevelsV import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableMap -class ChangeRoomPermissionsStateProvider : PreviewParameterProvider { +class ChangeRoomPermissionsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aChangeRoomPermissionsState(), diff --git a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsView.kt b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsView.kt index bb702ed90a..aba7a671a8 100644 --- a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsView.kt +++ b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/permissions/ChangeRoomPermissionsView.kt @@ -132,7 +132,7 @@ private fun titleForType(type: RoomPermissionType): String = when (type) { @PreviewsDayNight @Composable -internal fun ChangeRoomPermissionsViewPreview(@PreviewParameter(ChangeRoomPermissionsStateProvider::class) state: ChangeRoomPermissionsState) { +internal fun ChangeRoomPermissionsViewPreview(@PreviewParameter(ChangeRoomPermissionsStatePreviewParam::class) state: ChangeRoomPermissionsState) { ElementPreview { ChangeRoomPermissionsView( state = state, diff --git a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesStateProvider.kt b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesStatePreviewParam.kt similarity index 98% rename from features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesStateProvider.kt rename to features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesStatePreviewParam.kt index e6b71ef752..2d6f8e02d0 100644 --- a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesStateProvider.kt +++ b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesStatePreviewParam.kt @@ -29,7 +29,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -class ChangeRolesStateProvider : PreviewParameterProvider { +class ChangeRolesStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aChangeRolesState(), diff --git a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesView.kt b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesView.kt index b2c88efede..05bb77dfd4 100644 --- a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesView.kt +++ b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/roles/ChangeRolesView.kt @@ -393,7 +393,7 @@ private fun MemberRow( @PreviewsDayNight @Composable -internal fun ChangeRolesViewPreview(@PreviewParameter(ChangeRolesStateProvider::class) state: ChangeRolesState) { +internal fun ChangeRolesViewPreview(@PreviewParameter(ChangeRolesStatePreviewParam::class) state: ChangeRolesState) { ElementPreview { ChangeRolesView( state = state diff --git a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsStateProvider.kt b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsStatePreviewParam.kt similarity index 96% rename from features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsStateProvider.kt rename to features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsStatePreviewParam.kt index 45bd72db19..2fc39212d8 100644 --- a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsStateProvider.kt +++ b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import kotlinx.collections.immutable.toImmutableList -class RolesAndPermissionsStateProvider : PreviewParameterProvider { +class RolesAndPermissionsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRolesAndPermissionsState(roomSupportsOwners = false), diff --git a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsView.kt b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsView.kt index 3cf29c18cf..d9c09bbc64 100644 --- a/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsView.kt +++ b/features/rolesandpermissions/impl/src/main/kotlin/io/element/android/features/rolesandpermissions/impl/root/RolesAndPermissionsView.kt @@ -191,7 +191,7 @@ private fun ChangeOwnRoleBottomSheet( @PreviewsDayNight @Composable -internal fun RolesAndPermissionsViewPreview(@PreviewParameter(RolesAndPermissionsStateProvider::class) state: RolesAndPermissionsState) { +internal fun RolesAndPermissionsViewPreview(@PreviewParameter(RolesAndPermissionsStatePreviewParam::class) state: RolesAndPermissionsState) { ElementPreview { RolesAndPermissionsView( state = state, diff --git a/features/rolesandpermissions/impl/src/main/res/values-ar/translations.xml b/features/rolesandpermissions/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..75633a1273 --- /dev/null +++ b/features/rolesandpermissions/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,98 @@ + + + "مسؤول" + "حظر الأشخاص" + "تغيير الإعدادات" + "إزالة الرسائل" + "عضو" + "دعوة الأشخاص" + "مشاركة الموقع المباشر" + "إدارة المساحة" + "إدارة الغرف" + "إدارة الأعضاء" + "الرسائل والمحتوى" + "مشرف" + "إزالة الأشخاص" + "تغيير الصورة الرمزية" + "تعديل التفاصيل" + "تغيير الاسم" + "تغيير الموضوع" + "إرسال الرسائل" + "الصلاحيات" + "تعديل المسؤولين" + "لن تتمكن من التراجع عن هذا الإجراء. ستتم ترقية المستخدم ليحصل على مستوى الصلاحيات نفسه الذي لديك." + "إضافة مسؤول؟" + "لن تتمكن من التراجع عن هذا الإجراء. ستنقل الملكية إلى المستخدمين المحددين. بمجرد مغادرتك، سيصبح ذلك دائمًا." + "نقل الملكية؟" + "خفض الرتبة" + "لن تتمكن من التراجع عن هذا التغيير لأنك تخفض رتبتك. إذا كنت آخر مستخدم لديه صلاحيات في الغرفة، فسيكون من المستحيل استعادة الصلاحيات." + "خفض رتبتك؟" + "%1$s (قيد الانتظار)" + "(قيد الانتظار)" + "يتمتع المسؤولون تلقائيًا بصلاحيات المشرفين" + "يتمتع المالكون بامتيازات المسؤولين تلقائيًا." + "تعديل المشرفين" + "اختيار المالكين" + "المسؤولون" + "المشرفون" + "الأعضاء" + "لديك تغييرات غير محفوظة." + "حفظ التغييرات؟" + "لا يوجد مستخدمون محظورون." + + "%1$d محظورين" + "%1$d محظور" + "%1$d محظوران" + "%1$d محظورين" + "%1$d محظورًا" + "%1$d محظور" + + "تحقّق من الإملاء أو جرّب بحثًا جديدًا" + "لا توجد نتائج لـ “%1$s”" + + "%1$d شخص" + "%1$d شخص" + "%1$d شخصين" + "%1$d اشخاص" + "%1$d شخص" + "%1$d شخص" + + "حظر المستخدم" + "إزالة العضو فقط" + "إلغاء الحظر" + "يمكن لهذا المستخدم الانضمام إلى هذه الغرفة مرة أخرى عند دعوته." + "إلغاء حظر المستخدم" + "المحظورون" + "الأعضاء" + + "%1$d مدعوّين" + "%1$d مدعو" + "%1$d مدعوّان" + "%1$d مدعوّين" + "%1$d مدعوًا" + "%1$d مدعو" + + "قيد الانتظار" + "مسؤول" + "مشرف" + "مالك" + "أعضاء الغرفة" + "جارٍ رفع حظر %1$s" + "المسؤولون" + "المسؤولون والمالكون" + "تغيير دوري" + "خفض رتبتي إلى عضو" + "خفض رتبتي إلى مشرف" + "الإشراف على الأعضاء" + "الرسائل والمحتوى" + "المشرفون" + "المالكون" + "الصلاحيات" + "إعادة تعيين الصلاحيات" + "بمجرد إعادة تعيين الصلاحيات، ستفقد الإعدادات الحالية." + "إعادة تعيين الصلاحيات؟" + "الأدوار" + "تفاصيل الغرفة" + "تفاصيل المساحة" + "الأدوار والصلاحيات" + diff --git a/features/rolesandpermissions/impl/src/main/res/values-es/translations.xml b/features/rolesandpermissions/impl/src/main/res/values-es/translations.xml index a41489ea1b..defb25b9be 100644 --- a/features/rolesandpermissions/impl/src/main/res/values-es/translations.xml +++ b/features/rolesandpermissions/impl/src/main/res/values-es/translations.xml @@ -2,9 +2,13 @@ "Administrador" "Vetar personas" + "Cambiar ajustes" "Eliminar mensajes" "Miembro" "Invitar a otras personas" + "Compartir ubicación en tiempo real" + "Gestionar el espacio" + "Gestionar salas" "Administrar miembros" "Mensajes y contenido" "Moderador" @@ -14,25 +18,36 @@ "Cambiar el nombre de la sala" "Cambiar el tema de la sala" "Enviar mensajes" + "Permisos" "Editar administradores" "No podrás deshacer esta acción. Estás promocionando al usuario para que tenga el mismo nivel de poder que tú." - "¿Agregar Admin?" + "¿Agregar administrador?" + "Esta acción es irreversible. Estás transfiriendo la propiedad a los usuarios seleccionados. Una vez que salgas, será permanente." + "¿Transferir la propiedad?" "Degradar" "No podrás deshacer este cambio ya que te estás degradando. Si eres el último usuario privilegiado en la sala será imposible recuperar los privilegios." "¿Degradarte?" "%1$s (Pendiente)" "(Pendiente)" "Los administradores tienen privilegios de moderador de forma automática" + "Los propietarios tienen automáticamente privilegios de administrador." "Editar moderadores" + "Elegir propietarios" "Administradores" "Moderadores" "Miembros" "Tienes cambios sin guardar." "¿Guardar cambios?" - "No hay usuarios baneados." + "No hay usuarios vetados." + + "%1$d vetado" + "%1$d vetados" + + "Revisa la ortografía o intenta una nueva búsqueda." + "Ningún resultado para «%1$s»" - "%1$d Persona" - "%1$d Personas" + "%1$d persona" + "%1$d personas" "Sacar y vetar a un miembro" "Solo eliminar miembro" @@ -41,21 +56,31 @@ "Eliminar veto en la sala" "Vetados" "Miembros" + + "%1$d invitado" + "%1$d invitados" + + "Pendiente" "Administrador" "Moderador" + "Propietario" "Miembros de la sala" "Levantando veto a %1$s" "Administradores" + "Administradores y propietarios" "Cambiar mi rol" "Degradar a miembro" "Degradar a moderador" "Moderación de miembros" "Mensajes y contenido" "Moderadores" + "Propietarios" + "Permisos" "Restablecer permisos" "Una vez que restablezca los permisos, perderá la configuración actual." "¿Restablecer los permisos?" "Roles" "Detalles de la sala" + "Detalles del espacio" "Roles y permisos" diff --git a/features/rolesandpermissions/impl/src/main/res/values-fa/translations.xml b/features/rolesandpermissions/impl/src/main/res/values-fa/translations.xml index e381cec856..345a451678 100644 --- a/features/rolesandpermissions/impl/src/main/res/values-fa/translations.xml +++ b/features/rolesandpermissions/impl/src/main/res/values-fa/translations.xml @@ -2,9 +2,13 @@ "ادمین" "تحریم افراد" + "تغییر تنظیمات" "حذف پیام‌ها" "عضو" "دعوت کاربران" + "اشتراک گذاری موقعیت مکانی زنده" + "مدیریت فضا" + "مدیریت اتاق‌ها" "مدیریت اعضا" "پیام‌ها و محتوا" "ناظم" @@ -14,9 +18,11 @@ "تغییر نام اتاق" "دگرگونی موضوع اتاق" "فرستادن پیام‌ها" + "دسترسی‌ها" "ویرایش مدیران" "قادر نخواهید بود این کنش را بازکردانید. داردید کاربر را به سطح قدرت خودتان ارتقا می‌دهید." "افزودن مدیر؟" + "شما قادر به لغو این اقدام نخواهید بود. شما در حال انتقال مالکیت به کاربران انتخاب شده هستید. پس از خروج، این انتقال دائمی خواهد بود." "انتقال مالکیت؟" "تنزل بده" "شما نمی‌توانید این تغییر را بازگردانید زیرا در حال تنزل نقش خود در اتاق هستید، اگر آخرین کاربر ممتاز در اتاق باشید، امکان دستیابی مجدد به دسترسی‌های سطح بالای اتاق غیرممکن است." @@ -33,6 +39,12 @@ "تغییراتی ذخیره نشده دارید." "ذخیرهٔ تغییرات؟" "هیچ کاربری محروم نشده." + + "%1$d محروم شد" + "%1$d محروم شد" + + "املای کلمات را بررسی کنید یا جستجوی جدیدی را امتحان کنید" + "هیچ نتیجه‌ای برای «%1$s» یافت نشد." "%1$d نفر" "%1$d نفر" @@ -44,6 +56,11 @@ "تحریم نکردن از اتاق" "محروم" "اعضا" + + "%1$d دعوت شده" + "%1$d دعوت شده" + + "در حال بررسی" "ادمین" "ناظم" "مالک" @@ -58,10 +75,12 @@ "پیام‌ها و محتوا" "ناظم‌ها" "مالکان" + "دسترسی‌ها" "بازنشانی اجازه‌ها" "پس از بازنشانی اجازه‌ها تنظیمات فعلی را از دست خواهید داد." "بازنشانی اجازه‌ها؟" "نقش‌ها" "جزییات اتاق" + "جزئیات فضا" "نقش‌ها و مجوزها" diff --git a/features/rolesandpermissions/impl/src/main/res/values-zh-rTW/translations.xml b/features/rolesandpermissions/impl/src/main/res/values-zh-rTW/translations.xml index e9933c4819..409c112ad1 100644 --- a/features/rolesandpermissions/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/rolesandpermissions/impl/src/main/res/values-zh-rTW/translations.xml @@ -6,6 +6,7 @@ "移除訊息" "成員" "邀請夥伴" + "分享即時位置" "管理空間" "管理聊天室" "管理成員" diff --git a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverPresenter.kt b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverPresenter.kt index 78be168e53..1ec0ce0691 100644 --- a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverPresenter.kt +++ b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverPresenter.kt @@ -24,7 +24,10 @@ import io.element.android.libraries.matrix.api.core.RoomAlias import io.element.android.libraries.matrix.api.room.alias.ResolvedRoomAlias import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import java.util.concurrent.TimeoutException import kotlin.jvm.optionals.getOrElse +import kotlin.time.Duration.Companion.seconds @AssistedInject class RoomAliasResolverPresenter( @@ -61,9 +64,14 @@ class RoomAliasResolverPresenter( private fun CoroutineScope.resolveAlias(resolveState: MutableState>) = launch { suspend { - matrixClient.resolveRoomAlias(roomAlias) + val result = withTimeoutOrNull(ALIAS_RESOLVE_TIMEOUT_IN_SECONDS.seconds) { + matrixClient.resolveRoomAlias(roomAlias) + } ?: throw TimeoutException("Timed out while resolving ${roomAlias.value}") + result .getOrThrow() .getOrElse { throw RoomAliasResolverFailures.UnknownAlias } }.runCatchingUpdatingState(resolveState) } } + +private const val ALIAS_RESOLVE_TIMEOUT_IN_SECONDS = 10 diff --git a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverStateProvider.kt b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverStatePreviewParam.kt similarity index 93% rename from features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverStateProvider.kt rename to features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverStatePreviewParam.kt index c3152bc303..6f93930b99 100644 --- a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverStateProvider.kt +++ b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.matrix.api.core.RoomAlias import io.element.android.libraries.matrix.api.exception.ClientException import io.element.android.libraries.matrix.api.room.alias.ResolvedRoomAlias -open class RoomAliasResolverStateProvider : PreviewParameterProvider { +open class RoomAliasResolverStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomAliasResolverState(), diff --git a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverView.kt b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverView.kt index ad0d2e9ab9..37960a50e2 100644 --- a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverView.kt +++ b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasResolverView.kt @@ -147,7 +147,7 @@ private fun RoomAliasResolverTopBar( @PreviewsDayNight @Composable -internal fun RoomAliasResolverViewPreview(@PreviewParameter(RoomAliasResolverStateProvider::class) state: RoomAliasResolverState) = ElementPreview { +internal fun RoomAliasResolverViewPreview(@PreviewParameter(RoomAliasResolverStatePreviewParam::class) state: RoomAliasResolverState) = ElementPreview { RoomAliasResolverView( state = state, onSuccess = { }, diff --git a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/di/RoomAliasResolverModule.kt b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/di/RoomAliasResolverBindingContainer.kt similarity index 92% rename from features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/di/RoomAliasResolverModule.kt rename to features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/di/RoomAliasResolverBindingContainer.kt index 8f5c9d733b..a3796fad91 100644 --- a/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/di/RoomAliasResolverModule.kt +++ b/features/roomaliasresolver/impl/src/main/kotlin/io/element/android/features/roomaliasresolver/impl/di/RoomAliasResolverBindingContainer.kt @@ -18,9 +18,9 @@ import io.element.android.libraries.matrix.api.core.RoomAlias @BindingContainer @ContributesTo(SessionScope::class) -object RoomAliasResolverModule { +object RoomAliasResolverBindingContainer { @Provides - fun providesJoinRoomPresenterFactory( + fun providesRoomAliasResolverPresenterFactory( client: MatrixClient, ): RoomAliasResolverPresenter.Factory { return object : RoomAliasResolverPresenter.Factory { diff --git a/features/roomaliasresolver/impl/src/main/res/values-ar/translations.xml b/features/roomaliasresolver/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..6500dcebf6 --- /dev/null +++ b/features/roomaliasresolver/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,5 @@ + + + "تعذّر عرض معاينة هذه الغرفة" + "تعذّر حل الاسم المستعار للغرفة." + diff --git a/features/roomaliasresolver/impl/src/main/res/values-fa/translations.xml b/features/roomaliasresolver/impl/src/main/res/values-fa/translations.xml index 4fba81c4f8..f9fdf67b21 100644 --- a/features/roomaliasresolver/impl/src/main/res/values-fa/translations.xml +++ b/features/roomaliasresolver/impl/src/main/res/values-fa/translations.xml @@ -1,4 +1,5 @@ + "ما نتوانستیم پیش‌نمایش این اتاق را نمایش دهیم" "شکست در دریافت نام مستعار اتاق." diff --git a/features/roomaliasresolver/impl/src/test/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasHelperPresenterTest.kt b/features/roomaliasresolver/impl/src/test/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasHelperPresenterTest.kt index df8b8058be..a50049446b 100644 --- a/features/roomaliasresolver/impl/src/test/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasHelperPresenterTest.kt +++ b/features/roomaliasresolver/impl/src/test/kotlin/io/element/android/features/roomaliasresolver/impl/RoomAliasHelperPresenterTest.kt @@ -22,10 +22,12 @@ import io.element.android.libraries.matrix.test.A_ROOM_ID import io.element.android.libraries.matrix.test.A_SERVER_LIST import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.tests.testutils.WarmUpRule +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.Test import java.util.Optional +import java.util.concurrent.TimeoutException class RoomAliasHelperPresenterTest { @get:Rule @@ -60,6 +62,22 @@ class RoomAliasHelperPresenterTest { } } + @Test + fun `present - a server that never answers ends up in an error state`() = runTest { + val client = FakeMatrixClient( + resolveRoomAliasResult = { awaitCancellation() } + ) + val presenter = createPresenter(matrixClient = client) + moleculeFlow(RecompositionMode.Immediate) { + presenter.present() + }.test { + assertThat(awaitItem().resolveState.isUninitialized()).isTrue() + assertThat(awaitItem().resolveState.isLoading()).isTrue() + val resultState = awaitItem() + assertThat(resultState.resolveState.errorOrNull()).isInstanceOf(TimeoutException::class.java) + } + } + @Test fun `present - resolve alias error and retry`() = runTest { val client = FakeMatrixClient( diff --git a/features/roomcall/api/src/main/kotlin/io/element/android/features/roomcall/api/RoomCallStateProvider.kt b/features/roomcall/api/src/main/kotlin/io/element/android/features/roomcall/api/RoomCallStatePreviewParam.kt similarity index 94% rename from features/roomcall/api/src/main/kotlin/io/element/android/features/roomcall/api/RoomCallStateProvider.kt rename to features/roomcall/api/src/main/kotlin/io/element/android/features/roomcall/api/RoomCallStatePreviewParam.kt index 3356fa0366..84b0bda6be 100644 --- a/features/roomcall/api/src/main/kotlin/io/element/android/features/roomcall/api/RoomCallStateProvider.kt +++ b/features/roomcall/api/src/main/kotlin/io/element/android/features/roomcall/api/RoomCallStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.roomcall.api import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class RoomCallStateProvider : PreviewParameterProvider { +open class RoomCallStatePreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( aStandByCallState(), aStandByCallState(canStartCall = false), diff --git a/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenter.kt b/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenter.kt index 15e320c8f8..7763933a29 100644 --- a/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenter.kt +++ b/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenter.kt @@ -60,10 +60,13 @@ class RoomCallStatePresenter( isUserLocallyInTheCall = isUserLocallyInTheCall, isAudioCall = roomInfo.activeCallIntentConsensus.isAudio(), ) - else -> RoomCallState.StandBy( - canStartCall = canJoinCall, - isDM = roomInfo.isDm - ) + else -> { + val isEmptyDm = roomInfo.isDm && roomInfo.activeMembersCount <= 1 + RoomCallState.StandBy( + canStartCall = canJoinCall && !isEmptyDm, + isDM = roomInfo.isDm + ) + } } } } diff --git a/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/di/RoomCallModule.kt b/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/di/RoomCallBindingContainer.kt similarity index 95% rename from features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/di/RoomCallModule.kt rename to features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/di/RoomCallBindingContainer.kt index fc649dd1f2..aa2d0fdde4 100644 --- a/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/di/RoomCallModule.kt +++ b/features/roomcall/impl/src/main/kotlin/io/element/android/features/roomcall/impl/di/RoomCallBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.di.RoomScope @ContributesTo(RoomScope::class) @BindingContainer -interface RoomCallModule { +interface RoomCallBindingContainer { @Binds fun bindRoomCallStatePresenter(presenter: RoomCallStatePresenter): Presenter } diff --git a/features/roomcall/impl/src/test/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenterTest.kt b/features/roomcall/impl/src/test/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenterTest.kt index 0612adbea1..9a4c3b0af0 100644 --- a/features/roomcall/impl/src/test/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenterTest.kt +++ b/features/roomcall/impl/src/test/kotlin/io/element/android/features/roomcall/impl/RoomCallStatePresenterTest.kt @@ -49,6 +49,42 @@ class RoomCallStatePresenterTest { } } + @Test + fun `present - a DM with no other member cannot start a call`() = runTest { + val room = FakeJoinedRoom( + baseRoom = FakeBaseRoom( + initialRoomInfo = aRoomInfo(isDm = true, activeMembersCount = 1, joinedMembersCount = 1), + roomPermissions = roomPermissions(true), + ) + ) + val presenter = createRoomCallStatePresenter(joinedRoom = room) + presenter.test { + skipItems(1) + assertThat(awaitItem()).isEqualTo( + RoomCallState.StandBy( + canStartCall = false, + isDM = true + ) + ) + } + } + + @Test + fun `present - a DM becomes callable once the other member is active`() = runTest { + val baseRoom = FakeBaseRoom( + initialRoomInfo = aRoomInfo(isDm = true, activeMembersCount = 1, joinedMembersCount = 1), + roomPermissions = roomPermissions(true), + ) + val room = FakeJoinedRoom(baseRoom = baseRoom) + val presenter = createRoomCallStatePresenter(joinedRoom = room) + presenter.test { + skipItems(1) + assertThat(awaitItem()).isEqualTo(RoomCallState.StandBy(canStartCall = false, isDM = true)) + baseRoom.givenRoomInfo(aRoomInfo(isDm = true, activeMembersCount = 2, joinedMembersCount = 2)) + assertThat(awaitItem()).isEqualTo(RoomCallState.StandBy(canStartCall = true, isDM = true)) + } + } + @Test fun `present - element call not available`() = runTest { val room = FakeJoinedRoom( diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsStateProvider.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsStatePreviewParam.kt similarity index 99% rename from features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsStateProvider.kt rename to features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsStatePreviewParam.kt index 6aa4f11a8e..d1652b30dd 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsStateProvider.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsStatePreviewParam.kt @@ -31,7 +31,7 @@ import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.ui.components.aMatrixUserList import kotlinx.collections.immutable.toImmutableList -open class RoomDetailsStateProvider : PreviewParameterProvider { +open class RoomDetailsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomDetailsState(displayAdminSettings = true), diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsView.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsView.kt index 96dc3e25ba..b2874d01f9 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsView.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsView.kt @@ -905,12 +905,12 @@ private fun DebugInfoSection( @PreviewWithExtraLargeHeight @Composable -internal fun RoomDetailsPreview(@PreviewParameter(RoomDetailsStateProvider::class) state: RoomDetailsState) = +internal fun RoomDetailsPreview(@PreviewParameter(RoomDetailsStatePreviewParam::class) state: RoomDetailsState) = ElementPreviewLight { ContentToPreview(state) } @PreviewWithExtraLargeHeight @Composable -internal fun RoomDetailsDarkPreview(@PreviewParameter(RoomDetailsStateProvider::class) state: RoomDetailsState) = +internal fun RoomDetailsDarkPreview(@PreviewParameter(RoomDetailsStatePreviewParam::class) state: RoomDetailsState) = ElementPreviewDark { ContentToPreview(state) } @PreviewWithExtraLargeHeight diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/di/RoomMemberModule.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/di/RoomMemberBindingContainer.kt similarity index 95% rename from features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/di/RoomMemberModule.kt rename to features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/di/RoomMemberBindingContainer.kt index 479f23f90d..6651e85097 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/di/RoomMemberModule.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/di/RoomMemberBindingContainer.kt @@ -21,9 +21,9 @@ import io.element.android.libraries.matrix.api.room.JoinedRoom @BindingContainer @ContributesTo(RoomScope::class) -object RoomMemberModule { +object RoomMemberBindingContainer { @Provides - fun provideRoomMemberDetailsPresenterFactory( + fun providesRoomMemberDetailsPresenterFactory( room: JoinedRoom, userProfilePresenterFactory: UserProfilePresenterFactory, encryptionService: EncryptionService, diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/invite/RoomInviteMembersView.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/invite/RoomInviteMembersView.kt index cb305426bc..d00a4e159a 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/invite/RoomInviteMembersView.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/invite/RoomInviteMembersView.kt @@ -24,7 +24,7 @@ import androidx.compose.ui.unit.dp import io.element.android.compound.theme.ElementTheme import io.element.android.features.invitepeople.api.InvitePeopleEvents import io.element.android.features.invitepeople.api.InvitePeopleState -import io.element.android.features.invitepeople.api.InvitePeopleStateProvider +import io.element.android.features.invitepeople.api.InvitePeopleStatePreviewParam import io.element.android.features.roomdetails.impl.R import io.element.android.libraries.designsystem.components.ProgressDialog import io.element.android.libraries.designsystem.components.button.BackButton @@ -116,7 +116,7 @@ private fun InviteProgressDialog() { @PreviewsDayNight @Composable -internal fun RoomInviteMembersViewPreview(@PreviewParameter(InvitePeopleStateProvider::class) state: InvitePeopleState) = ElementPreview { +internal fun RoomInviteMembersViewPreview(@PreviewParameter(InvitePeopleStatePreviewParam::class) state: InvitePeopleState) = ElementPreview { RoomInviteMembersView( state = state, invitePeopleView = {}, diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenter.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenter.kt index f47f12f446..674dd9aad9 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenter.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenter.kt @@ -37,6 +37,7 @@ import io.element.android.libraries.matrix.api.room.roomMembers import io.element.android.libraries.matrix.api.room.toMatrixUser import io.element.android.libraries.matrix.ui.room.PowerLevelRoomMemberComparator import io.element.android.libraries.matrix.ui.room.roomMemberIdentityStateChange +import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.persistentMapOf import kotlinx.collections.immutable.toImmutableList @@ -58,6 +59,7 @@ class RoomMemberListPresenter( override fun present(): RoomMemberListState { val searchQuery = rememberTextFieldState() val membersState by room.membersStateFlow.collectAsState() + val roomInfo by room.roomInfoFlow.collectAsState() val canInvite by room.permissionsAsState(false) { perms -> perms.canOwnUserInvite() } val roomModerationState = roomMembersModerationPresenter.present() @@ -72,13 +74,18 @@ class RoomMemberListPresenter( var selectedSection by remember { mutableStateOf(SelectedSection.MEMBERS) } var roomMembers: AsyncData by remember { mutableStateOf(AsyncData.Loading()) } var filteredRoomMembers: AsyncData by remember { mutableStateOf(AsyncData.Loading()) } + val activeCallParticipants = roomInfo.activeRoomCallParticipants + + val comparator = remember(activeCallParticipants) { + roomMemberListComparator(activeCallParticipants) + } // Update the room members when the screen is loaded LaunchedEffect(Unit) { room.updateMembers() } - LaunchedEffect(membersState, roomMemberIdentityStates) { + LaunchedEffect(membersState, roomMemberIdentityStates, activeCallParticipants) { if (membersState is RoomMembersState.Unknown) { return@LaunchedEffect } @@ -90,23 +97,23 @@ class RoomMemberListPresenter( } withContext(coroutineDispatchers.io) { val members = membersState.roomMembers().orEmpty().groupBy { it.membership } - val info = room.info() - if (members.getOrDefault(RoomMembershipState.JOIN, emptyList()).size < info.joinedMembersCount / 2) { + if (members.getOrDefault(RoomMembershipState.JOIN, emptyList()).size < roomInfo.joinedMembersCount / 2) { // Don't display initial room member list if we have less than half of the joined members: - // This result will come from the timeline loading membership events and it'll be wrong. + // This result will come from the timeline loading membership events, and it'll be wrong. return@withContext } val result = RoomMembers( invited = members.getOrDefault(RoomMembershipState.INVITE, emptyList()) - .map { it.withIdentityState(roomMemberIdentityStates) } + .map { it.withIdentityState(roomMemberIdentityStates, activeCallParticipants) } .toImmutableList(), joined = members.getOrDefault(RoomMembershipState.JOIN, emptyList()) - .sortedWith(powerLevelRoomMemberComparator) - .map { it.withIdentityState(roomMemberIdentityStates) } + .sortedWith(comparator) + // .sortedWith(powerLevelRoomMemberComparator) + .map { it.withIdentityState(roomMemberIdentityStates, activeCallParticipants) } .toImmutableList(), banned = members.getOrDefault(RoomMembershipState.BAN, emptyList()) .sortedBy { it.userId.value } - .map { it.withIdentityState(roomMemberIdentityStates) } + .map { it.withIdentityState(roomMemberIdentityStates, activeCallParticipants) } .toImmutableList(), ) roomMembers = if (membersState is RoomMembersState.Pending) { @@ -150,12 +157,29 @@ class RoomMemberListPresenter( return state } - private suspend fun RoomMember.withIdentityState(identityStates: ImmutableMap): RoomMemberWithIdentityState { + private suspend fun RoomMember.withIdentityState( + identityStates: ImmutableMap, + activeCallParticipants: ImmutableList + ): RoomMemberWithIdentityState { return if (room.info().isEncrypted != true) { - RoomMemberWithIdentityState(this, null) + RoomMemberWithIdentityState(this, null, userId in activeCallParticipants) } else { val identityState = identityStates[userId] ?: encryptionService.getUserIdentity(userId, fallbackToServer = false).getOrNull() - RoomMemberWithIdentityState(this, identityState) + RoomMemberWithIdentityState(this, identityState, userId in activeCallParticipants) } } + + private fun roomMemberListComparator( + activeCallParticipants: List, + ): Comparator = + Comparator { a, b -> + val aInCall = a.userId in activeCallParticipants + val bInCall = b.userId in activeCallParticipants + + when { + aInCall && !bInCall -> -1 + !aInCall && bInCall -> 1 + else -> powerLevelRoomMemberComparator.compare(a, b) + } + } } diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListState.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListState.kt index 6d52db6c87..7b6744ef0b 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListState.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListState.kt @@ -66,4 +66,5 @@ data class RoomMembers( data class RoomMemberWithIdentityState( val roomMember: RoomMember, val identityState: IdentityState?, + val isInCall: Boolean ) diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListStateProvider.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListStatePreviewParam.kt similarity index 96% rename from features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListStateProvider.kt rename to features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListStatePreviewParam.kt index 472a185076..59a26e6207 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListStateProvider.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListStatePreviewParam.kt @@ -31,7 +31,7 @@ import io.element.android.libraries.matrix.api.room.RoomMembershipState import io.element.android.libraries.matrix.api.user.DisplayedStatus import kotlinx.collections.immutable.persistentListOf -internal class RoomMemberListStateProvider : PreviewParameterProvider { +internal class RoomMemberListStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomMemberListState( @@ -78,7 +78,7 @@ private fun aLoadedRoomMembers() = AsyncData.Success( joined = persistentListOf( anAlice().withIdentity(identityState = IdentityState.Verified), aBob().withIdentity(identityState = IdentityState.PinViolation), - aCarol().withIdentity(), + aCarol().withIdentity(isInCall = true), aDavid().withIdentity(), anEve().withIdentity(identityState = IdentityState.VerificationViolation) ), @@ -174,4 +174,8 @@ fun aBannedSusie(): RoomMember = aRoomMember(UserId("@susie:server.org"), USER_N fun aBannedMallory(): RoomMember = aRoomMember(UserId("@mallory:server.org"), USER_NAME_MALLORY, membership = RoomMembershipState.BAN) -private fun RoomMember.withIdentity(identityState: IdentityState? = null) = RoomMemberWithIdentityState(this, identityState) +private fun RoomMember.withIdentity(identityState: IdentityState? = null, isInCall: Boolean = false) = RoomMemberWithIdentityState( + this, + identityState, + isInCall +) diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListView.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListView.kt index 659d8ed0e0..f19ee95106 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListView.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListView.kt @@ -338,6 +338,15 @@ private fun RoomMemberListItem( color = ElementTheme.colors.textSecondary, ) } + + if (roomMemberWithIdentity.isInCall) { + Icon( + modifier = Modifier.size(20.dp), + imageVector = CompoundIcons.VideoCallSolid(), + contentDescription = stringResource(CommonStrings.action_video_call), + tint = ElementTheme.colors.iconSuccessPrimary + ) + } } } ) @@ -366,7 +375,7 @@ private fun RoomMemberListTopBar( @PreviewsDayNight @Composable -internal fun RoomMemberListViewPreview(@PreviewParameter(RoomMemberListStateProvider::class) state: RoomMemberListState) = ElementPreview { +internal fun RoomMemberListViewPreview(@PreviewParameter(RoomMemberListStatePreviewParam::class) state: RoomMemberListState) = ElementPreview { RoomMemberListView( state = state, navigator = object : RoomMemberListNavigator { diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsItem.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsItem.kt index 2d5418afdc..eb695f1f34 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsItem.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsItem.kt @@ -12,7 +12,6 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import io.element.android.features.roomdetails.impl.R import io.element.android.libraries.matrix.api.room.RoomNotificationMode -import io.element.android.libraries.ui.strings.CommonStrings import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList @@ -36,7 +35,7 @@ fun roomNotificationSettingsItems(): ImmutableList ) RoomNotificationMode.MUTE -> RoomNotificationSettingsItem( mode = it, - title = stringResource(CommonStrings.common_mute), + title = stringResource(R.string.screen_room_notification_settings_mode_mute), ) } } diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsStateProvider.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsStatePreviewParam.kt similarity index 95% rename from features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsStateProvider.kt rename to features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsStatePreviewParam.kt index 603d22b502..f7ac7597d6 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsStateProvider.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.room.RoomNotificationMode -internal class RoomNotificationSettingsStateProvider : PreviewParameterProvider { +internal class RoomNotificationSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomNotificationSettingsState(), diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsView.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsView.kt index 12bc258944..f0676f133e 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsView.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/RoomNotificationSettingsView.kt @@ -34,7 +34,6 @@ import io.element.android.libraries.designsystem.text.buildAnnotatedStringWithSt import io.element.android.libraries.designsystem.theme.components.Scaffold import io.element.android.libraries.designsystem.theme.components.TopAppBar import io.element.android.libraries.matrix.api.room.RoomNotificationMode -import io.element.android.libraries.ui.strings.CommonStrings @Composable fun RoomNotificationSettingsView( @@ -118,7 +117,7 @@ private fun RoomSpecificNotificationSettingsView( RoomNotificationMode.MENTIONS_AND_KEYWORDS_ONLY -> { stringResource(id = R.string.screen_room_notification_settings_mode_mentions_and_keywords) } - RoomNotificationMode.MUTE -> stringResource(id = CommonStrings.common_mute) + RoomNotificationMode.MUTE -> stringResource(id = R.string.screen_room_notification_settings_mode_mute) } val displayMentionsOnlyDisclaimer = state.displayMentionsOnlyDisclaimer && state.defaultRoomNotificationMode == RoomNotificationMode.MENTIONS_AND_KEYWORDS_ONLY @@ -175,7 +174,7 @@ private fun RoomNotificationSettingsTopBar( @PreviewsDayNight @Composable internal fun RoomNotificationSettingsViewPreview( - @PreviewParameter(RoomNotificationSettingsStateProvider::class) state: RoomNotificationSettingsState + @PreviewParameter(RoomNotificationSettingsStatePreviewParam::class) state: RoomNotificationSettingsState ) = ElementPreview { RoomNotificationSettingsView( state = state, diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsStateProvider.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsStatePreviewParam.kt similarity index 92% rename from features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsStateProvider.kt rename to features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsStatePreviewParam.kt index 039f489bbf..6a3ecacfcb 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsStateProvider.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.room.RoomNotificationMode -internal class UserDefinedRoomNotificationSettingsStateProvider : PreviewParameterProvider { +internal class UserDefinedRoomNotificationSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( RoomNotificationSettingsState( diff --git a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsView.kt b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsView.kt index 1721c9925c..befbc9382f 100644 --- a/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsView.kt +++ b/features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/notificationsettings/UserDefinedRoomNotificationSettingsView.kt @@ -105,7 +105,7 @@ private fun UserDefinedRoomNotificationSettingsTopBar( @PreviewsDayNight @Composable internal fun UserDefinedRoomNotificationSettingsViewPreview( - @PreviewParameter(UserDefinedRoomNotificationSettingsStateProvider::class) state: RoomNotificationSettingsState + @PreviewParameter(UserDefinedRoomNotificationSettingsStatePreviewParam::class) state: RoomNotificationSettingsState ) = ElementPreview { UserDefinedRoomNotificationSettingsView( state = state, diff --git a/features/roomdetails/impl/src/main/res/values-ar/translations.xml b/features/roomdetails/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..3d640a615a --- /dev/null +++ b/features/roomdetails/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,188 @@ + + + "لا يرى الأعضاء الجدد السجل" + "يرى الأعضاء الجدد السجل" + "يمكن لأي شخص رؤية السجل" + "تحتاج إلى عنوان حتى تظهر الغرفة في الدليل العام." + "تعديل العنوان" + "حدث خطأ أثناء تحديث إعدادات الإشعارات." + "لا يدعم خادمك المنزلي هذا الخيار في الغرف المشفّرة، وقد لا تتلقى إشعارات في بعض الغرف." + "الاستطلاعات" + "مسؤول" + "حظر الأشخاص" + "إزالة الرسائل" + "عضو" + "دعوة الأشخاص" + "إدارة الأعضاء" + "الرسائل والمحتوى" + "مشرف" + "إزالة الأشخاص" + "تغيير الصورة الرمزية" + "تعديل التفاصيل" + "تغيير الاسم" + "تغيير الموضوع" + "إرسال الرسائل" + "تعديل المسؤولين" + "لن تتمكن من التراجع عن هذا الإجراء. ستتم ترقية المستخدم ليحصل على مستوى الصلاحيات نفسه الذي لديك." + "إضافة مسؤول؟" + "لن تتمكن من التراجع عن هذا الإجراء. ستنقل الملكية إلى المستخدمين المحددين. بمجرد مغادرتك، سيصبح ذلك دائمًا." + "نقل الملكية؟" + "خفض الرتبة" + "لن تتمكن من التراجع عن هذا التغيير لأنك تخفض رتبتك. إذا كنت آخر مستخدم لديه صلاحيات في الغرفة، فسيكون من المستحيل استعادة الصلاحيات." + "خفض رتبتك؟" + "%1$s (قيد الانتظار)" + "(قيد الانتظار)" + "يتمتع المسؤولون تلقائيًا بصلاحيات المشرفين" + "يتمتع المالكون بامتيازات المسؤولين تلقائيًا." + "تعديل المشرفين" + "اختيار المالكين" + "المسؤولون" + "المشرفون" + "الأعضاء" + "لديك تغييرات غير محفوظة." + "حفظ التغييرات؟" + "إضافة موضوع" + "مشفّرة" + "غير مشفّرة" + "غرفة عامة" + "تعديل التفاصيل" + "قد كان هناك خطأ والمعلومات لم تتحدث." + "غير قادر على تعديل الغرفة" + "الرسائل مؤمَّنة بأقفال. أنت والمستقبلون فقط من تملكون المفاتيح الخاصة لفتح أقفالها." + "تشفير الرسائل مفعّل" + "حصل خطأ أثناء تحميل إعدادات الإشعارات." + "تعذّر كتم هذه الغرفة، يرجى المحاولة مجدداً." + "تعذّر إلغاء كتم هذه الغرفة، يرجى المحاولة مجدداً." + "لا تغلق التطبيق حتى الانتهاء." + "جارٍ تحضير الدعوات…" + "دعوة أشخاص" + "دعوة " + "مغادرة المحادثة" + "مغادرة الغرفة" + "الوسائط والملفات" + "مخصص" + "افتراضي" + "الإشعارات" + "الرسائل المثبّتة" + "الملف الشخصي" + "طلبات الانضمام" + "الأدوار والصلاحيات" + "الاسم" + "الأمان والخصوصية" + "الأمان" + "مشاركة الغرفة" + "معلومات الغرفة" + "الموضوع" + "يتم تحديث الغرفة…" + "لا يوجد مستخدمون محظورون." + + "%1$d محظورين" + "%1$d محظور" + "%1$d محظوران" + "%1$d محظورين" + "%1$d محظورًا" + "%1$d محظور" + + "تحقّق من الإملاء أو جرّب بحثًا جديدًا" + "لا توجد نتائج لـ “%1$s”" + + "%1$d شخص" + "%1$d شخص" + "%1$d شخصين" + "%1$d اشخاص" + "%1$d شخص" + "%1$d شخص" + + "حظر المستخدم" + "إزالة العضو فقط" + "إلغاء الحظر" + "يمكن لهذا المستخدم الانضمام إلى هذه الغرفة مرة أخرى عند دعوته." + "إلغاء حظر المستخدم" + "المحظورون" + "الأعضاء" + + "%1$d مدعوّين" + "%1$d مدعو" + "%1$d مدعوّان" + "%1$d مدعوّين" + "%1$d مدعوًا" + "%1$d مدعو" + + "قيد الانتظار" + "مسؤول" + "مشرف" + "مالك" + "أعضاء الغرفة" + "جارٍ رفع حظر %1$s" + "السماح بإعدادات مخصصة" + "سيؤدي تشغيل هذا إلى استبدال إعداداتك الافتراضية" + "أرسل لي إشعارات هذه المحادثة لـ" + "يمكنك تغيير ذلك في الـ %1$s الخاص بك." + "الإعدادات العامة" + "الإعدادات الافتراضية" + "إزالة الإعدادات الخاصة" + "حصل خطأ أثناء تحميل إعدادات الإشعارات." + "تعّذرت استعادة الوضع الافتراضي، يرجى المحاولة مجدداً." + "تعذّر تطبيق الوضع، يرجى المحاولة مجدداً." + "لا يدعم خادمك المنزلي هذا الخيار في الغرف المشفّرة، ولن تتلقى إشعارات في هذه الغرفة." + "كل الرسائل" + "في هذه الغرفة، أرسل لي إشعارات لـ" + "المسؤولون" + "المسؤولون والمالكون" + "تغيير دوري" + "خفض رتبتي إلى عضو" + "خفض رتبتي إلى مشرف" + "الإشراف على الأعضاء" + "الرسائل والمحتوى" + "المشرفون" + "المالكون" + "الصلاحيات" + "إعادة تعيين الصلاحيات" + "بمجرد إعادة تعيين الصلاحيات، ستفقد الإعدادات الحالية." + "إعادة تعيين الصلاحيات؟" + "الأدوار" + "تفاصيل الغرفة" + "الأدوار والصلاحيات" + "وضع علامة كمقروء" + "وضع علامة كغير مقروء" + "إضافة عنوان" + "يمكن لأي شخص في المساحات المصرّح بها الانضمام، لكن يجب على الآخرين طلب الوصول." + "يجب على الجميع طلب الوصول." + "طلب الانضمام" + "يمكن لأي شخص في %1$s الانضمام، لكن يجب على الآخرين طلب الوصول." + "نعم، فعّل التشفير" + "بعد تفعيله، لا يمكن تعطيل التشفير في الغرفة. لن يكون سجل الرسائل مرئيًا لأعضاء الغرفة إلا منذ وقت دعوتهم أو منذ انضمامهم إلى الغرفة. +لن يتمكن أي شخص غير أعضاء الغرفة من قراءة الرسائل. قد يمنع ذلك البوتات والجسور من العمل بشكل صحيح. +لا نوصي بتفعيل التشفير للغرف التي يمكن لأي شخص العثور عليها والانضمام إليها." + "تفعيل التشفير؟" + "بعد تفعيله، لا يمكن تعطيل التشفير." + "التشفير" + "تفعيل التشفير من طرف إلى طرف" + "يمكن لأي شخص الانضمام." + "أي شخص" + "اختر المساحات التي يمكن لأعضائها الانضمام إلى هذه الغرفة دون دعوة. %1$s" + "إدارة المساحات" + "يمكن للأشخاص المدعوين فقط الانضمام." + "بالدعوة فقط" + "الوصول" + "يمكن لأي شخص في المساحات المصرّح بها الانضمام." + "يمكن لأي شخص في %1$s الانضمام." + "أعضاء المساحة" + "المساحات غير مدعومة حاليًا" + "تحتاج إلى عنوان حتى تظهر الغرفة في الدليل العام." + "العنوان" + "السماح بالعثور على هذه الغرفة عند البحث في دليل الغرف العام على %1$s" + "السماح بالعثور عليها عند البحث في الدليل العام." + "مرئية في الدليل العام" + "أي شخص (السجل عام)" + "لن تؤثر التغييرات على الرسائل السابقة، بل على الرسائل الجديدة فقط. %1$s" + "من يمكنه قراءة السجل" + "الأعضاء منذ دعوتهم" + "الأعضاء (السجل الكامل)" + "عناوين الغرف وسيلة للعثور على الغرف والوصول إليها. كما يضمن ذلك إمكانية مشاركة غرفتك بسهولة مع الآخرين. +يمكنك اختيار نشر غرفتك في دليل الغرف العام على خادمك المنزلي." + "نشر الغرفة" + "العناوين وسيلة للعثور على الغرف والمساحات والوصول إليها. كما يضمن ذلك إمكانية مشاركتها بسهولة مع الآخرين." + "الظهور" + "الأمان والخصوصية" + diff --git a/features/roomdetails/impl/src/main/res/values-be/translations.xml b/features/roomdetails/impl/src/main/res/values-be/translations.xml index 2b0b59e359..130912651c 100644 --- a/features/roomdetails/impl/src/main/res/values-be/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-be/translations.xml @@ -88,7 +88,6 @@ "Не ўдалося наладзіць рэжым, паспрабуйце яшчэ раз." "Ваш хатні сервер не падтрымлівае гэту опцыю ў зашыфраваных пакоях, вы не атрымаеце апавяшчэнне ў гэтым пакоі." "Усе паведамленні" - "Толькі згадванні і ключавыя словы" "У гэтым пакоі паведаміце мяне пра" "Адміністратары" "Змяніць маю роль" diff --git a/features/roomdetails/impl/src/main/res/values-bg/translations.xml b/features/roomdetails/impl/src/main/res/values-bg/translations.xml index 7369d78f1d..a7594bc411 100644 --- a/features/roomdetails/impl/src/main/res/values-bg/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-bg/translations.xml @@ -68,7 +68,6 @@ "Неуспешно възстановяване на режима по подразбиране, моля, опитайте отново." "Неуспешно задаване на режима, моля, опитайте отново." "Всички съобщения" - "Само споменавания и ключови думи" "В тази стая, да бъда известяван за" "Администратори" "Промяна на моята роля" diff --git a/features/roomdetails/impl/src/main/res/values-ca/translations.xml b/features/roomdetails/impl/src/main/res/values-ca/translations.xml index 8b9f8d937e..b1a022a17d 100644 --- a/features/roomdetails/impl/src/main/res/values-ca/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-ca/translations.xml @@ -91,8 +91,6 @@ "No s\'ha pogut restaurar el mode predeterminat. Torna-ho a provar." "No s\'ha pogut configurar el mode. Torna-ho a provar." "El servidor no admet aquesta opció en sales xifrades, no rebras notificacions en aquesta sala." - "Tots els missatges" - "Mencions y paraules clau (només)" "En aquesta sala, notifica\'m en" "Administradors" "Canvia el meu rol" diff --git a/features/roomdetails/impl/src/main/res/values-cy/translations.xml b/features/roomdetails/impl/src/main/res/values-cy/translations.xml index f5d4eecac5..68c53ec260 100644 --- a/features/roomdetails/impl/src/main/res/values-cy/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-cy/translations.xml @@ -103,7 +103,7 @@ "Wedi methu gosod y modd, ceisiwch eto." "Nid yw eich gweinydd cartref yn cefnogi\'r dewis hwn mewn ystafelloedd sydd wedi\'u hamgryptio, chewch chi ddim eich hysbysu yn yr ystafell hon." "Pob neges" - "Crybwylliadau ac Allweddeiriau\'n unig" + "Dim ond Crybwylliadau ac Allweddeiriau" "Yn yr ystafell hon, rhowch wybod i mi am" "Gweinyddwyr" "Gweinyddwyr a pherchnogion" diff --git a/features/roomdetails/impl/src/main/res/values-da/translations.xml b/features/roomdetails/impl/src/main/res/values-da/translations.xml index 191df9f059..e727221b74 100644 --- a/features/roomdetails/impl/src/main/res/values-da/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-da/translations.xml @@ -113,8 +113,6 @@ "Gendannelse af standardtilstanden mislykkedes. Prøv igen." "Kunne ikke indstille tilstanden. Prøv igen." "Din hjemmeserver understøtter ikke denne indstilling i krypterede rum, du får ikke besked i dette rum." - "Alle beskeder" - "Kun omtaler og nøgleord" "Giv mig besked i dette rum for" "Administratorer" "Administratorer og ejere" diff --git a/features/roomdetails/impl/src/main/res/values-el/translations.xml b/features/roomdetails/impl/src/main/res/values-el/translations.xml index 5f1a3ce4ab..6350d5de24 100644 --- a/features/roomdetails/impl/src/main/res/values-el/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-el/translations.xml @@ -114,7 +114,6 @@ "Αποτυχία ρύθμισης της λειτουργίας, δοκίμασε ξανά." "Ο αρχικός διακομιστής σας δεν υποστηρίζει αυτή την επιλογή σε κρυπτογραφημένες αίθουσες, δεν θα λάβετε ειδοποιήσεις σε αυτή την αίθουσα." "Όλα τα μηνύματα" - "Μόνο αναφορές και λέξεις-κλειδιά" "Σε αυτήν την αίθουσα, ειδοποιήστε με για" "Διαχειριστές" "Διαχειριστές και κάτοχοι" diff --git a/features/roomdetails/impl/src/main/res/values-es/translations.xml b/features/roomdetails/impl/src/main/res/values-es/translations.xml index 9537596d4e..8b9b5365c8 100644 --- a/features/roomdetails/impl/src/main/res/values-es/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-es/translations.xml @@ -1,5 +1,8 @@ + "Los miembros nuevos no ven el historial" + "Los miembros nuevos ven el historial" + "Cualquiera puede ver el historial" "Necesitarás una dirección de sala para que sea visible en el directorio." "Editar dirección" "Se ha producido un error al actualizar la configuración de notificaciones." @@ -21,14 +24,18 @@ "Enviar mensajes" "Editar administradores" "No podrás deshacer esta acción. Estás promocionando al usuario para que tenga el mismo nivel de poder que tú." - "¿Agregar Admin?" + "¿Agregar administrador?" + "Esta acción es irreversible. Estás transfiriendo la propiedad a los usuarios seleccionados. Una vez que salgas, será permanente." + "¿Transferir la propiedad?" "Degradar" "No podrás deshacer este cambio ya que te estás degradando. Si eres el último usuario privilegiado en la sala será imposible recuperar los privilegios." "¿Degradarte?" "%1$s (Pendiente)" "(Pendiente)" "Los administradores tienen privilegios de moderador de forma automática" + "Los propietarios tienen automáticamente privilegios de administrador." "Editar moderadores" + "Elegir propietarios" "Administradores" "Moderadores" "Miembros" @@ -46,11 +53,13 @@ "Se ha producido un error al cargar la configuración de las notificaciones." "No se ha podido silenciar esta sala, inténtalo de nuevo." "Error al dejar de silenciar esta sala, por favor inténtalo de nuevo." + "No cierres la aplicación hasta que se haya finalizado." + "Preparando invitaciones…" "Invitar personas" "Invitar" "Salir de la conversación" "Salir de la sala" - "Medios y archivos" + "Multimedia y archivos" "Personalizado" "Por defecto" "Notificaciones" @@ -58,16 +67,23 @@ "Perfil" "Solicitudes de unión" "Roles y permisos" + "Nombre" "Seguridad y privacidad" "Seguridad" "Compartir sala" "Información de la sala" "Tema" "Actualizando la sala…" - "No hay usuarios baneados." + "No hay usuarios vetados." + + "%1$d vetado" + "%1$d vetados" + + "Revisa la ortografía o intenta una nueva búsqueda." + "Ningún resultado para «%1$s»" - "%1$d Persona" - "%1$d Personas" + "%1$d persona" + "%1$d personas" "Sacar y vetar a un miembro" "Solo eliminar miembro" @@ -76,8 +92,14 @@ "Eliminar veto en la sala" "Vetados" "Miembros" + + "%1$d invitado" + "%1$d invitados" + + "Pendiente" "Administrador" "Moderador" + "Propietario" "Miembros de la sala" "Levantando veto a %1$s" "Permitir configuración personalizada" @@ -92,15 +114,17 @@ "No se pudo cambiar el modo, por favor inténtalo de nuevo." "Tu servidor base no admite esta opción en salas cifradas, no recibirás notificaciones de esta sala." "Todos los mensajes" - "Únicamente Menciones y Palabras clave" "En esta sala, notificarme por" "Administradores" + "Administradores y propietarios" "Cambiar mi rol" "Degradar a miembro" "Degradar a moderador" "Moderación de miembros" "Mensajes y contenido" "Moderadores" + "Propietarios" + "Permisos" "Restablecer permisos" "Una vez que restablezca los permisos, perderá la configuración actual." "¿Restablecer los permisos?" @@ -110,8 +134,10 @@ "Marcar como leído" "Marcar como no leído" "Agregar dirección" + "Cualquiera en espacios autorizados puede unirse, pero el resto debe solicitar acceso." "Todos deben solicitar acceso." "Solicitar unirse" + "Cualquiera en %1$s puede unirse, pero el resto debe solicitar acceso." "Sí, activar cifrado" "Una vez activado, el cifrado de una sala no se puede desactivar. El historial de mensajes solo será visible para los miembros de la sala desde que fueron invitados o desde que se unieron a la sala. Nadie más que los miembros de la sala podrán leer los mensajes. Esto puede impedir que los bots y los puentes funcionen correctamente. @@ -122,21 +148,29 @@ No recomendamos habilitar el cifrado para las salas que cualquiera pueda encontr "Activar el cifrado de extremo a extremo" "Cualquiera puede unirse" "Cualquiera" + "Elige qué miembros de los espacios pueden unirse a esta sala sin una invitación. %1$s" + "Gestionar espacios" "Solo las personas invitadas pueden unirse." "Solo por invitación" "Acceso" + "Cualquiera en espacios autorizados puede unirse." + "Cualquiera en %1$s puede unirse." + "Miembros del espacio" "No se admiten los espacios por el momento." "Necesitarás una dirección de sala para que sea visible en el directorio." "Dirección" "Permite encontrar esta sala buscando en el directorio de salas públicas de %1$s" + "Permitir que sea encontrada al buscar en el directorio público." "Visible en el directorio público" "Cualquiera (el historial es público)" + "Los cambios no afectarán a los mensajes anteriores, solo a los nuevos. %1$s" "Quién puede leer el historial" - "Solo participantes desde que fueron invitados" - "Miembros (historia completa)" + "Miembros desde su invitación" + "Miembros (historial completo)" "Las direcciones de sala son formas de buscar salas y acceder a ellas. Esto también garantiza que puedas compartir fácilmente tu sala con otras personas. Puedes optar por publicar tu sala en el directorio de salas públicas de tu servidor base." "Publicación de la sala" + "Las direcciones son una forma de encontrar y acceder a salas y espacios. También garantizan que puedas compartirlos fácilmente con otras personas." "Visibilidad" "Seguridad y privacidad" diff --git a/features/roomdetails/impl/src/main/res/values-et/translations.xml b/features/roomdetails/impl/src/main/res/values-et/translations.xml index e6962456ac..329ac267bf 100644 --- a/features/roomdetails/impl/src/main/res/values-et/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-et/translations.xml @@ -113,8 +113,7 @@ "Vaikimisi seadistuste taastamine ei õnnestunud. Palun proovi uuesti." "Seadistuste muutmine ei õnnestunud. Palun proovi uuesti." "Sinu koduserver ei toeta seda võimalust krüptitud jututubades, seega sa ei saa selle jututoa kohta teavitusi." - "Kõikide sõnumite korral" - "Mainimiste ja võtmesõnade alusel" + "Kõik sõnumid" "Selles jututoas teavita mind" "Peakasutajad" "Peakasutajad ja omanikud" diff --git a/features/roomdetails/impl/src/main/res/values-eu/translations.xml b/features/roomdetails/impl/src/main/res/values-eu/translations.xml index 64f32e44d9..e00aff7d4c 100644 --- a/features/roomdetails/impl/src/main/res/values-eu/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-eu/translations.xml @@ -83,7 +83,6 @@ "Errorea gertatu da jakinarazpen-ezarpenak kargatzean." "Zure zerbitzaria ez da bateragarria enkriptatutako gelen aukerarekin; litekeena da gela batzuetako jakinarazpenak ez jasotzea." "Mezu guztiak" - "Aipamenak eta hitz gakoak soilik" "Gela honetan, jakinarazi" "Administratzaileak" "Administratzaileak eta jabeak" diff --git a/features/roomdetails/impl/src/main/res/values-fa/translations.xml b/features/roomdetails/impl/src/main/res/values-fa/translations.xml index 7cdfe409dd..1ea8bc2e69 100644 --- a/features/roomdetails/impl/src/main/res/values-fa/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-fa/translations.xml @@ -1,6 +1,10 @@ - "نشانی اتاق" + "اعضای جدید تاریخچه را نمی‌بینند" + "اعضای جدید تاریخچه را می‌بینند" + "هر کسی می‌تواند تاریخچه را ببیند" + "برای اینکه بتوانید آن را در فهرست عمومی مشاهده کنید، به یک آدرس نیاز دارید." + "ویرایش آدرس" "هنگام به‌روز کردن تنظیمات آگاهی خطایی رخ داد." "کارساز خانگیتان از این گزینه در اتاق‌های رمز شده پشتیبانی نمی‌کند. ممکن است در برخی اتاق‌ها آگاه نشوید." "نظرسنجی‌ها" @@ -21,6 +25,7 @@ "ویرایش مدیران" "قادر نخواهید بود این کنش را بازکردانید. داردید کاربر را به سطح قدرت خودتان ارتقا می‌دهید." "افزودن مدیر؟" + "شما قادر به لغو این اقدام نخواهید بود. شما در حال انتقال مالکیت به کاربران انتخاب شده هستید. پس از خروج، این انتقال دائمی خواهد بود." "انتقال مالکیت؟" "تنزل بده" "شما نمی‌توانید این تغییر را بازگردانید زیرا در حال تنزل نقش خود در اتاق هستید، اگر آخرین کاربر ممتاز در اتاق باشید، امکان دستیابی مجدد به دسترسی‌های سطح بالای اتاق غیرممکن است." @@ -62,6 +67,7 @@ "نمایه" "درخواست‌های پیوستن" "نقش‌ها و مجوزها" + "نام" "امنیت و محرمانگی" "امنیت" "هم‌رسانی اتاق" @@ -69,6 +75,12 @@ "موضوع" "به‌روز کردن اتاق…" "هیچ کاربری محروم نشده." + + "%1$d محروم شد" + "%1$d محروم شد" + + "املای کلمات را بررسی کنید یا جستجوی جدیدی را امتحان کنید" + "هیچ نتیجه‌ای برای «%1$s» یافت نشد." "%1$d نفر" "%1$d نفر" @@ -80,6 +92,11 @@ "تحریم نکردن از اتاق" "محروم" "اعضا" + + "%1$d دعوت شده" + "%1$d دعوت شده" + + "در حال بررسی" "ادمین" "ناظم" "مالک" @@ -108,6 +125,7 @@ "پیام‌ها و محتوا" "ناظم‌ها" "مالکان" + "دسترسی‌ها" "بازنشانی اجازه‌ها" "پس از بازنشانی اجازه‌ها تنظیمات فعلی را از دست خواهید داد." "بازنشانی اجازه‌ها؟" @@ -116,21 +134,44 @@ "نقش‌ها و مجوزها" "علامت‌گذاری به عنوان خوانده شده" "نشان به ناخوانده" - "افزودن نشانی اتاق" + "اضافه کردن آدرس" + "هر کسی که در فضاهای مجاز باشد می‌تواند عضو شود، اما بقیه باید درخواست دسترسی بدهند." + "همه باید درخواست دسترسی بدهند." "درخواست دعوت" + "هر کسی در %1$s می‌تواند عضو شود، اما بقیه باید درخواست دسترسی بدهند." "بله. به کار انداختن رمزنگاری" + "پس از فعال کردن، رمزگذاری برای یک اتاق قابل غیرفعال کردن نیست، تاریخچه پیام فقط برای اعضای اتاق از زمان دعوت یا از زمان پیوستن به اتاق قابل مشاهده خواهد بود. +هیچ کس غیر از اعضای اتاق قادر به خواندن پیام‌ها نخواهد بود. این ممکن است مانع از عملکرد صحیح ربات‌ها و پل‌ها شود. +ما فعال کردن رمزگذاری را برای اتاق‌هایی که هر کسی می‌تواند آنها را پیدا کند و به آنها بپیوندد، توصیه نمی‌کنیم." "رمزگذاری فعال شود؟" "پس از به کار افتادن، رمزنگاری قابل از کار انداختن نیست." "رمزنگاری" - "هرکسی می‌تواند یافته و بپیوندد" - "هرکسی" - "افراد فقط در صورت دعوت می‌توانند بپیوندند" - "فقط دعوتی" - "دسترسی اتاق" + "فعال کردن رمزنگاری سراسری" + "هر کسی می‌تواند عضو شود." + "هر کس" + "انتخاب کنید که اعضای کدام فضاها می‌توانند بدون دعوتنامه به این اتاق بپیوندند. %1$s" + "مدیریت فضاها" + "فقط افراد دعوت شده می‌توانند عضو شوند." + "فقط دعوت" + "دسترسی" + "هر کسی که در فضاهای مجاز باشد می‌تواند عضو شود." + "هر کسی که در %1$s باشد می‌تواند عضو شود." + "اعضای فضا" "در حال حاضر فضاها پشتیبانی نمی‌شوند" - "نشانی اتاق" + "برای اینکه بتوانید آن را در فهرست عمومی مشاهده کنید، به یک آدرس نیاز دارید." + "آدرس" + "با جستجو در فهرست اتاق‌های عمومی %1$s، امکان یافتن این اتاق را فراهم کنید." + "با جستجو در فهرست عمومی، می‌توان آن را پیدا کرد." + "قابل مشاهده در فهرست عمومی" "هرکسی" + "تغییرات روی پیام‌های قبلی تأثیری نخواهند داشت، فقط روی پیام‌های جدید اعمال می‌شوند. %1$s" + "چه کسی می‌تواند تاریخ بخواند؟" + "اعضا از زمان دعوت" + "اعضا (تاریخچه کامل)" + "آدرس‌های اتاق، راه‌هایی برای پیدا کردن و دسترسی به اتاق‌ها هستند. این همچنین تضمین می‌کند که می‌توانید به راحتی اتاق خود را با دیگران به اشتراک بگذارید. +شما می‌توانید اتاق خود را در دایرکتوری عمومی اتاق سرور خانگی خود منتشر کنید." "انتشار اتاق" - "نمایانی اتاق" + "آدرس‌ها راهی برای پیدا کردن و دسترسی به اتاق‌ها و فضاها هستند. این همچنین تضمین می‌کند که می‌توانید به راحتی آنها را با دیگران به اشتراک بگذارید." + "قابلیت مشاهده" "امنیت و محرمانگی" diff --git a/features/roomdetails/impl/src/main/res/values-fi/translations.xml b/features/roomdetails/impl/src/main/res/values-fi/translations.xml index 4eafca087e..b6586d8884 100644 --- a/features/roomdetails/impl/src/main/res/values-fi/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-fi/translations.xml @@ -115,6 +115,7 @@ "Kotipalvelimesi ei tue tätä vaihtoehtoa salatuissa huoneissa, joten et saa ilmoituksia tästä huoneesta." "Kaikista viesteistä" "Vain maininnoista ja avainsanoista" + "Mykistä" "Ilmoita minulle tässä huoneessa" "Ylläpitäjät" "Ylläpitäjät ja omistajat" diff --git a/features/roomdetails/impl/src/main/res/values-fr/translations.xml b/features/roomdetails/impl/src/main/res/values-fr/translations.xml index 0d6844cb7e..237767c82a 100644 --- a/features/roomdetails/impl/src/main/res/values-fr/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-fr/translations.xml @@ -114,8 +114,9 @@ "Échec de la configuration du mode, veuillez réessayer." "Votre serveur d’accueil ne supporte pas cette option pour les salons chiffrés, vous ne serez pas notifié(e) dans ce salon." "Tous les messages" - "Mentions et mots clés uniquement" - "Dans ce salon, prévenez-moi pour" + "Les messages avec mentions et mots clés uniquement" + "Aucun message" + "Pour ce salon, afficher une notification pour" "Administrateurs" "Administrateurs et propriétaires" "Changer mon rôle" diff --git a/features/roomdetails/impl/src/main/res/values-hr/translations.xml b/features/roomdetails/impl/src/main/res/values-hr/translations.xml index 5619164dd2..fffdc33e40 100644 --- a/features/roomdetails/impl/src/main/res/values-hr/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-hr/translations.xml @@ -116,8 +116,6 @@ "Vraćanje zadanog načina rada nije uspjelo, pokušajte ponovno." "Postavljanje načina rada nije uspjelo, pokušajte ponovno." "Vaš matični poslužitelj ne podržava ovu mogućnost u šifriranim sobama; nećete dobiti obavijest u ovoj sobi." - "Sve poruke" - "Samo spominjanja i ključne riječi" "U ovoj sobi obavijesti me za" "Administratori" "Administratori i vlasnici" diff --git a/features/roomdetails/impl/src/main/res/values-it/translations.xml b/features/roomdetails/impl/src/main/res/values-it/translations.xml index b8a18d4421..c876567303 100644 --- a/features/roomdetails/impl/src/main/res/values-it/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-it/translations.xml @@ -114,7 +114,6 @@ "Impossibile impostare la modalità, riprova." "Il tuo homeserver non supporta questa opzione nelle stanze cifrate, quindi non riceverai notifiche in questa stanza." "Tutti i messaggi" - "Solo menzioni e parole chiave" "In questa stanza, avvisami per" "Amministratori" "Amministratori e proprietari" diff --git a/features/roomdetails/impl/src/main/res/values-ja/translations.xml b/features/roomdetails/impl/src/main/res/values-ja/translations.xml index bf0ef7424c..830ebd5452 100644 --- a/features/roomdetails/impl/src/main/res/values-ja/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-ja/translations.xml @@ -110,8 +110,6 @@ "デフォルトの復元に失敗しました。再試行してください。" "設定に失敗しました。再試行してください。" "暗号化されたルームでは、この機能にホームサーバーが対応しないため、このルームからの通知を受信できません。" - "すべてのメッセージ" - "メンションとキーワードのみ" "このルームでは以下の通知を受け取る" "管理者" "管理者と所有者" diff --git a/features/roomdetails/impl/src/main/res/values-ka/translations.xml b/features/roomdetails/impl/src/main/res/values-ka/translations.xml index 8fd0b2c8a6..6bc01b34b9 100644 --- a/features/roomdetails/impl/src/main/res/values-ka/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-ka/translations.xml @@ -79,7 +79,6 @@ "რეჟიმის დაყენება ვერ მოხერხდა, გთხოვთ, სცადოთ ხელახლა." "თქვენი სახლის სერვერი არ უჭერს მხარს ამ პარამეტრს დაშიფრულ ოთახებში, თქვენ არ მიიღებთ შეტყობინებას ამ ოთახში." "ყველა შეტყობინება" - "მხოლოდ ხსენებები და საკვანძო სიტყვები" "ამ ოთახში, შემატყობინეთ:" "ადმინისტრატორები" "ჩემი როლის შეცვლა" diff --git a/features/roomdetails/impl/src/main/res/values-ko/translations.xml b/features/roomdetails/impl/src/main/res/values-ko/translations.xml index 4a32cab45d..3d0a106e25 100644 --- a/features/roomdetails/impl/src/main/res/values-ko/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-ko/translations.xml @@ -111,7 +111,6 @@ "모드 설정이 실패했습니다. 다시 시도해 주세요." "귀하의 홈 서버는 암호화된 방에서 이 옵션을 지원하지 않으므로, 이 방에서 알림을 받지 못합니다." "모든 메시지" - "언급 및 키워드만" "이 방에서, 알림을 주세요" "관리자" "관리자 및 소유자" diff --git a/features/roomdetails/impl/src/main/res/values-nb/translations.xml b/features/roomdetails/impl/src/main/res/values-nb/translations.xml index 0cb3dfc268..8507587f95 100644 --- a/features/roomdetails/impl/src/main/res/values-nb/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-nb/translations.xml @@ -114,7 +114,6 @@ "Innstilling av modus mislyktes, prøv igjen." "Hjemmeserveren din støtter ikke dette alternativet i krypterte rom, og du vil ikke bli varslet i dette rommet." "Alle meldinger" - "Bare omtaler og nøkkelord" "I dette rommet, varsle meg om" "Administratorer" "Administratorer og eiere" diff --git a/features/roomdetails/impl/src/main/res/values-nl/translations.xml b/features/roomdetails/impl/src/main/res/values-nl/translations.xml index 2ee5caca97..a25a674edc 100644 --- a/features/roomdetails/impl/src/main/res/values-nl/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-nl/translations.xml @@ -85,7 +85,6 @@ "Het instellen van de meldingen is mislukt. Probeer het opnieuw." "Je homeserver ondersteunt deze optie niet in versleutelde kamers; in deze kamer krijg je geen meldingen." "Alle berichten" - "Alleen vermeldingen en trefwoorden" "In deze kamer, stuur me een melding voor" "Beheerders" "Mijn rol wijzigen" diff --git a/features/roomdetails/impl/src/main/res/values-pl/translations.xml b/features/roomdetails/impl/src/main/res/values-pl/translations.xml index b79d3014e5..14225bcdf9 100644 --- a/features/roomdetails/impl/src/main/res/values-pl/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-pl/translations.xml @@ -118,6 +118,7 @@ "Twój serwer domowy nie wspiera tej opcji w pokojach szyfrowanych, możesz nie otrzymać powiadomień z tego pokoju." "Wszystkie wiadomości" "Tylko wzmianki i słowa kluczowe" + "Wycisz" "W tym pokoju, powiadamiaj mnie przez" "Administratorzy" "Administratorzy i właściciele" diff --git a/features/roomdetails/impl/src/main/res/values-pt-rBR/translations.xml b/features/roomdetails/impl/src/main/res/values-pt-rBR/translations.xml index f2ddfb86cb..e741c43c90 100644 --- a/features/roomdetails/impl/src/main/res/values-pt-rBR/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-pt-rBR/translations.xml @@ -111,7 +111,6 @@ "Falha ao definir o modo, tente novamente." "Seu servidor-casa não suporta esta opção em salas criptografadas, você não será notificado nesta sala." "Todas as mensagens" - "Somente menções e palavras-chave" "Nesta sala, notifique-me de" "Administradores" "Administradores e proprietários" diff --git a/features/roomdetails/impl/src/main/res/values-pt/translations.xml b/features/roomdetails/impl/src/main/res/values-pt/translations.xml index 04ded84480..53eaebb934 100644 --- a/features/roomdetails/impl/src/main/res/values-pt/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-pt/translations.xml @@ -109,8 +109,7 @@ "Falha ao restaurar o modo predefinido, tenta novamente." "Falha ao definir o modo, tenta novamente." "O teu servidor não suporta esta opção em salas cifradas, pelo que não serás notificado nesta sala." - "Qualquer mensagem" - "Menções ou palavras-chave" + "Todas as mensagens" "Nesta sala, notifica-me se" "Administradores" "Administradores e donos" diff --git a/features/roomdetails/impl/src/main/res/values-ro/translations.xml b/features/roomdetails/impl/src/main/res/values-ro/translations.xml index f3feda811a..ced134da3d 100644 --- a/features/roomdetails/impl/src/main/res/values-ro/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-ro/translations.xml @@ -118,6 +118,7 @@ "Serverul dumneavoastră nu acceptă această opțiune în camerele criptate, nu veți primi notificări în această cameră." "Toate mesajele" "Numai mențiuni și cuvinte cheie" + "Mut" "În această cameră, anunțați-mă pentru" "Administratori" "Administratori și proprietari" diff --git a/features/roomdetails/impl/src/main/res/values-sv/translations.xml b/features/roomdetails/impl/src/main/res/values-sv/translations.xml index aa9f244498..764b18de76 100644 --- a/features/roomdetails/impl/src/main/res/values-sv/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-sv/translations.xml @@ -99,7 +99,6 @@ "Misslyckades att ställa in läget, vänligen pröva igen." "Din hemserver stöder inte det här alternativet i krypterade rum, du blir inte aviserad i det här rummet." "Alla meddelanden" - "Endast omnämnanden och nyckelord" "I det här rummet, meddela mig för" "Administratörer" "Administratörer och ägare" diff --git a/features/roomdetails/impl/src/main/res/values-tr/translations.xml b/features/roomdetails/impl/src/main/res/values-tr/translations.xml index a9bfc6fbe2..9f78649509 100644 --- a/features/roomdetails/impl/src/main/res/values-tr/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-tr/translations.xml @@ -97,7 +97,6 @@ "Ayarlanamadı, lütfen tekrar deneyin." "Ana sunucunuz şifreli odalarda bu seçeneği desteklemiyor, bu odada bildirim almayacaksınız." "Tüm mesajlar" - "Yalnızca Bahsetmeler ve Anahtar Kelimeler" "Bu odada, bana bildir" "Yöneticiler" "Rolümü değiştir" diff --git a/features/roomdetails/impl/src/main/res/values-uk/translations.xml b/features/roomdetails/impl/src/main/res/values-uk/translations.xml index 8f566bb235..edc1fab508 100644 --- a/features/roomdetails/impl/src/main/res/values-uk/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-uk/translations.xml @@ -117,7 +117,8 @@ "Не вдалося встановити режим, спробуйте ще раз." "Ваш домашній сервер не підтримує цю опцію в зашифрованих кімнатах, ви не отримаєте сповіщення в цій кімнаті." "Всі повідомлення" - "Тільки згадки та ключові слова" + "Лише згадки та ключові слова" + "Вимкнути звук" "У цій кімнаті сповіщати мене про" "Адміністратори" "Адміністратори та власники" diff --git a/features/roomdetails/impl/src/main/res/values-ur/translations.xml b/features/roomdetails/impl/src/main/res/values-ur/translations.xml index 5c32811f36..89387da0de 100644 --- a/features/roomdetails/impl/src/main/res/values-ur/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-ur/translations.xml @@ -83,8 +83,6 @@ "متعین وضع کو بحال کرنے میں ناکام، برائے مہربانی دوبارہ کوشش کریں۔" "وضع ترتیب دینے میں ناکام، برائے مہربانی دوبارہ کوشش کریں۔" "آپ کا منزلی خادم مرموز کردہ کمروں میں اس اختیار کی حمایت نہیں کرتا ہے، آپ کو اس کمرے میں مطلع کیا جائے گا۔" - "تمام پیغامات" - "صرف تذکرے اور کلیدی الفاظ" "اس کمرے میں، مجھے مطلع کریں برائے" "منتظمین" "میرا کردار تبدیل کریں" diff --git a/features/roomdetails/impl/src/main/res/values-uz/translations.xml b/features/roomdetails/impl/src/main/res/values-uz/translations.xml index d7778f2df4..10ffe9cf95 100644 --- a/features/roomdetails/impl/src/main/res/values-uz/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-uz/translations.xml @@ -114,7 +114,6 @@ "Rejimni o‘rnatib bo‘lmadi, qayta urinib ko‘ring." "Uy serveringiz shifrlangan xonalarda ushbu imkoniyatni qoʻllab-quvvatlamaydi, shuning uchun bu xonadan bildirishnomalar olmaysiz." "Barcha xabarlar" - "Faqat eslatmalar va kalit so\'zlar" "Bu xonada menga xabar bering" "Adminlar" "Adminlar va egalari" diff --git a/features/roomdetails/impl/src/main/res/values-vi/translations.xml b/features/roomdetails/impl/src/main/res/values-vi/translations.xml index ecc7e4e227..df42b37f77 100644 --- a/features/roomdetails/impl/src/main/res/values-vi/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-vi/translations.xml @@ -90,8 +90,6 @@ "Không thể khôi phục chế độ mặc định, vui lòng thử lại." "Không thể thiết lập chế độ, hãy thử lại nhé." "Máy chủ không hỗ trợ tùy chọn này trong phòng mã hóa, bạn sẽ không nhận thông báo ở đây." - "Tất cả tin nhắn." - "Chỉ đề cập và từ khóa" "Trong phòng này, thông báo cho tôi khi" "Quản trị viên" "Thay đổi vai trò của tôi" diff --git a/features/roomdetails/impl/src/main/res/values-zh/translations.xml b/features/roomdetails/impl/src/main/res/values-zh/translations.xml index 8a5c5734ed..a7592c38c7 100644 --- a/features/roomdetails/impl/src/main/res/values-zh/translations.xml +++ b/features/roomdetails/impl/src/main/res/values-zh/translations.xml @@ -111,7 +111,8 @@ "设置模式失败,请重试。" "主服务器不支持在加密房间中的此选项,因此在此房间你可能无法收到通知。" "所有消息" - "仅限提及和关键词" + "仅提及与关键词" + "静默" "在此房间通知我以下类型" "管理员" "管理员与所有者" diff --git a/features/roomdetails/impl/src/main/res/values/localazy.xml b/features/roomdetails/impl/src/main/res/values/localazy.xml index 31851c2603..05bdb50d6e 100644 --- a/features/roomdetails/impl/src/main/res/values/localazy.xml +++ b/features/roomdetails/impl/src/main/res/values/localazy.xml @@ -115,6 +115,7 @@ "Your homeserver does not support this option in encrypted rooms, you won\'t get notified in this room." "All messages" "Mentions and replies only" + "Mute" "In this room, notify me for" "Admins" "Admins and owners" diff --git a/features/roomdetails/impl/src/test/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenterTest.kt b/features/roomdetails/impl/src/test/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenterTest.kt index 48f0e791a3..0a88d2bf57 100644 --- a/features/roomdetails/impl/src/test/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenterTest.kt +++ b/features/roomdetails/impl/src/test/kotlin/io/element/android/features/roomdetails/impl/members/RoomMemberListPresenterTest.kt @@ -191,6 +191,38 @@ class RoomMemberListPresenterTest { awaitItem().eventSink(RoomMemberListEvent.RoomMemberSelected(anInvitedVictor())) } } + + @Test + fun `call participants are shown first in joined members`() = runTest { + val room = createFakeJoinedRoom().apply { + givenRoomInfo( + aRoomInfo( + joinedMembersCount = 5, + activeRoomCallParticipants = listOf( + aCarol().userId + ), + ) + ) + givenRoomMembersState(RoomMembersState.Ready(aRoomMemberList())) + } + + val presenter = createPresenter(joinedRoom = room) + + presenter.test { + skipItems(1) + + val loadedState = awaitItem() + val joined = loadedState.filteredRoomMembers.dataOrNull()!!.joined + + assertThat(joined.first().roomMember.userId) + .isEqualTo(aCarol().userId) + + assertThat(joined.first().isInCall).isTrue() + + assertThat(joined.count { it.isInCall }).isEqualTo(1) + assertThat(joined.drop(1).all { !it.isInCall }).isTrue() + } + } } private fun createFakeJoinedRoom( diff --git a/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditStateProvider.kt b/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditStatePreviewParam.kt similarity index 96% rename from features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditStateProvider.kt rename to features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditStatePreviewParam.kt index a6e2e3798b..b58cf5db49 100644 --- a/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditStateProvider.kt +++ b/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.permissions.api.PermissionsState import io.element.android.libraries.permissions.api.aPermissionsState import kotlinx.collections.immutable.toImmutableList -open class RoomDetailsEditStateProvider : PreviewParameterProvider { +open class RoomDetailsEditStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomDetailsEditState(), diff --git a/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditView.kt b/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditView.kt index 9cdc800267..04c8796285 100644 --- a/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditView.kt +++ b/features/roomdetailsedit/impl/src/main/kotlin/io/element/android/features/roomdetailsedit/impl/RoomDetailsEditView.kt @@ -185,7 +185,7 @@ fun RoomDetailsEditView( @PreviewsDayNight @Composable -internal fun RoomDetailsEditViewPreview(@PreviewParameter(RoomDetailsEditStateProvider::class) state: RoomDetailsEditState) = ElementPreview { +internal fun RoomDetailsEditViewPreview(@PreviewParameter(RoomDetailsEditStatePreviewParam::class) state: RoomDetailsEditState) = ElementPreview { RoomDetailsEditView( state = state, onDone = {}, diff --git a/features/roomdetailsedit/impl/src/main/res/values-ar/translations.xml b/features/roomdetailsedit/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..5d58de994f --- /dev/null +++ b/features/roomdetailsedit/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,7 @@ + + + "تعديل التفاصيل" + "قد كان هناك خطأ والمعلومات لم تتحدث." + "غير قادر على تعديل الغرفة" + "يتم تحديث الغرفة…" + diff --git a/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryStateProvider.kt b/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryStatePreviewParam.kt similarity index 96% rename from features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryStateProvider.kt rename to features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryStatePreviewParam.kt index 4ee90fdf16..d7869f3d06 100644 --- a/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryStateProvider.kt +++ b/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.matrix.api.core.RoomId import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -open class RoomDirectoryStateProvider : PreviewParameterProvider { +open class RoomDirectoryStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomDirectoryState(), diff --git a/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryView.kt b/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryView.kt index dd9098b7ad..b880a4d28e 100644 --- a/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryView.kt +++ b/features/roomdirectory/impl/src/main/kotlin/io/element/android/features/roomdirectory/impl/root/RoomDirectoryView.kt @@ -278,7 +278,7 @@ private fun RoomDirectoryRoomRow( @PreviewsDayNight @Composable -internal fun RoomDirectoryViewPreview(@PreviewParameter(RoomDirectoryStateProvider::class) state: RoomDirectoryState) = ElementPreview { +internal fun RoomDirectoryViewPreview(@PreviewParameter(RoomDirectoryStatePreviewParam::class) state: RoomDirectoryState) = ElementPreview { RoomDirectoryView( state = state, onResultClick = {}, diff --git a/features/roomdirectory/impl/src/main/res/values-ar/translations.xml b/features/roomdirectory/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..ff40f27f27 --- /dev/null +++ b/features/roomdirectory/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,5 @@ + + + "فشل التحميل" + "دليل الغرف" + diff --git a/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationEvents.kt b/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationEvents.kt index 2238ff41df..d452ff4e66 100644 --- a/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationEvents.kt +++ b/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationEvents.kt @@ -10,6 +10,9 @@ package io.element.android.features.roommembermoderation.api import io.element.android.libraries.matrix.api.user.MatrixUser +/** + * Events sent to the moderation presenter through [RoomMemberModerationState.eventSink]. + */ interface RoomMemberModerationEvents { data class ShowActionsForUser(val user: MatrixUser) : RoomMemberModerationEvents data class ProcessAction(val action: ModerationAction, val targetUser: MatrixUser) : RoomMemberModerationEvents diff --git a/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationRenderer.kt b/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationRenderer.kt index efc87d8a40..7696f826a1 100644 --- a/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationRenderer.kt +++ b/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationRenderer.kt @@ -12,7 +12,18 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import io.element.android.libraries.matrix.api.user.MatrixUser +/** + * Renders the moderation action sheet and its confirmation dialogs; it draws nothing until the host screen asks for a member's actions. + */ interface RoomMemberModerationRenderer { + /** + * Draws whichever sheet or dialog the current state calls for. + * + * @param state the state produced by the moderation presenter. + * @param onSelectAction called when the user picks an action, so the host screen can navigate if that action needs its own screen. + * @param onAvatarClick called when the user taps the member's avatar, or `null` to make it non-interactive. + * @param modifier layout modifier for the container. + */ @Composable fun Render( state: RoomMemberModerationState, diff --git a/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationState.kt b/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationState.kt index c9ee958f6f..9227c77edf 100644 --- a/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationState.kt +++ b/features/roommembermoderation/api/src/main/kotlin/io/element/android/features/roommembermoderation/api/RoomMemberModerationState.kt @@ -10,9 +10,15 @@ package io.element.android.features.roommembermoderation.api import androidx.compose.runtime.Immutable +/** + * State of the member moderation flow, which is the action sheet and the confirmation dialogs shown for a room member. + */ @Immutable interface RoomMemberModerationState { + /** Which moderation actions the current user is allowed to perform, so the UI can hide or disable the rest. */ val permissions: RoomMemberModerationPermissions + + /** Where the host screen sends its events to open the actions of a member or run one of them. */ val eventSink: (RoomMemberModerationEvents) -> Unit } diff --git a/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/InternalRoomMemberModerationStateProvider.kt b/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/InternalRoomMemberModerationStatePreviewParam.kt similarity index 97% rename from features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/InternalRoomMemberModerationStateProvider.kt rename to features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/InternalRoomMemberModerationStatePreviewParam.kt index 2c32f2c47a..78358da213 100644 --- a/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/InternalRoomMemberModerationStateProvider.kt +++ b/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/InternalRoomMemberModerationStatePreviewParam.kt @@ -20,7 +20,7 @@ import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.MatrixUser import kotlinx.collections.immutable.toImmutableList -class InternalRoomMemberModerationStateProvider : PreviewParameterProvider { +class InternalRoomMemberModerationStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomMembersModerationState( diff --git a/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/RoomMemberModerationView.kt b/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/RoomMemberModerationView.kt index a5e0ac274f..f1c6cc8ed3 100644 --- a/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/RoomMemberModerationView.kt +++ b/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/RoomMemberModerationView.kt @@ -362,7 +362,7 @@ private fun RoomMemberActionsBottomSheet( @PreviewsDayNight @Composable -internal fun RoomMemberModerationViewPreview(@PreviewParameter(InternalRoomMemberModerationStateProvider::class) state: InternalRoomMemberModerationState) { +internal fun RoomMemberModerationViewPreview(@PreviewParameter(InternalRoomMemberModerationStatePreviewParam::class) state: InternalRoomMemberModerationState) { val isDoingAction = listOf(state.kickUserAsyncAction, state.banUserAsyncAction, state.unbanUserAsyncAction).any { it is AsyncAction.Loading } val modifier = if (isDoingAction) { Modifier.fillMaxWidth().heightIn(min = 64.dp) diff --git a/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/di/RoomMemberModerationModule.kt b/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/di/RoomMemberModerationBindingContainer.kt similarity index 94% rename from features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/di/RoomMemberModerationModule.kt rename to features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/di/RoomMemberModerationBindingContainer.kt index ab82f6ced4..1ffe6df41f 100644 --- a/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/di/RoomMemberModerationModule.kt +++ b/features/roommembermoderation/impl/src/main/kotlin/io/element/android/features/roommembermoderation/impl/di/RoomMemberModerationBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.di.RoomScope @ContributesTo(RoomScope::class) @BindingContainer -interface RoomMemberModerationModule { +interface RoomMemberModerationBindingContainer { @Binds fun bindRoomMemberModerationPresenter(presenter: RoomMemberModerationPresenter): Presenter } diff --git a/features/roommembermoderation/impl/src/main/res/values-ar/translations.xml b/features/roommembermoderation/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..3a425d4d7d --- /dev/null +++ b/features/roommembermoderation/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,22 @@ + + + "حظر المستخدم" + "حظر" + "لن يتمكن هذا العضو من الانضمام مرة أخرى حتى إذا تمت دعوته." + "هل أنت متأكد من أنك تريد حظر هذا العضو؟" + "لن يتمكن هذا المستخدم من الانضمام إلى هذه المساحة مرة أخرى إذا تمت دعوته، لكنه سيظل محتفظًا بعضويته في أي غرف أو مساحات فرعية." + "جارٍ حظر %1$s" + "إزالة" + "يمكن لهذا المستخدم الانضمام إلى هذه الغرفة مرة أخرى عند دعوته." + "هل أنت متأكد من رغبتك في إزالة هذا العضو؟" + "سيتمكن هذا المستخدم من الانضمام إلى هذه المساحة مرة أخرى إذا تمت دعوته، وسيظل محتفظًا بعضويته في أي غرف أو مساحات فرعية." + "عرض الملف الشخصي" + "إزالة المستخدم" + "إزالة العضو وحظره من الانضمام مستقبلًا؟" + "جارٍ إزالة %1$s…" + "إلغاء حظر المستخدم" + "إلغاء الحظر" + "سيتمكن هذا المستخدم من الانضمام مرة أخرى إذا تمت دعوته" + "هل أنت متأكد من رغبتك في إلغاء حظر هذا العضو؟" + "جارٍ رفع حظر %1$s" + diff --git a/features/roommembermoderation/impl/src/main/res/values-es/translations.xml b/features/roommembermoderation/impl/src/main/res/values-es/translations.xml index 7f83f7546e..7f4a1e96cf 100644 --- a/features/roommembermoderation/impl/src/main/res/values-es/translations.xml +++ b/features/roommembermoderation/impl/src/main/res/values-es/translations.xml @@ -4,10 +4,12 @@ "Vetar" "No podrán volver a unirse a esta sala si son invitados." "¿Estás seguro de que quieres vetar a este miembro?" + "No podrá volver a unirse a este espacio aunque le inviten, pero seguirá siendo miembro de cualquier sala o subespacio donde ya lo fuese." "Vetando a %1$s" "Echar" "Podrá volver a unirse a esta sala si se le invita." "¿Seguro que quieres echar a este miembro?" + "Podrá volver a unirse a este espacio si se le invita, y seguirá siendo miembro de cualquier sala o subespacio donde ya lo fuese." "Ver perfil" "Sacar de la sala" "¿Sacar al miembro y prohibirle unirse en el futuro?" diff --git a/features/roommembermoderation/impl/src/main/res/values-fa/translations.xml b/features/roommembermoderation/impl/src/main/res/values-fa/translations.xml index 6ddb482189..d647dd1915 100644 --- a/features/roommembermoderation/impl/src/main/res/values-fa/translations.xml +++ b/features/roommembermoderation/impl/src/main/res/values-fa/translations.xml @@ -4,15 +4,19 @@ "تحریم" "در صورت دعوت نمی‌تواند دوباره به اتاق بپیوندد." "مطمئنید می‌خواهید این عضو را تحریم کنید؟" + "در صورت دعوت، آنها دیگر نمی‌توانند به این فضا بپیوندند، اما همچنان عضویت خود در هر اتاق یا زیرفضا را حفظ خواهند کرد." "تحریم کردن %1$s" "برداشتن" "در صورت دعوت می‌تواند دوباره به اتاق بپیوندد." "مطمئنید می‌خواهید این عضو را بردارید؟" + "در صورت دعوت، آنها می‌توانند دوباره به این فضا بپیوندند و همچنان عضویت خود را در هر اتاق یا زیرفضا حفظ خواهند کرد." "دیدن نمایه" "حذف کاربر" "برداشتن عضو و تحریم پیوستن در آینده؟" "برداشتن %1$s…" "تحریم نکردن از اتاق" "رفع انسداد" + "در صورت دعوت، آنها می‌توانند دوباره بپیوندند" + "آیا مطمئن هستید که می‌خواهید این عضو را از حالت مسدود خارج کنید؟" "رفع تحریم %1$s" diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableStateProvider.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableStatePreviewParam.kt similarity index 92% rename from features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableStateProvider.kt rename to features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableStatePreviewParam.kt index 6aa10d9a0b..6eea9c366a 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableStateProvider.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.encryption.BackupState -open class SecureBackupDisableStateProvider : PreviewParameterProvider { +open class SecureBackupDisableStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSecureBackupDisableState(), diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableView.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableView.kt index 24678148b4..423e2ed5da 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableView.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/disable/SecureBackupDisableView.kt @@ -112,7 +112,7 @@ private fun SecureBackupDisableItem(text: String) { @PreviewsDayNight @Composable internal fun SecureBackupDisableViewPreview( - @PreviewParameter(SecureBackupDisableStateProvider::class) state: SecureBackupDisableState + @PreviewParameter(SecureBackupDisableStatePreviewParam::class) state: SecureBackupDisableState ) = ElementPreview { SecureBackupDisableView( state = state, diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyStateProvider.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyStatePreviewParam.kt similarity index 94% rename from features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyStateProvider.kt rename to features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyStatePreviewParam.kt index 5e95b5713e..5041f4ab92 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyStateProvider.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyStatePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.features.securebackup.impl.setup.views.RecoveryKeyView import io.element.android.features.securebackup.impl.setup.views.aFormattedRecoveryKey import io.element.android.libraries.architecture.AsyncAction -open class SecureBackupEnterRecoveryKeyStateProvider : PreviewParameterProvider { +open class SecureBackupEnterRecoveryKeyStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSecureBackupEnterRecoveryKeyState(recoveryKey = ""), diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyView.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyView.kt index 34fca33e96..823bbf5c80 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyView.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/enter/SecureBackupEnterRecoveryKeyView.kt @@ -97,7 +97,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable internal fun SecureBackupEnterRecoveryKeyViewPreview( - @PreviewParameter(SecureBackupEnterRecoveryKeyStateProvider::class) state: SecureBackupEnterRecoveryKeyState + @PreviewParameter(SecureBackupEnterRecoveryKeyStatePreviewParam::class) state: SecureBackupEnterRecoveryKeyState ) = ElementPreview { SecureBackupEnterRecoveryKeyView( state = state, diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordStateProvider.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordStatePreviewParam.kt similarity index 91% rename from features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordStateProvider.kt rename to features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordStatePreviewParam.kt index fc4ce2430e..b6e786a9bc 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordStateProvider.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.securebackup.impl.reset.password import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -class ResetIdentityPasswordStateProvider : PreviewParameterProvider { +class ResetIdentityPasswordStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aResetIdentityPasswordState(), diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordView.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordView.kt index 3bb77ac206..27612a7b4d 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordView.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/password/ResetIdentityPasswordView.kt @@ -106,7 +106,7 @@ private fun Content(text: String, onTextChange: (String) -> Unit, hasError: Bool @PreviewsDayNight @Composable -internal fun ResetIdentityPasswordViewPreview(@PreviewParameter(ResetIdentityPasswordStateProvider::class) state: ResetIdentityPasswordState) { +internal fun ResetIdentityPasswordViewPreview(@PreviewParameter(ResetIdentityPasswordStatePreviewParam::class) state: ResetIdentityPasswordState) { ElementPreview { ResetIdentityPasswordView( state = state, diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootStateProvider.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootStatePreviewParam.kt similarity index 88% rename from features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootStateProvider.kt rename to features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootStatePreviewParam.kt index 697401367f..e4bb24355e 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootStateProvider.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.securebackup.impl.reset.root import androidx.compose.ui.tooling.preview.PreviewParameterProvider -class ResetIdentityRootStateProvider : PreviewParameterProvider { +class ResetIdentityRootStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( ResetIdentityRootState( diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootView.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootView.kt index 7ac8dbe4cf..0109bd4faf 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootView.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/reset/root/ResetIdentityRootView.kt @@ -130,7 +130,7 @@ private fun Content() { @PreviewsDayNight @Composable -internal fun ResetIdentityRootViewPreview(@PreviewParameter(ResetIdentityRootStateProvider::class) state: ResetIdentityRootState) { +internal fun ResetIdentityRootViewPreview(@PreviewParameter(ResetIdentityRootStatePreviewParam::class) state: ResetIdentityRootState) { ElementPreview { ResetIdentityRootView( state = state, diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootStateProvider.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootStatePreviewParam.kt similarity index 97% rename from features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootStateProvider.kt rename to features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootStatePreviewParam.kt index 5dc3bea7e8..3247db78eb 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootStateProvider.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.designsystem.utils.snackbar.SnackbarMessage import io.element.android.libraries.matrix.api.encryption.BackupState import io.element.android.libraries.matrix.api.encryption.RecoveryState -open class SecureBackupRootStateProvider : PreviewParameterProvider { +open class SecureBackupRootStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSecureBackupRootState(backupState = BackupState.UNKNOWN, doesBackupExistOnServer = AsyncData.Uninitialized), diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootView.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootView.kt index 626a162152..8059329cd0 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootView.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/root/SecureBackupRootView.kt @@ -236,7 +236,7 @@ private fun LoadingView() { @PreviewsDayNight @Composable internal fun SecureBackupRootViewPreview( - @PreviewParameter(SecureBackupRootStateProvider::class) state: SecureBackupRootState + @PreviewParameter(SecureBackupRootStatePreviewParam::class) state: SecureBackupRootState ) = ElementPreview { SecureBackupRootView( state = state, diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupStateProvider.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupStatePreviewParam.kt similarity index 95% rename from features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupStateProvider.kt rename to features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupStatePreviewParam.kt index a780fa0c36..f88fd56d79 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupStateProvider.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.features.securebackup.impl.setup.views.RecoveryKeyUser import io.element.android.features.securebackup.impl.setup.views.RecoveryKeyViewState import io.element.android.features.securebackup.impl.setup.views.aFormattedRecoveryKey -open class SecureBackupSetupStateProvider : PreviewParameterProvider { +open class SecureBackupSetupStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSecureBackupSetupState(setupState = SetupState.Init), diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupView.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupView.kt index 497c64f072..cab1e0995c 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupView.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupView.kt @@ -195,7 +195,7 @@ private fun ColumnScope.Buttons( @PreviewsDayNight @Composable internal fun SecureBackupSetupViewPreview( - @PreviewParameter(SecureBackupSetupStateProvider::class) state: SecureBackupSetupState + @PreviewParameter(SecureBackupSetupStatePreviewParam::class) state: SecureBackupSetupState ) = ElementPreview { SecureBackupSetupView( state = state, diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupViewChangePreview.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupViewChangePreview.kt index 39fa7debe9..0fd7901f55 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupViewChangePreview.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/SecureBackupSetupViewChangePreview.kt @@ -17,7 +17,7 @@ import io.element.android.libraries.designsystem.preview.PreviewsDayNight @PreviewsDayNight @Composable internal fun SecureBackupSetupViewChangePreview( - @PreviewParameter(SecureBackupSetupStateProvider::class) state: SecureBackupSetupState + @PreviewParameter(SecureBackupSetupStatePreviewParam::class) state: SecureBackupSetupState ) = ElementPreview { SecureBackupSetupView( state = state.copy( diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyView.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyView.kt index 8055709f20..61b36d3adf 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyView.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyView.kt @@ -269,7 +269,7 @@ private fun RecoveryKeyFooter(state: RecoveryKeyViewState) { @PreviewsDayNight @Composable internal fun RecoveryKeyViewPreview( - @PreviewParameter(RecoveryKeyViewStateProvider::class) state: RecoveryKeyViewState + @PreviewParameter(RecoveryKeyViewStatePreviewParam::class) state: RecoveryKeyViewState ) = ElementPreview { RecoveryKeyView( state = state, diff --git a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyViewStateProvider.kt b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyViewStatePreviewParam.kt similarity index 95% rename from features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyViewStateProvider.kt rename to features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyViewStatePreviewParam.kt index c1a841aa7b..69a5757e1f 100644 --- a/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyViewStateProvider.kt +++ b/features/securebackup/impl/src/main/kotlin/io/element/android/features/securebackup/impl/setup/views/RecoveryKeyViewStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.features.securebackup.impl.setup.views import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class RecoveryKeyViewStateProvider : PreviewParameterProvider { +open class RecoveryKeyViewStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf(RecoveryKeyUserStory.Setup, RecoveryKeyUserStory.Change, RecoveryKeyUserStory.Enter) .flatMap { diff --git a/features/securebackup/impl/src/main/res/values-ar/translations.xml b/features/securebackup/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..7b3295f49a --- /dev/null +++ b/features/securebackup/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,95 @@ + + + "حذف تخزين المفاتيح" + "تفعيل النسخ الاحتياطي" + "سيتيح لك هذا الاطّلاع على سجل محادثاتك على أي أجهزة جديدة، وهو مطلوب للنسخ الاحتياطي للمحادثات والهوية الرقمية. %1$s." + "تخزين المفاتيح" + "يجب تشغيل تخزين المفاتيح لنسخ دردشاتك احتياطيًا." + "رفع المفاتيح من هذا الجهاز" + "السماح بتخزين المفاتيح" + "تغيير مفتاح الاسترداد" + "يتم نسخ دردشاتك احتياطيًا تلقائيًا بتشفير من طرف إلى طرف. لاستعادة هذه النسخة الاحتياطية والاحتفاظ بهويتك الرقمية إذا فقدت الوصول إلى جميع أجهزتك، ستحتاج إلى مفتاح الاسترداد." + "أدخل مفتاح الاسترداد" + "تخزين المفاتيح لديك غير متزامن حاليًا." + "الحصول على مفتاح الاسترداد" + "يتم نسخ محادثاتك احتياطيًا تلقائيًا باستخدام التشفير التام بين الطرفين. لاستعادة هذه النسخة الاحتياطية والاحتفاظ بهويتك الرقمية عند فقدان الوصول إلى جميع أجهزتك، ستحتاج إلى مفتاح الاسترداد." + "افتح %1$s على جهاز سطح مكتب" + "سجّل الدخول إلى حسابك مرة أخرى" + "عندما يُطلب منك التحقق من جهازك، اختر %1$s" + "“إعادة تعيين الكل”" + "اتّبع التعليمات لإنشاء مفتاح استرداد جديد" + "احفظ مفتاح الاسترداد الجديد في مدير كلمات مرور أو ملاحظة مشفّرة" + "إعادة تعيين تشفير حسابك باستخدام جهاز آخر" + "مفتاح الاسترداد الذي أدخلته غير مطابق" + "إنهاء الإعداد" + "أدخل مفتاح الاسترداد مرة أخرى." + "أكّد مفتاح الاسترداد" + + "الحد الأدنى %1$d أحرف. لا تستخدم كلمة مرور حسابك" + "الحد الأدنى %1$d حرف. لا تستخدم كلمة مرور حسابك" + "الحد الأدنى %1$d حرفان. لا تستخدم كلمة مرور حسابك" + "الحد الأدنى %1$d أحرف. لا تستخدم كلمة مرور حسابك" + "الحد الأدنى %1$d حرفًا. لا تستخدم كلمة مرور حسابك" + "الحد الأدنى %1$d حرف. لا تستخدم كلمة مرور حسابك" + + "القوة" + "قوة عبارة المرور: %1$s" + "متوسط" + "قوي" + "قوي جدًا" + "ضعيف جدًا" + "ضعيف" + "اختر مفتاح استرداد يمكنك تذكّره." + "أدخل مفتاح استرداد" + "جارٍ تحميل متطلبات مفتاح الاسترداد" + "لتغيير مفتاح الاسترداد، انتقل إلى الإعدادات > التشفير > النسخ الاحتياطي" + "يمكنك استخدام مفتاح الاسترداد لتأكيد الأجهزة الجديدة أو استعادة محادثاتك المشفّرة إذا فقدت الوصول إلى جميع أجهزتك." + "تم إعداد نسختك الاحتياطية بالكامل الآن" + "متابعة إعادة التعيين" + "سيتم الاحتفاظ بتفاصيل حسابك وجهات اتصالك وتفضيلاتك وقائمة الدردشات" + "ستفقد أي سجل رسائل مخزّن على الخادم فقط" + "ستحتاج إلى التحقق من جميع أجهزتك وجهات اتصالك الحالية مرة أخرى" + "لا تُعد تعيين هويتك الرقمية إلا إذا لم يكن لديك وصول إلى جهاز آخر تم التحقق منه ولا تملك مفتاح الاسترداد." + "لا يمكنك التأكيد؟ ستحتاج إلى إعادة تعيين هويتك الرقمية." + "حذف" + "ستفقد سجل محادثاتك المشفّر وستحتاج إلى إعادة ضبط هويتك الرقمية إذا أزلت جميع أجهزتك." + "هل أنت متأكد من رغبتك في حذف تخزين المفاتيح؟" + "سيؤدي حذف تخزين المفاتيح إلى إزالة هويتك الرقمية ومفاتيح الرسائل من الخادم وإيقاف ميزات الأمان التالية:" + "لن يتوفر لك سجل الرسائل المشفّرة على الأجهزة الجديدة" + "ستفقد الوصول إلى رسائلك المشفّرة إذا تم تسجيل خروجك من %1$s في كل مكان" + "هل أنت متأكد من رغبتك في إيقاف تخزين المفاتيح وحذفه؟" + "احصل على مفتاح استرداد جديد إذا فقدت مفتاحك الحالي. بعد تغيير مفتاح الاسترداد، لن يعمل مفتاحك القديم بعد ذلك." + "إنشاء مفتاح استرداد جديد" + "لا تشارك هذا مع أي شخص!" + "تم تغيير مفتاح الاسترداد" + "تغيير مفتاح الاسترداد؟" + "إنشاء مفتاح استرداد جديد" + "تأكد من ألا يتمكن أحد من رؤية هذه الشاشة!" + "يُرجى المحاولة مرة أخرى لتأكيد الوصول إلى تخزين المفاتيح." + "مفتاح الاسترداد غير صحيح" + "إذا كان لديك مفتاح أمان أو عبارة أمان، فسيعمل ذلك أيضًا." + "أدخل…" + "هل فقدت مفتاح الاسترداد؟" + "تم تأكيد مفتاح الاسترداد" + "أدخل مفتاح الاسترداد" + "تم نسخ مفتاح الاسترداد" + "جارٍ الإنشاء…" + "حفظ مفتاح الاسترداد" + "دوّن مفتاح الاسترداد هذا في مكان آمن، مثل مدير كلمات مرور أو ملاحظة مشفّرة أو خزنة مادية." + "اضغط لنسخ مفتاح الاسترداد" + "احفظ مفتاح الاسترداد الخاص بك في مكان آمن" + "لن تتمكن من الوصول إلى مفتاح الاسترداد الجديد بعد هذه الخطوة." + "هل حفظت مفتاح الاسترداد الخاص بك؟" + "تخزين المفاتيح لديك محمي بمفتاح استرداد. إذا احتجت إلى مفتاح استرداد جديد بعد الإعداد، يمكنك إعادة إنشائه بتحديد «تغيير مفتاح الاسترداد»." + "إنشاء مفتاح الاسترداد الخاص بك" + "لا تشارك هذا مع أي شخص!" + "تم إعداد الاسترداد بنجاح" + "الحصول على مفتاح الاسترداد" + "نعم، أعد التعيين الآن" + "لا يمكن التراجع عن هذه العملية." + "هل أنت متأكد من أنك تريد إعادة تعيين هويتك الرقمية؟" + "حدث خطأ غير معروف. يُرجى التحقق من صحة كلمة مرور حسابك ثم المحاولة مرة أخرى." + "أدخل…" + "أكّد أنك تريد إعادة تعيين هويتك الرقمية." + "أدخل كلمة مرور حسابك للمتابعة" + diff --git a/features/securebackup/impl/src/main/res/values-de/translations.xml b/features/securebackup/impl/src/main/res/values-de/translations.xml index d53086a6d1..7fbcc1e4b4 100644 --- a/features/securebackup/impl/src/main/res/values-de/translations.xml +++ b/features/securebackup/impl/src/main/res/values-de/translations.xml @@ -8,10 +8,11 @@ "Schlüssel von diesem Gerät hochladen" "Schlüsselspeicherung zulassen" "Wiederherstellungsschlüssel ändern" - "Stelle deine kryptographische Identität und deinen Nachrichtenverlauf mit einem Wiederherstellungsschlüssel wieder her, falls du deine Geräte verloren hast." + "Von deinen Chats wird automatisch ein Ende-zu-Ende-verschlüsseltes Backup erstellt. Wenn du den Zugriff auf alle deine Geräte verlierst, brauchst du deinen Wiederherstellungsschlüssel, um dieses Backup wiederherzustellen und deine digitale Identität zu behalten." "Wiederherstellungsschlüssel eingeben" "Dein Schlüssel ist derzeit nicht synchronisiert." "Wiederherstellungsschlüssel einrichten" + "Von deinen Chats wird automatisch ein Ende-zu-Ende-verschlüsseltes Backup erstellt. Wenn du den Zugriff auf alle deine Geräte verlierst, brauchst du deinen Wiederherstellungsschlüssel, um dieses Backup wiederherzustellen und deine digitale Identität zu behalten." "Öffne " "%1$s" diff --git a/features/securebackup/impl/src/main/res/values-es/translations.xml b/features/securebackup/impl/src/main/res/values-es/translations.xml index 0904559a8f..a99c4bf496 100644 --- a/features/securebackup/impl/src/main/res/values-es/translations.xml +++ b/features/securebackup/impl/src/main/res/values-es/translations.xml @@ -2,16 +2,17 @@ "Borrar almacén de claves" "Activar copia de seguridad" - "Almacena tu identidad criptográfica y las claves de tus mensajes de forma segura en el servidor. Esto te permitirá ver tu historial de mensajes en cualquier dispositivo nuevo. %1$s." + "Esto te permitirá ver tu historial de chat en cualquier dispositivo nuevo y es necesario para la copia de seguridad de tus chats y de tu identidad digital. %1$s." "Almacenamiento de claves" - "El almacenamiento de claves debe estar activado para configurar la recuperación." + "El almacenamiento de claves debe estar activado para hacer copias de seguridad de tus chats." "Subir claves desde este dispositivo" "Permitir almacenamiento de claves" "Cambiar la clave de recuperación" - "Recupera tu identidad criptográfica y tu historial de mensajes con una clave de recuperación si has perdido todos tus dispositivos actuales." + "Tus chats se respaldan automáticamente con cifrado de extremo a extremo. Para restaurar esta copia de seguridad y conservar tu identidad digital si pierdes el acceso a todos tus dispositivos, necesitarás tu clave de recuperación." "Introduce la clave de recuperación" "Tu almacén de claves no está sincronizado actualmente." - "Configurar la recuperación" + "Obtener clave de recuperación" + "Tus chats se respaldan automáticamente con cifrado de extremo a extremo. Para restaurar esta copia de seguridad y conservar tu identidad digital si pierdes el acceso a todos tus dispositivos, necesitarás tu clave de recuperación." "Abre %1$s en un dispositivo de escritorio" "Vuelve a iniciar sesión en tu cuenta" "Cuando se te pida que verifiques tu dispositivo, selecciona %1$s" @@ -19,16 +20,37 @@ "Sigue las instrucciones para crear una nueva clave de recuperación" "Guarda tu nueva clave de recuperación en un administrador de contraseñas o en una nota cifrada" "Restablece el cifrado de tu cuenta usando otro dispositivo" + "La clave de recuperación que introdujiste no coincide" + "Finalizar la configuración" + "Introduce de nuevo tu clave de recuperación." + "Confirma tu clave de recuperación" + + "Mínimo %1$d carácter. No uses la contraseña de tu cuenta" + "Mínimo %1$d caracteres. No uses la contraseña de tu cuenta" + + "Fortaleza" + "Fortaleza de la frase de contraseña: %1$s" + "Moderada" + "Fuerte" + "Muy fuerte" + "Muy débil" + "Débil" + "Elige una clave de recuperación que puedas memorizar." + "Introduce una clave de recuperación" + "Cargando requisitos de la clave de recuperación" + "Para cambiar tu clave de recuperación, ve a Ajustes → Cifrado → Copia de seguridad" + "Puedes usar tu clave de recuperación para confirmar dispositivos nuevos o restaurar tus chats cifrados si pierdes el acceso a todos tus dispositivos." + "Tu copia de seguridad está ahora totalmente configurada" "Continuar con el restablecimiento" "Se conservarán los detalles de tu cuenta, tus contactos, tus preferencias y tu lista de chats" "Perderás cualquier historial de mensajes que solo esté almacenado en el servidor" "Tendrás que verificar de nuevo todos tus dispositivos y contactos existentes" - "Restablece tu identidad solo si no tienes acceso a otro dispositivo en el que hayas iniciado sesión y has perdido tu clave de recuperación." - "¿No puedes confirmar? Tendrás que restablecer tu identidad." - "Desactivar" - "Perderás tus mensajes cifrados si cierras sesión en todos los dispositivos." - "¿Estás seguro de que quieres desactivar la copia de seguridad?" - "Al borrar el almacén de claves, se eliminarán del servidor tu identidad criptográfica y claves de los mensajes, y se desactivarán las siguientes funciones de seguridad:" + "Restablece tu identidad digital solo si ya no tienes acceso a ningún otro dispositivo verificado y no tienes tu clave de recuperación." + "¿No puedes confirmar? Tendrás que restablecer tu identidad digital." + "Eliminar" + "Perderás tu historial de chats cifrados y tendrás que restablecer tu identidad digital si eliminas todos tus dispositivos." + "¿Estás seguro de que quieres eliminar el almacén de claves?" + "Al borrar el almacén de claves, se eliminarán del servidor tu identidad digital y claves de los mensajes, y se desactivarán las siguientes funciones de seguridad:" "No tendrás un historial de mensajes cifrados en nuevos dispositivos" "Perderás el acceso a tus mensajes cifrados si cierras sesión en %1$s en todas partes" "¿Estás seguro de que quieres desactivar el almacenamiento de claves y borrarlo?" @@ -58,12 +80,12 @@ "Generar tu clave de recuperación" "¡No la compartas con nadie!" "Configuración de recuperación terminada" - "Configurar la recuperación" + "Obtener clave de recuperación" "Sí, restablecer ahora" "Este proceso es irreversible." - "¿Estás seguro de que quieres restablecer tu identidad?" + "¿Estás seguro de que quieres restablecer tu identidad digital?" "Se ha producido un error desconocido. Comprueba que la contraseña de tu cuenta sea correcta y vuelve a intentarlo." "Introducir…" - "Confirma que quieres restablecer tu identidad." + "Confirma que quieres restablecer tu identidad digital." "Introduce la contraseña de tu cuenta para continuar" diff --git a/features/securebackup/impl/src/main/res/values-fa/translations.xml b/features/securebackup/impl/src/main/res/values-fa/translations.xml index bd7a43ffba..9457bcb2af 100644 --- a/features/securebackup/impl/src/main/res/values-fa/translations.xml +++ b/features/securebackup/impl/src/main/res/values-fa/translations.xml @@ -4,12 +4,15 @@ "روشن کردن پشتیبان" "ذخیرهٔ کلیدهای پیام‌ها و هویت رمزنگاریتان به صورت امن روی کارساز. این کار می‌گذارد تاریخچهٔ پیام‌هایتان را روی هر افزارهٔ جدیدی ببینید. %1$s." "ذخیره‌ساز کلید" + "برای پشتیبان‌گیری از چت‌هایتان، باید گزینه‌ی ذخیره‌سازی کلید (Key Storage) فعال باشد." "بارگذاری کلیدها از ین افزاره" "اجازهٔ ذخیرهٔ کلید" "تغییر کلید بازیابی" + "چت‌های شما به طور خودکار با رمزگذاری سراسری پشتیبان‌گیری می‌شوند. برای بازیابی این پشتیبان‌گیری و حفظ هویت دیجیتال خود در زمانی که دسترسی به تمام دستگاه‌هایتان را از دست می‌دهید، به کلید بازیابی خود نیاز خواهید داشت." "ورود کلید بازیابی" "ذخیره‌ساز کلیدتان از هم‌گام بودن در آمده." "دریافت کلید بازیابی" + "چت‌های شما به طور خودکار با رمزگذاری سراسری پشتیبان‌گیری می‌شوند. برای بازیابی این پشتیبان‌گیری و حفظ هویت دیجیتال خود در زمانی که دسترسی به تمام دستگاه‌هایتان را از دست می‌دهید، به کلید بازیابی خود نیاز خواهید داشت." "گشودن %1$s در افزارهٔ میزکار" "ورود دوباره به حسابتان" "گزینش %1$s هنگام درخواست تأیید افزاره‌تان" @@ -17,12 +20,33 @@ "پیروی از دستورالعمل‌ها برای ایجاد کلید بازیابی جدید" "ذخیرهٔ کلید بازیابی جدیدتان در مدیر گذرواژه یا یادداشت رمز شده" "بازنشانی رمزنگاری برای حسابتان با استفاده از افزاره‌ای دیگر" + "کلید بازیابی که وارد کرده‌اید مطابقت ندارد" + "پایان تنظیمات" + "دوباره کلید بازیابی خود را وارد کنید." + "کلید بازیابی خود را تأیید کنید" + + "حداقل کاراکتر %1$d. از رمز عبور حساب کاربری خود استفاده نکنید." + "حداقل کاراکترهای %1$d. از رمز عبور حساب کاربری خود استفاده نکنید." + + "قدرت" + "قدرت رمز عبور: %1$s" + "متوسط" + "قوی" + "خیلی قوی" + "خیلی ضعیف" + "ضعیف" + "یک کلید بازیابی انتخاب کنید که بتوانید آن را به خاطر بسپارید." + "یک کلید بازیابی وارد کنید" + "بارگذاری الزامات کلید بازیابی" + "برای تغییر کلید بازیابی خود، به تنظیمات → رمزگذاری → پشتیبان‌گیری بروید." + "اگر دسترسی به همه دستگاه‌هایتان را از دست بدهید، می‌توانید از کلید بازیابی خود برای تأیید دستگاه‌های جدید یا بازیابی چت‌های رمزگذاری‌شده‌تان استفاده کنید." + "پشتیبان‌گیری شما اکنون کاملاً راه‌اندازی شده است" "ادامهٔ بازنشانی" "جزییات حساب، آشنایان، ترجیحات و سیاههٔ گپ‌هایتان حفظ خواهند شد" "تاریخچهٔ گپ‌هایتان را از دست خواهید داد" "لازم است دوباره همهٔ آشنایان و افزاره‌های موجودتان را تأیید کنید" - "فقط اگر به افزاره‌ای وارد شده از پیش دسترسی ندارید و کلید بازیابیتان را گم کرده‌اید بازنشانی کنید." - "نمی‌توانید تأیید کنید؟ لازم است هویتتان را بازنشانی کنید." + "فقط در صورتی که به دستگاه تأیید شده دیگری دسترسی ندارید و کلید بازیابی خود را ندارید، هویت دیجیتال خود را بازنشانی کنید." + "نمی‌توانید تأیید کنید؟ باید هویت دیجیتال خود را مجدداً تنظیم کنید." "حذف" "اگر از تمام دستگاه‌هایتان خارج شوید، تاریخچه چت رمزگذاری‌شده خود را از دست خواهید داد و باید هویت دیجیتال خود را مجدداً تنظیم کنید." "آیا مطمئن هستید که می‌خواهید کلید ذخیره‌سازی را حذف کنید؟" @@ -59,5 +83,9 @@ "دریافت کلید بازیابی" "بله. اکنون بازنشانی شود" "این فرایند بازگشت‌ناپذیر است." + "آیا مطمئن هستید که می‌خواهید هویت دیجیتال خود را بازنشانی کنید؟" + "خطای ناشناخته‌ای رخ داده است. لطفاً بررسی کنید که رمز عبور حساب شما صحیح است و دوباره امتحان کنید." "ورود…" + "تأیید کنید که می‌خواهید هویت دیجیتال خود را مجدداً تنظیم کنید." + "برای ادامه، رمز عبور حساب خود را وارد کنید" diff --git a/features/securebackup/impl/src/main/res/values-pl/translations.xml b/features/securebackup/impl/src/main/res/values-pl/translations.xml index fb1da3ca04..491d30d8c1 100644 --- a/features/securebackup/impl/src/main/res/values-pl/translations.xml +++ b/features/securebackup/impl/src/main/res/values-pl/translations.xml @@ -8,11 +8,11 @@ "Prześlij klucze z tego urządzenia" "Zezwól na magazynowanie kluczy" "Zmień klucz przywracania" - "Twoje czaty są automatycznie archiwizowane za pomocą szyfrowania end-to-end. Aby przywrócić tę kopię zapasową i swoją tożsamość cyfrową, wymagany będzie klucz przywracania." + "Twoje czaty są automatycznie archiwizowane za pomocą szyfrowania end-to-end. Aby przywrócić kopię zapasową i swoją tożsamość cyfrową, wymagany będzie klucz przywracania." "Wprowadź klucz przywracania" "Magazyn kluczy nie jest zsynchronizowany." "Uzyskaj klucz przywracania" - "Twoje czaty są automatycznie archiwizowane za pomocą szyfrowania end-to-end. Aby przywrócić tę kopię zapasową i swoją tożsamość cyfrową, wymagany będzie klucz przywracania." + "Twoje czaty są automatycznie archiwizowane za pomocą szyfrowania end-to-end. Aby przywrócić kopię zapasową i swoją tożsamość cyfrową, wymagany będzie klucz przywracania." "Otwórz %1$s na urządzeniu stacjonarnym" "Zaloguj się ponownie na swoje konto" "Gdy pojawi się prośba o weryfikację urządzenia, wybierz %1$s" diff --git a/features/securebackup/impl/src/main/res/values-ro/translations.xml b/features/securebackup/impl/src/main/res/values-ro/translations.xml index 2351a54923..c9060945c7 100644 --- a/features/securebackup/impl/src/main/res/values-ro/translations.xml +++ b/features/securebackup/impl/src/main/res/values-ro/translations.xml @@ -8,11 +8,11 @@ "Încărcați cheile de pe acest dispozitiv" "Permiteți stocarea cheilor" "Schimbați cheia de recuperare" - "Mesajele dumneavoastră sunt copiate automat cu criptare end-to-end. Pentru a restaura această copie de rezervă și a vă păstra identitatea digitală atunci când pierdeți accesul la toate dispozitivele dumneavoastră, veți avea nevoie de cheia de recuperare." + "Mesajele dumneavoastră sunt copiate automat cu criptare end-to-end. Pentru a restaura aceast backup și a vă păstra identitatea digitală atunci când pierdeți accesul la toate dispozitivele dumneavoastră, veți avea nevoie de cheia de recuperare." "Introduceți cheia de recuperare" "Backup-ul pentru chat nu este sincronizat în prezent." "Obțineți cheia de recuperare" - "Chaturile dumneavoastră sunt salvate automat cu criptare end-to-end. Pentru a restaura această copie de rezervă și a vă păstra identitatea digitală atunci când pierdeți accesul la toate dispozitivele dumneavoastră, veți avea nevoie de cheia de recuperare." + "Chaturile dumneavoastră sunt salvate automat cu criptare end-to-end. Pentru a restaura această backup și a vă păstra identitatea digitală atunci când pierdeți accesul la toate dispozitivele dumneavoastră, veți avea nevoie de cheia de recuperare." "Deschideți %1$s pe un dispozitiv desktop" "Conectați-vă din nou la contul dumneavoastră" "Când vi se cere să vă verificați dispozitivul, selectați%1$s" @@ -20,6 +20,28 @@ "Urmați instrucțiunile pentru a crea o nouă cheie de recuperare" "Salvați noua cheie de recuperare într-un manager de parole sau o notă criptată" "Resetați criptarea contului dumneavoastră folosind un alt dispozitiv" + "Cheia de recuperare introdusă nu se potrivește" + "Finalizați configurarea" + "Introduceți din nou cheia de recuperare." + "Confirmați cheia de recuperare" + + "Minim %1$d caracter. Nu folosiți parola contului dvs." + "Minim %1$d caractere. Nu folosiți parola contului dvs." + "Minim %1$d caractere. Nu folosiți parola contului dvs." + + "Rezistenţă" + "Rezistența parolei: %1$s" + "Moderată" + "Puternică" + "Foarte puternică" + "Foarte slabă" + "Slabă" + "Alegeți o cheie de recuperare pe care o puteți memora." + "Introduceți o cheie de recuperare" + "Se încarcă cerințele cheii de recuperare" + "Pentru a schimba cheia de recuperare, accesați Setări → Criptare → Backup" + "Puteți folosi cheia de recuperare pentru a confirma dispozitive noi sau pentru a restaura chat-urile criptate dacă pierdeți accesul la toate dispozitivele." + "Backup-ul dumneavoastră este acum complet configurat" "Continuați resetarea" "Detaliile contului, contactele, preferințele și lista de chat vor fi păstrate" "Veți pierde mesajele anterioare care au fost stocate doar pe server" diff --git a/features/securebackup/impl/src/main/res/values-zh-rTW/translations.xml b/features/securebackup/impl/src/main/res/values-zh-rTW/translations.xml index 9b791eb938..daf8a73964 100644 --- a/features/securebackup/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/securebackup/impl/src/main/res/values-zh-rTW/translations.xml @@ -20,6 +20,26 @@ "按照說明建立新復原金鑰" "將您的新復原金鑰儲存在密碼管理程式或加密筆記中" "使用其他裝置重設您帳號的加密" + "您輸入的復原金鑰不符合" + "完成設定" + "請再次輸入您的復原金鑰。" + "確認您的復原金鑰" + + "最少 %1$d 個字元。請勿使用您的帳號密碼。" + + "強度" + "密碼短語強度:%1$s" + "中等" + "強" + "非常強" + "非常弱" + "弱" + "請輸入您可以記住的復原金鑰。" + "輸入復原金鑰" + "正在載入復原金鑰需求" + "若要變更復原金鑰,請前往「設定」→「加密」→「備份」" + "若您無法存取您所有的裝置,可以使用復原金鑰來確認新裝置或還原加密聊天紀錄。" + "您的備份已設定完成" "繼續重設" "您的帳號詳細資訊、聯絡人、偏好設定與聊天清單都會保留" "您將會遺失僅儲存在伺服器上的任何訊息歷史紀錄" diff --git a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressStateProvider.kt b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressStatePreviewParam.kt similarity index 94% rename from features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressStateProvider.kt rename to features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressStatePreviewParam.kt index 7b82175bb7..096e9c50c5 100644 --- a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressStateProvider.kt +++ b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.ui.room.address.RoomAddressValidity -open class EditRoomAddressStateProvider : PreviewParameterProvider { +open class EditRoomAddressStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anEditRoomAddressState(), diff --git a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressView.kt b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressView.kt index da18b963fa..c1156df209 100644 --- a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressView.kt +++ b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/editroomaddress/EditRoomAddressView.kt @@ -112,7 +112,7 @@ private fun EditRoomAddressTopBar( @PreviewsDayNight @Composable internal fun EditRoomAddressViewPreview( - @PreviewParameter(EditRoomAddressStateProvider::class) state: EditRoomAddressState + @PreviewParameter(EditRoomAddressStatePreviewParam::class) state: EditRoomAddressState ) = ElementPreview { EditRoomAddressView( state = state, diff --git a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesStateProvider.kt b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesStatePreviewParam.kt similarity index 94% rename from features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesStateProvider.kt rename to features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesStatePreviewParam.kt index d2fec941ff..d5d1986b83 100644 --- a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesStateProvider.kt +++ b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesStatePreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.previewutils.room.aSpaceRoom import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableSet -open class ManageAuthorizedSpacesStateProvider : PreviewParameterProvider { +open class ManageAuthorizedSpacesStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aManageAuthorizedSpacesState(), diff --git a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesView.kt b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesView.kt index 514c38a3fd..0bb6bc49e6 100644 --- a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesView.kt +++ b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/manageauthorizedspaces/ManageAuthorizedSpacesView.kt @@ -191,7 +191,7 @@ private fun ManageAuthorizedSpacesTopBar( @PreviewsDayNight @Composable internal fun ManageAuthorizedSpacesViewPreview( - @PreviewParameter(ManageAuthorizedSpacesStateProvider::class) state: ManageAuthorizedSpacesState + @PreviewParameter(ManageAuthorizedSpacesStatePreviewParam::class) state: ManageAuthorizedSpacesState ) = ElementPreview { ManageAuthorizedSpacesView(state = state) } diff --git a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyStateProvider.kt b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyStatePreviewParam.kt similarity index 98% rename from features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyStateProvider.kt rename to features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyStatePreviewParam.kt index 998d61b564..102adb4015 100644 --- a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyStateProvider.kt +++ b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.matrix.api.spaces.SpaceRoom import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableSet -open class SecurityAndPrivacyStateProvider : PreviewParameterProvider { +open class SecurityAndPrivacyStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = commonSecurityAndPrivacyStates(isSpace = false) + commonSecurityAndPrivacyStates(isSpace = true) + diff --git a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyView.kt b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyView.kt index 43feb99611..e2cc5522a6 100644 --- a/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyView.kt +++ b/features/securityandprivacy/impl/src/main/kotlin/io/element/android/features/securityandprivacy/impl/root/SecurityAndPrivacyView.kt @@ -469,12 +469,12 @@ private fun HistoryVisibilityItem( @PreviewWithLargeHeight @Composable -internal fun SecurityAndPrivacyViewLightPreview(@PreviewParameter(SecurityAndPrivacyStateProvider::class) state: SecurityAndPrivacyState) = +internal fun SecurityAndPrivacyViewLightPreview(@PreviewParameter(SecurityAndPrivacyStatePreviewParam::class) state: SecurityAndPrivacyState) = ElementPreviewLight { ContentToPreview(state) } @PreviewWithLargeHeight @Composable -internal fun SecurityAndPrivacyViewDarkPreview(@PreviewParameter(SecurityAndPrivacyStateProvider::class) state: SecurityAndPrivacyState) = +internal fun SecurityAndPrivacyViewDarkPreview(@PreviewParameter(SecurityAndPrivacyStatePreviewParam::class) state: SecurityAndPrivacyState) = ElementPreviewDark { ContentToPreview(state) } @ExcludeFromCoverage diff --git a/features/securityandprivacy/impl/src/main/res/values-ar/translations.xml b/features/securityandprivacy/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..d6006ec8f3 --- /dev/null +++ b/features/securityandprivacy/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,50 @@ + + + "تحتاج إلى عنوان حتى تظهر الغرفة في الدليل العام." + "تعديل العنوان" + "المساحات التي يمكن لأعضائها الانضمام إلى الغرفة دون دعوة." + "إدارة المساحات" + "(مساحة غير معروفة)" + "مساحات أخرى لست عضوًا فيها" + "مساحاتك" + "إضافة عنوان" + "يمكن لأي شخص في المساحات المصرّح بها الانضمام، لكن يجب على الآخرين طلب الوصول." + "يجب على الجميع طلب الوصول." + "طلب الانضمام" + "يمكن لأي شخص في %1$s الانضمام، لكن يجب على الآخرين طلب الوصول." + "نعم، فعّل التشفير" + "بعد تفعيله، لا يمكن تعطيل التشفير في الغرفة. لن يكون سجل الرسائل مرئيًا لأعضاء الغرفة إلا منذ وقت دعوتهم أو منذ انضمامهم إلى الغرفة. +لن يتمكن أي شخص غير أعضاء الغرفة من قراءة الرسائل. قد يمنع ذلك البوتات والجسور من العمل بشكل صحيح. +لا نوصي بتفعيل التشفير للغرف التي يمكن لأي شخص العثور عليها والانضمام إليها." + "تفعيل التشفير؟" + "بعد تفعيله، لا يمكن تعطيل التشفير." + "التشفير" + "تفعيل التشفير من طرف إلى طرف" + "يمكن لأي شخص الانضمام." + "أي شخص" + "اختر المساحات التي يمكن لأعضائها الانضمام إلى هذه الغرفة دون دعوة. %1$s" + "إدارة المساحات" + "يمكن للأشخاص المدعوين فقط الانضمام." + "بالدعوة فقط" + "الوصول" + "يمكن لأي شخص في المساحات المصرّح بها الانضمام." + "يمكن لأي شخص في %1$s الانضمام." + "أعضاء المساحة" + "المساحات غير مدعومة حاليًا" + "تحتاج إلى عنوان حتى تظهر الغرفة في الدليل العام." + "العنوان" + "السماح بالعثور على هذه الغرفة عند البحث في دليل الغرف العام على %1$s" + "السماح بالعثور عليها عند البحث في الدليل العام." + "مرئية في الدليل العام" + "أي شخص (السجل عام)" + "لن تؤثر التغييرات على الرسائل السابقة، بل على الرسائل الجديدة فقط. %1$s" + "من يمكنه قراءة السجل" + "الأعضاء منذ دعوتهم" + "الأعضاء (السجل الكامل)" + "عناوين الغرف وسيلة للعثور على الغرف والوصول إليها. كما يضمن ذلك إمكانية مشاركة غرفتك بسهولة مع الآخرين. +يمكنك اختيار نشر غرفتك في دليل الغرف العام على خادمك المنزلي." + "نشر الغرفة" + "العناوين وسيلة للعثور على الغرف والمساحات والوصول إليها. كما يضمن ذلك إمكانية مشاركتها بسهولة مع الآخرين." + "الظهور" + "الأمان والخصوصية" + diff --git a/features/securityandprivacy/impl/src/main/res/values-es/translations.xml b/features/securityandprivacy/impl/src/main/res/values-es/translations.xml index f7e7812914..49547a939e 100644 --- a/features/securityandprivacy/impl/src/main/res/values-es/translations.xml +++ b/features/securityandprivacy/impl/src/main/res/values-es/translations.xml @@ -2,9 +2,16 @@ "Necesitarás una dirección de sala para que sea visible en el directorio." "Editar dirección" + "Espacios donde los miembros pueden unirse a la sala sin invitación." + "Gestionar espacios" + "(Espacio desconocido)" + "Otros espacios de los que no eres miembro" + "Tus espacios" "Agregar dirección" + "Cualquiera en espacios autorizados puede unirse, pero el resto debe solicitar acceso." "Todos deben solicitar acceso." "Solicitar unirse" + "Cualquiera en %1$s puede unirse, pero el resto debe solicitar acceso." "Sí, activar cifrado" "Una vez activado, el cifrado de una sala no se puede desactivar. El historial de mensajes solo será visible para los miembros de la sala desde que fueron invitados o desde que se unieron a la sala. Nadie más que los miembros de la sala podrán leer los mensajes. Esto puede impedir que los bots y los puentes funcionen correctamente. @@ -15,21 +22,29 @@ No recomendamos habilitar el cifrado para las salas que cualquiera pueda encontr "Activar el cifrado de extremo a extremo" "Cualquiera puede unirse" "Cualquiera" + "Elige qué miembros de los espacios pueden unirse a esta sala sin una invitación. %1$s" + "Gestionar espacios" "Solo las personas invitadas pueden unirse." "Solo por invitación" "Acceso" + "Cualquiera en espacios autorizados puede unirse." + "Cualquiera en %1$s puede unirse." + "Miembros del espacio" "No se admiten los espacios por el momento." "Necesitarás una dirección de sala para que sea visible en el directorio." "Dirección" "Permite encontrar esta sala buscando en el directorio de salas públicas de %1$s" + "Permitir que sea encontrada al buscar en el directorio público." "Visible en el directorio público" "Cualquiera (el historial es público)" + "Los cambios no afectarán a los mensajes anteriores, solo a los nuevos. %1$s" "Quién puede leer el historial" - "Solo participantes desde que fueron invitados" - "Miembros (historia completa)" + "Miembros desde su invitación" + "Miembros (historial completo)" "Las direcciones de sala son formas de buscar salas y acceder a ellas. Esto también garantiza que puedas compartir fácilmente tu sala con otras personas. Puedes optar por publicar tu sala en el directorio de salas públicas de tu servidor base." "Publicación de la sala" + "Las direcciones son una forma de encontrar y acceder a salas y espacios. También garantizan que puedas compartirlos fácilmente con otras personas." "Visibilidad" "Seguridad y privacidad" diff --git a/features/securityandprivacy/impl/src/main/res/values-fa/translations.xml b/features/securityandprivacy/impl/src/main/res/values-fa/translations.xml index 6fc141b487..d4a92973cb 100644 --- a/features/securityandprivacy/impl/src/main/res/values-fa/translations.xml +++ b/features/securityandprivacy/impl/src/main/res/values-fa/translations.xml @@ -1,21 +1,50 @@ - "نشانی اتاق" - "افزودن نشانی اتاق" + "برای اینکه بتوانید آن را در فهرست عمومی مشاهده کنید، به یک آدرس نیاز دارید." + "ویرایش آدرس" + "فضاهایی که اعضا می‌توانند بدون دعوت‌نامه به اتاق بپیوندند." + "مدیریت فضاها" + "(فضای ناشناخته)" + "فضاهای دیگری که عضو آنها نیستید" + "فضاهای شما" + "اضافه کردن آدرس" + "هر کسی که در فضاهای مجاز باشد می‌تواند عضو شود، اما بقیه باید درخواست دسترسی بدهند." + "همه باید درخواست دسترسی بدهند." "درخواست دعوت" + "هر کسی در %1$s می‌تواند عضو شود، اما بقیه باید درخواست دسترسی بدهند." "بله. به کار انداختن رمزنگاری" + "پس از فعال کردن، رمزگذاری برای یک اتاق قابل غیرفعال کردن نیست، تاریخچه پیام فقط برای اعضای اتاق از زمان دعوت یا از زمان پیوستن به اتاق قابل مشاهده خواهد بود. +هیچ کس غیر از اعضای اتاق قادر به خواندن پیام‌ها نخواهد بود. این ممکن است مانع از عملکرد صحیح ربات‌ها و پل‌ها شود. +ما فعال کردن رمزگذاری را برای اتاق‌هایی که هر کسی می‌تواند آنها را پیدا کند و به آنها بپیوندد، توصیه نمی‌کنیم." "رمزگذاری فعال شود؟" "پس از به کار افتادن، رمزنگاری قابل از کار انداختن نیست." "رمزنگاری" - "هرکسی می‌تواند یافته و بپیوندد" - "هرکسی" - "افراد فقط در صورت دعوت می‌توانند بپیوندند" - "فقط دعوتی" - "دسترسی اتاق" + "فعال کردن رمزنگاری سراسری" + "هر کسی می‌تواند عضو شود." + "هر کس" + "انتخاب کنید که اعضای کدام فضاها می‌توانند بدون دعوتنامه به این اتاق بپیوندند. %1$s" + "مدیریت فضاها" + "فقط افراد دعوت شده می‌توانند عضو شوند." + "فقط دعوت" + "دسترسی" + "هر کسی که در فضاهای مجاز باشد می‌تواند عضو شود." + "هر کسی که در %1$s باشد می‌تواند عضو شود." + "اعضای فضا" "در حال حاضر فضاها پشتیبانی نمی‌شوند" - "نشانی اتاق" + "برای اینکه بتوانید آن را در فهرست عمومی مشاهده کنید، به یک آدرس نیاز دارید." + "آدرس" + "با جستجو در فهرست اتاق‌های عمومی %1$s، امکان یافتن این اتاق را فراهم کنید." + "با جستجو در فهرست عمومی، می‌توان آن را پیدا کرد." + "قابل مشاهده در فهرست عمومی" "هرکسی" + "تغییرات روی پیام‌های قبلی تأثیری نخواهند داشت، فقط روی پیام‌های جدید اعمال می‌شوند. %1$s" + "چه کسی می‌تواند تاریخ بخواند؟" + "اعضا از زمان دعوت" + "اعضا (تاریخچه کامل)" + "آدرس‌های اتاق، راه‌هایی برای پیدا کردن و دسترسی به اتاق‌ها هستند. این همچنین تضمین می‌کند که می‌توانید به راحتی اتاق خود را با دیگران به اشتراک بگذارید. +شما می‌توانید اتاق خود را در دایرکتوری عمومی اتاق سرور خانگی خود منتشر کنید." "انتشار اتاق" - "نمایانی اتاق" + "آدرس‌ها راهی برای پیدا کردن و دسترسی به اتاق‌ها و فضاها هستند. این همچنین تضمین می‌کند که می‌توانید به راحتی آنها را با دیگران به اشتراک بگذارید." + "قابلیت مشاهده" "امنیت و محرمانگی" diff --git a/features/share/api/src/main/kotlin/io/element/android/features/share/api/OnSharedData.kt b/features/share/api/src/main/kotlin/io/element/android/features/share/api/OnSharedData.kt index d7985e8b06..f635cc0cce 100644 --- a/features/share/api/src/main/kotlin/io/element/android/features/share/api/OnSharedData.kt +++ b/features/share/api/src/main/kotlin/io/element/android/features/share/api/OnSharedData.kt @@ -11,5 +11,8 @@ package io.element.android.features.share.api * Post-processing to be done once a [ShareIntentData] has been consumed. */ fun interface OnSharedData { + /** + * @param data the shared content that has just been handled, so any temporary copy of it can be released. + */ operator fun invoke(data: ShareIntentData) } diff --git a/features/share/api/src/main/kotlin/io/element/android/features/share/api/ShareIntentHandler.kt b/features/share/api/src/main/kotlin/io/element/android/features/share/api/ShareIntentHandler.kt index d689c57398..d85ae9792a 100644 --- a/features/share/api/src/main/kotlin/io/element/android/features/share/api/ShareIntentHandler.kt +++ b/features/share/api/src/main/kotlin/io/element/android/features/share/api/ShareIntentHandler.kt @@ -9,10 +9,14 @@ package io.element.android.features.share.api import android.content.Intent +/** + * Recognises the intents another app uses to share content into this one, and resolves what was shared. + */ interface ShareIntentHandler { /** * This methods aims to handle incoming share intents and parse its data. * + * @param intent the intent the app was started with. * @return the [ShareIntentData] if it could be resolved, or null. */ fun handleIncomingShareIntent( diff --git a/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/DefaultShareIntentHandler.kt b/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/DefaultShareIntentHandler.kt index cfa06c3a97..2ae31fb00c 100644 --- a/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/DefaultShareIntentHandler.kt +++ b/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/DefaultShareIntentHandler.kt @@ -42,7 +42,8 @@ class DefaultShareIntentHandler( val uris = getIncomingUris(intent, type) return when { uris.isEmpty() && type == MimeTypes.PlainText -> handlePlainText(intent) - type.isMimeTypeImage() || + uris.isNotEmpty() || + type.isMimeTypeImage() || type.isMimeTypeVideo() || type.isMimeTypeAudio() || type.isMimeTypeApplication() || diff --git a/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareStateProvider.kt b/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareStatePreviewParam.kt similarity index 93% rename from features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareStateProvider.kt rename to features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareStatePreviewParam.kt index 88f9d42f40..97135acb71 100644 --- a/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareStateProvider.kt +++ b/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.core.RoomId -open class ShareStateProvider : PreviewParameterProvider { +open class ShareStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aShareState(), diff --git a/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareView.kt b/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareView.kt index ec5897bcad..5e5130965f 100644 --- a/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareView.kt +++ b/features/share/impl/src/main/kotlin/io/element/android/features/share/impl/ShareView.kt @@ -33,7 +33,7 @@ fun ShareView( @PreviewsDayNight @Composable -internal fun ShareViewPreview(@PreviewParameter(ShareStateProvider::class) state: ShareState) = ElementPreview { +internal fun ShareViewPreview(@PreviewParameter(ShareStatePreviewParam::class) state: ShareState) = ElementPreview { ShareView( state = state, onShareSuccess = {} diff --git a/features/share/impl/src/test/kotlin/io/element/android/features/share/impl/DefaultShareIntentHandlerTest.kt b/features/share/impl/src/test/kotlin/io/element/android/features/share/impl/DefaultShareIntentHandlerTest.kt new file mode 100644 index 0000000000..d81bbe053d --- /dev/null +++ b/features/share/impl/src/test/kotlin/io/element/android/features/share/impl/DefaultShareIntentHandlerTest.kt @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.share.impl + +import android.content.ComponentName +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.IntentFilter +import android.database.Cursor +import android.net.Uri +import androidx.core.net.toUri +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import io.element.android.features.share.api.ShareIntentData +import io.element.android.features.share.api.UriToShare +import io.element.android.libraries.core.mimetype.MimeTypes +import io.element.android.tests.testutils.robolectric.RobolectricTest +import org.junit.Test +import org.robolectric.Robolectric +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf + +class DefaultShareIntentHandlerTest : RobolectricTest() { + @Test + fun `an image is shared as an uri`() { + val uri = "content://sender/image.jpg".toUri() + val result = createDefaultShareIntentHandler().handleIncomingShareIntent( + aSendIntent(type = "image/jpeg", uri = uri) + ) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = listOf(UriToShare(uri = uri, mimeType = "image/jpeg")), + ) + ) + } + + @Test + fun `an uri with an unlisted mime type is shared`() { + val uri = "content://sender/logs.zip".toUri() + val result = createDefaultShareIntentHandler().handleIncomingShareIntent( + aSendIntent(type = "message/rfc822", uri = uri) + ) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = listOf(UriToShare(uri = uri, mimeType = "message/rfc822")), + ) + ) + } + + @Test + fun `an uri with an unlisted mime type keeps the text as a caption`() { + val uri = "content://sender/logs.zip".toUri() + val result = createDefaultShareIntentHandler().handleIncomingShareIntent( + aSendIntent(type = "message/rfc822", uri = uri).apply { + putExtra(Intent.EXTRA_TEXT, "a caption") + } + ) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = "a caption", + uris = listOf(UriToShare(uri = uri, mimeType = "message/rfc822")), + ) + ) + } + + @Test + fun `several uris with an unlisted mime type are shared`() { + val firstUri = "content://sender/first.zip".toUri() + val secondUri = "content://sender/second.zip".toUri() + val intent = Intent(Intent.ACTION_SEND_MULTIPLE).apply { + type = "message/rfc822" + putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayListOf(firstUri, secondUri)) + } + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = listOf( + UriToShare(uri = firstUri, mimeType = "message/rfc822"), + UriToShare(uri = secondUri, mimeType = "message/rfc822"), + ), + ) + ) + } + + @Test + fun `a plain text is shared as a text`() { + val intent = Intent(Intent.ACTION_SEND).apply { + type = "text/plain" + putExtra(Intent.EXTRA_TEXT, "a text") + } + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(result).isEqualTo(ShareIntentData.PlainText("a text")) + } + + @Test + fun `an intent with neither uri nor text is not handled`() { + val intent = Intent(Intent.ACTION_SEND).apply { + type = "message/rfc822" + } + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(result).isNull() + } + + @Test + fun `an intent without mime type is not handled`() { + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(Intent(Intent.ACTION_SEND)) + assertThat(result).isNull() + } + + @Test + fun `an intent with a listed mime type and no uri is handled`() { + listOf( + MimeTypes.Jpeg, + MimeTypes.Mp4, + MimeTypes.Mp3, + MimeTypes.Pdf, + "file/binary", + "text/html", + MimeTypes.Any, + ).forEach { type -> + val result = createDefaultShareIntentHandler().handleIncomingShareIntent( + Intent(Intent.ACTION_SEND).apply { this.type = type } + ) + assertWithMessage("$type was not properly handled").that(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = emptyList(), + ) + ) + } + } + + @Test + fun `a send multiple intent without uri is handled`() { + val intent = Intent(Intent.ACTION_SEND_MULTIPLE).apply { + type = MimeTypes.Jpeg + } + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = emptyList(), + ) + ) + } + + @Test + fun `an uri is ignored when the intent is neither a send nor a send multiple`() { + val intent = Intent(Intent.ACTION_VIEW).apply { + type = MimeTypes.Jpeg + putExtra(Intent.EXTRA_STREAM, "content://sender/image.jpg".toUri()) + } + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = emptyList(), + ) + ) + } + + @Test + fun `an empty text is not kept as a caption`() { + val uri = "content://sender/logs.zip".toUri() + val result = createDefaultShareIntentHandler().handleIncomingShareIntent( + aSendIntent(type = "message/rfc822", uri = uri).apply { + putExtra(Intent.EXTRA_TEXT, "") + } + ) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = listOf(UriToShare(uri = uri, mimeType = "message/rfc822")), + ) + ) + } + + @Test + fun `a plain text intent without text is not handled`() { + val intent = Intent(Intent.ACTION_SEND).apply { + type = MimeTypes.PlainText + } + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(result).isNull() + } + + @Test + fun `a plain text intent with an empty text is not handled`() { + val intent = Intent(Intent.ACTION_SEND).apply { + type = MimeTypes.PlainText + putExtra(Intent.EXTRA_TEXT, "") + } + val result = createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(result).isNull() + } + + @Test + fun `the mime type of the uri overrides the one of the intent`() { + Robolectric.setupContentProvider(ZipContentProvider::class.java, "sender") + val uri = "content://sender/logs.zip".toUri() + val result = createDefaultShareIntentHandler().handleIncomingShareIntent( + aSendIntent(type = MimeTypes.Any, uri = uri) + ) + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = listOf(UriToShare(uri = uri, mimeType = "application/zip")), + ) + ) + } + + @Test + fun `the intent is made explicit for the application which will read the uri`() { + val intent = aSendIntent(type = "message/rfc822", uri = "content://sender/logs.zip".toUri()) + givenAnApplicationHandling(intent) + createDefaultShareIntentHandler().handleIncomingShareIntent(intent) + assertThat(intent.action).isNull() + assertThat(intent.component).isEqualTo(ComponentName(A_PACKAGE_NAME, AN_ACTIVITY_NAME)) + } + + @Test + fun `the intent stays implicit when the uri permission cannot be granted`() { + val uri = "content://sender/logs.zip".toUri() + val intent = aSendIntent(type = "message/rfc822", uri = uri) + givenAnApplicationHandling(intent) + val result = DefaultShareIntentHandler( + context = FailingGrantUriPermissionContext(RuntimeEnvironment.getApplication()), + ).handleIncomingShareIntent(intent) + assertThat(intent.action).isEqualTo(Intent.ACTION_SEND) + assertThat(intent.component).isNull() + assertThat(result).isEqualTo( + ShareIntentData.Uris( + text = null, + uris = listOf(UriToShare(uri = uri, mimeType = "message/rfc822")), + ) + ) + } + + private fun aSendIntent(type: String, uri: Uri) = Intent(Intent.ACTION_SEND).apply { + this.type = type + putExtra(Intent.EXTRA_STREAM, uri) + } + + private fun givenAnApplicationHandling(intent: Intent) { + val componentName = ComponentName(A_PACKAGE_NAME, AN_ACTIVITY_NAME) + shadowOf(RuntimeEnvironment.getApplication().packageManager).apply { + addActivityIfNotPresent(componentName) + addIntentFilterForActivity( + componentName, + IntentFilter(intent.action).apply { + addCategory(Intent.CATEGORY_DEFAULT) + addDataType(intent.type) + } + ) + } + } + + private fun createDefaultShareIntentHandler() = DefaultShareIntentHandler( + context = RuntimeEnvironment.getApplication(), + ) + + private class FailingGrantUriPermissionContext(context: Context) : ContextWrapper(context) { + override fun grantUriPermission(toPackage: String, uri: Uri, modeFlags: Int) { + error("Unable to grant Uri permission") + } + } + + private class ZipContentProvider : ContentProvider() { + override fun onCreate() = true + + override fun getType(uri: Uri) = "application/zip" + + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String?, + ): Cursor? = null + + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?) = 0 + + override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?) = 0 + } + + private companion object { + const val A_PACKAGE_NAME = "io.element.android.x" + const val AN_ACTIVITY_NAME = "io.element.android.x.MainActivity" + } +} diff --git a/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutStateProvider.kt b/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutStatePreviewParam.kt similarity index 94% rename from features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutStateProvider.kt rename to features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutStatePreviewParam.kt index 95a57db93e..ae60b7aacb 100644 --- a/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutStateProvider.kt +++ b/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.sessionstorage.api.LoginType import io.element.android.libraries.sessionstorage.api.SessionData -open class SignedOutStateProvider : PreviewParameterProvider { +open class SignedOutStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSignedOutState(), diff --git a/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutView.kt b/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutView.kt index 41a99713e7..9dcb4585e5 100644 --- a/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutView.kt +++ b/features/signedout/impl/src/main/kotlin/io/element/android/features/signedout/impl/SignedOutView.kt @@ -109,7 +109,7 @@ private fun SignedOutFooter( @PreviewsDayNight @Composable internal fun SignedOutViewPreview( - @PreviewParameter(SignedOutStateProvider::class) state: SignedOutState, + @PreviewParameter(SignedOutStatePreviewParam::class) state: SignedOutState, ) = ElementPreview { SignedOutView( state = state, diff --git a/features/signedout/impl/src/main/res/values-ar/translations.xml b/features/signedout/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..fecfbc2b3a --- /dev/null +++ b/features/signedout/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,8 @@ + + + "لقد غيّرت كلمة مرورك في جلسة أخرى" + "لقد حذفت هذه الجلسة من جلسة أخرى" + "أبطل مسؤول الخادم صلاحية وصولك" + "ربما تم تسجيل خروجك لأحد الأسباب المذكورة أدناه. يُرجى تسجيل الدخول مرة أخرى لمتابعة استخدام %s." + "تم تسجيل خروجك" + diff --git a/features/signedout/test/build.gradle.kts b/features/signedout/test/build.gradle.kts new file mode 100644 index 0000000000..5bbfb33c1a --- /dev/null +++ b/features/signedout/test/build.gradle.kts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ +plugins { + id("io.element.android-library") +} + +android { + namespace = "io.element.android.features.signedout.test" +} + +dependencies { + implementation(projects.libraries.architecture) + implementation(projects.features.signedout.api) + implementation(projects.tests.testutils) +} diff --git a/features/signedout/test/src/main/kotlin/io/element/android/features/signedout/test/FakeSignedOutEntryPoint.kt b/features/signedout/test/src/main/kotlin/io/element/android/features/signedout/test/FakeSignedOutEntryPoint.kt new file mode 100644 index 0000000000..863b946871 --- /dev/null +++ b/features/signedout/test/src/main/kotlin/io/element/android/features/signedout/test/FakeSignedOutEntryPoint.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.features.signedout.test + +import com.bumble.appyx.core.modality.BuildContext +import com.bumble.appyx.core.node.Node +import io.element.android.features.signedout.api.SignedOutEntryPoint +import io.element.android.tests.testutils.lambda.lambdaError + +class FakeSignedOutEntryPoint( + private val createNodeResult: (BuildContext, SignedOutEntryPoint.Params) -> Node = { _, _ -> lambdaError() }, +) : SignedOutEntryPoint { + override fun createNode( + parentNode: Node, + buildContext: BuildContext, + params: SignedOutEntryPoint.Params, + ): Node = createNodeResult(buildContext, params) +} diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceStateProvider.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceStatePreviewParam.kt similarity index 96% rename from features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceStateProvider.kt rename to features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceStatePreviewParam.kt index f9036f0452..9f9652c65c 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceStateProvider.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceStatePreviewParam.kt @@ -17,7 +17,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -internal class AddRoomToSpaceStateProvider : PreviewParameterProvider { +internal class AddRoomToSpaceStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( // Initial state with suggestions @@ -87,6 +87,7 @@ internal fun aSelectRoomInfoList(): ImmutableList = listOf( canonicalAlias = null, avatarUrl = null, heroes = persistentListOf(), + isDm = false, isTombstoned = false, ), SelectRoomInfo( @@ -95,6 +96,7 @@ internal fun aSelectRoomInfoList(): ImmutableList = listOf( canonicalAlias = null, avatarUrl = null, heroes = persistentListOf(), + isDm = false, isTombstoned = false, ), SelectRoomInfo( @@ -103,6 +105,7 @@ internal fun aSelectRoomInfoList(): ImmutableList = listOf( canonicalAlias = null, avatarUrl = null, heroes = persistentListOf(), + isDm = false, isTombstoned = false, ), ).toImmutableList() diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceView.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceView.kt index eb485f11b5..4db17634d6 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceView.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/addroom/AddRoomToSpaceView.kt @@ -12,10 +12,15 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items @@ -112,7 +117,13 @@ fun AddRoomToSpaceView( .consumeWindowInsets(paddingValues) ) { SearchBar( - modifier = Modifier.fillMaxWidth(), + modifier = Modifier + .fillMaxWidth() + .padding( + WindowInsets.safeDrawing + .only(WindowInsetsSides.Horizontal) + .asPaddingValues() + ), placeHolderTitle = stringResource(CommonStrings.action_search), queryState = state.searchQuery, active = state.isSearchActive, @@ -147,23 +158,35 @@ fun AddRoomToSpaceView( } if (!state.isSearchActive) { - Spacer(modifier = Modifier.height(16.dp)) - Text( - text = stringResource(R.string.screen_space_add_rooms_room_access_description), - color = ElementTheme.colors.textSecondary, - style = ElementTheme.typography.fontBodySmRegular, - modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) - ) - if (state.selectedRooms.isNotEmpty()) { - SelectedRoomsRow( - selectedRooms = state.selectedRooms, - onRemoveRoom = ::onRoomToggled, - modifier = Modifier.padding(vertical = 16.dp) + Column( + modifier = Modifier + .fillMaxWidth() + .padding( + WindowInsets.safeDrawing + .only(WindowInsetsSides.Horizontal) + .asPaddingValues() + ) + ) { + Spacer(modifier = Modifier.height(16.dp)) + Text( + text = stringResource(R.string.screen_space_add_rooms_room_access_description), + color = ElementTheme.colors.textSecondary, + style = ElementTheme.typography.fontBodySmRegular, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) ) + if (state.selectedRooms.isNotEmpty()) { + SelectedRoomsRow( + selectedRooms = state.selectedRooms, + onRemoveRoom = ::onRoomToggled, + modifier = Modifier.padding(vertical = 16.dp) + ) + } } if (state.suggestions.isNotEmpty()) { - LazyColumn { + LazyColumn( + contentPadding = lazyColumnContentPadding, + ) { item { ListSectionHeader( title = stringResource(id = CommonStrings.common_suggestions), @@ -250,7 +273,7 @@ private fun RoomListItem( @PreviewsDayNight @Composable internal fun AddRoomToSpaceViewPreview( - @PreviewParameter(AddRoomToSpaceStateProvider::class) state: AddRoomToSpaceState + @PreviewParameter(AddRoomToSpaceStatePreviewParam::class) state: AddRoomToSpaceState ) = ElementPreview { AddRoomToSpaceView( state = state, diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceStateProvider.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceStatePreviewParam.kt similarity index 98% rename from features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceStateProvider.kt rename to features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceStatePreviewParam.kt index ddf34cb076..3243a4fa53 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceStateProvider.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceStatePreviewParam.kt @@ -19,7 +19,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -class LeaveSpaceStateProvider : PreviewParameterProvider { +class LeaveSpaceStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aLeaveSpaceState(), diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceView.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceView.kt index b4722fad0d..992240cac2 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceView.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/leave/LeaveSpaceView.kt @@ -366,7 +366,7 @@ private fun SpaceItem( @PreviewsDayNight @Composable internal fun LeaveSpaceViewPreview( - @PreviewParameter(LeaveSpaceStateProvider::class) state: LeaveSpaceState, + @PreviewParameter(LeaveSpaceStatePreviewParam::class) state: LeaveSpaceState, ) = ElementPreview { LeaveSpaceView( state = state, diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpacePresenter.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpacePresenter.kt index 5ce6575493..de30ddb6c1 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpacePresenter.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpacePresenter.kt @@ -35,6 +35,7 @@ import io.element.android.libraries.matrix.api.core.toRoomIdOrAlias import io.element.android.libraries.matrix.api.room.BaseRoom import io.element.android.libraries.matrix.api.room.CurrentUserMembership import io.element.android.libraries.matrix.api.room.join.JoinRoom +import io.element.android.libraries.matrix.api.room.join.JoinRule import io.element.android.libraries.matrix.api.room.powerlevels.permissionsAsState import io.element.android.libraries.matrix.api.spaces.SpaceRoom import io.element.android.libraries.matrix.api.spaces.SpaceRoomList @@ -117,12 +118,14 @@ class SpacePresenter( val filteredChildren by remember { derivedStateOf { - val notRemoved = children.filterNot { it.roomId in removedRoomIds } + val visibleChildren = children + .filterNot { it.roomId in removedRoomIds } + .filterNot { it.cannotBeRejoined() } if (isManageMode) { // In manage mode, only show rooms (not spaces) - notRemoved.filter { !it.isSpace }.toImmutableList() + visibleChildren.filter { !it.isSpace }.toImmutableList() } else { - notRemoved.toImmutableList() + visibleChildren.toImmutableList() } } } @@ -254,3 +257,7 @@ class SpacePresenter( } } } + +private fun SpaceRoom.cannotBeRejoined(): Boolean { + return state == CurrentUserMembership.LEFT && joinRule == JoinRule.Invite +} diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceStateProvider.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceStatePreviewParam.kt similarity index 98% rename from features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceStateProvider.kt rename to features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceStatePreviewParam.kt index 6824cc6c10..34d6e4534a 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceStateProvider.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceStatePreviewParam.kt @@ -26,7 +26,7 @@ import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableMap import kotlinx.collections.immutable.toImmutableSet -open class SpaceStateProvider : PreviewParameterProvider { +open class SpaceStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSpaceState(), diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceView.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceView.kt index fe971091f5..f1cddf5e0f 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceView.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/root/SpaceView.kt @@ -680,7 +680,7 @@ private fun RemoveRoomsActionView( @PreviewsDayNight @Composable internal fun SpaceViewPreview( - @PreviewParameter(SpaceStateProvider::class) state: SpaceState + @PreviewParameter(SpaceStatePreviewParam::class) state: SpaceState ) = ElementPreview { SpaceView( state = state, diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsStateProvider.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsStatePreviewParam.kt similarity index 94% rename from features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsStateProvider.kt rename to features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsStatePreviewParam.kt index 36f6a2a1d0..a68a3ce850 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsStateProvider.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.designsystem.preview.SPACE_NAME import io.element.android.libraries.matrix.api.core.RoomAlias import io.element.android.libraries.matrix.api.core.RoomId -open class SpaceSettingsStateProvider : PreviewParameterProvider { +open class SpaceSettingsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSpaceSettingsState(), diff --git a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsView.kt b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsView.kt index 6237e443b0..b5cfc7702a 100644 --- a/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsView.kt +++ b/features/space/impl/src/main/kotlin/io/element/android/features/space/impl/settings/SpaceSettingsView.kt @@ -223,7 +223,7 @@ private fun LeaveSpaceItem( @PreviewsDayNight @Composable internal fun SpaceSettingsViewPreview( - @PreviewParameter(SpaceSettingsStateProvider::class) state: SpaceSettingsState + @PreviewParameter(SpaceSettingsStatePreviewParam::class) state: SpaceSettingsState ) = ElementPreview { SpaceSettingsView( state = state, diff --git a/features/space/impl/src/main/res/values-ar/translations.xml b/features/space/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..346752f14e --- /dev/null +++ b/features/space/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,36 @@ + + + "اختيار المالكين" + "%1$s (مسؤول)" + + "مغادرة %1$d غرف والمساحة" + "مغادرة %1$d غرفة والمساحة" + "مغادرة %1$d غرفتين والمساحة" + "مغادرة %1$d غرف والمساحة" + "مغادرة %1$d غرفة والمساحة" + "مغادرة %1$d غرفة والمساحة" + + "اختر الغرف التي تريد مغادرتها، والتي لست المسؤول الوحيد عنها:" + "يجب أن تعيّن مسؤولًا آخر لهذه المساحة قبل أن تتمكن من المغادرة." + "أنت المالك الوحيد لـ %1$s. يجب أن تنقل الملكية إلى شخص آخر قبل المغادرة." + "لن تتم إزالتك من الغرف التالية لأنك المسؤول الوحيد:" + "مغادرة %1$s؟" + "أنت المسؤول الوحيد عن %1$s" + "نقل الملكية" + "غرفة" + "لن تؤثر إضافة غرفة على إمكانية الوصول إلى الغرفة. لتغيير الوصول، انتقل إلى إعدادات الغرفة > الأمان والخصوصية." + "أضف غرفتك الأولى" + "عرض الأعضاء" + "لن تؤثر إزالة غرفة على إمكانية الوصول إلى الغرفة. لتغيير الوصول، انتقل إلى معلومات الغرفة > الخصوصية والأمان." + + "إزالة %1$d غرف من %2$s" + "إزالة %1$d غرفة من %2$s" + "إزالة %1$d غرفتين من %2$s" + "إزالة %1$d غرف من %2$s" + "إزالة %1$d غرفة من %2$s" + "إزالة %1$d غرفة من %2$s" + + "مغادرة المساحة" + "الأدوار والصلاحيات" + "الأمان والخصوصية" + diff --git a/features/space/impl/src/main/res/values-es/translations.xml b/features/space/impl/src/main/res/values-es/translations.xml index 41887088b6..f65375f616 100644 --- a/features/space/impl/src/main/res/values-es/translations.xml +++ b/features/space/impl/src/main/res/values-es/translations.xml @@ -1,5 +1,28 @@ + "Elegir propietarios" + "%1$s (Admin.)" + + "Salir de %1$d sala y del espacio" + "Salir de %1$d salas y del espacio" + + "Elige las salas de las que quieras salir en las que no eres el único administrador:" + "Debes designar otro administrador para este espacio antes de poder salir." + "Eres el único propietario de %1$s. Debes transferir la propiedad a otra persona antes de salir." + "No se te eliminará de las siguientes salas porque eres el único administrador:" + "¿Salir de %1$s?" + "Eres el único administrador de %1$s" + "Transferencia de propiedad" + "Sala" + "Añadir una sala no afectará a su configuración de acceso. Para cambiar el acceso, ve a Ajustes de la sala > Seguridad y privacidad." + "Añade tu primera sala" + "Ver miembros" + "Eliminar una sala no afectará a su configuración de acceso. Para cambiar el acceso, ve a Información de la sala > Privacidad y seguridad." + + "Eliminar %1$d sala de %2$s" + "Eliminar %1$d salas de %2$s" + + "Salir del espacio" "Roles y permisos" "Seguridad y privacidad" diff --git a/features/space/impl/src/main/res/values-fa/translations.xml b/features/space/impl/src/main/res/values-fa/translations.xml index d8f377c0b2..9aa3818f44 100644 --- a/features/space/impl/src/main/res/values-fa/translations.xml +++ b/features/space/impl/src/main/res/values-fa/translations.xml @@ -2,11 +2,26 @@ "گزینش مالکان" "‏%1$s (مدیر)" + + "اتاق و فضای %1$d را ترک کنید" + "اتاق‌ها و فضای %1$d را ترک کنید" + + "اتاق‌هایی را که می‌خواهید از آنها خارج شوید و تنها مدیر آنها نیستید، انتخاب کنید:" "پیش از ترک باید مدیری دیگر به این فضا تخصیص دهید." + "شما تنها مالک %1$s هستید. قبل از ترک محل، باید مالکیت را به شخص دیگری منتقل کنید." "از اتاق(های) زیر برداشته نخواهید شد؛ چرا که تنها مدیر هستید:" "ترک %1$s؟" "تنها مدیر %1$s هستید" + "انتقال مالکیت" + "اتاق" + "اضافه کردن اتاق تاثیری بر دسترسی به اتاق نخواهد داشت. برای تغییر دسترسی، به تنظیمات اتاق > امنیت و حریم خصوصی بروید." + "اولین اتاق خود را اضافه کنید" "دیدن اعضا" + "حذف یک اتاق تاثیری بر دسترسی به آن نخواهد داشت. برای تغییر دسترسی، به اطلاعات اتاق > حریم خصوصی و امنیت بروید." + + "حذف اتاق %1$d از %2$s" + "حذف اتاق‌های %1$d از %2$s" + "ترک فضا" "نقش‌ها و مجوزها" "امنیت و محرمانگی" diff --git a/features/space/impl/src/test/kotlin/io/element/android/features/space/impl/root/SpacePresenterTest.kt b/features/space/impl/src/test/kotlin/io/element/android/features/space/impl/root/SpacePresenterTest.kt index ba4e10a447..2de52a600b 100644 --- a/features/space/impl/src/test/kotlin/io/element/android/features/space/impl/root/SpacePresenterTest.kt +++ b/features/space/impl/src/test/kotlin/io/element/android/features/space/impl/root/SpacePresenterTest.kt @@ -30,11 +30,13 @@ import io.element.android.libraries.matrix.api.room.BaseRoom import io.element.android.libraries.matrix.api.room.CurrentUserMembership import io.element.android.libraries.matrix.api.room.RoomType import io.element.android.libraries.matrix.api.room.join.JoinRoom +import io.element.android.libraries.matrix.api.room.join.JoinRule import io.element.android.libraries.matrix.api.spaces.SpaceRoomList import io.element.android.libraries.matrix.test.AN_EXCEPTION import io.element.android.libraries.matrix.test.A_ROOM_ID import io.element.android.libraries.matrix.test.A_ROOM_ID_2 import io.element.android.libraries.matrix.test.A_ROOM_ID_3 +import io.element.android.libraries.matrix.test.A_ROOM_ID_4 import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.libraries.matrix.test.room.FakeBaseRoom import io.element.android.libraries.matrix.test.room.join.FakeJoinRoom @@ -537,6 +539,78 @@ class SpacePresenterTest { } } + @Test + fun `present - left children which can only be joined by invitation are filtered out`() = runTest { + val leftInviteOnlyRoom = aSpaceRoom( + roomId = A_ROOM_ID, + roomType = RoomType.Room, + state = CurrentUserMembership.LEFT, + joinRule = JoinRule.Invite, + ) + val leftPublicRoom = aSpaceRoom( + roomId = A_ROOM_ID_2, + roomType = RoomType.Room, + state = CurrentUserMembership.LEFT, + joinRule = JoinRule.Public, + ) + val leftKnockRoom = aSpaceRoom( + roomId = A_ROOM_ID_3, + roomType = RoomType.Room, + state = CurrentUserMembership.LEFT, + joinRule = JoinRule.Knock, + ) + val leftRoomWithUnknownJoinRule = aSpaceRoom( + roomId = A_ROOM_ID_4, + roomType = RoomType.Room, + state = CurrentUserMembership.LEFT, + joinRule = null, + ) + val fakeSpaceRoomList = FakeSpaceRoomList( + initialSpaceRoomsValue = listOf(leftInviteOnlyRoom, leftPublicRoom, leftKnockRoom, leftRoomWithUnknownJoinRule), + paginateResult = { Result.success(Unit) }, + ) + val presenter = createSpacePresenter(spaceRoomList = fakeSpaceRoomList) + presenter.test { + awaitItem() + advanceUntilIdle() + val stateWithChildren = expectMostRecentItem() + assertThat(stateWithChildren.children).containsExactly(leftPublicRoom, leftKnockRoom, leftRoomWithUnknownJoinRule) + } + } + + @Test + fun `present - children which can only be joined by invitation are kept when not left`() = runTest { + val joinedRoom = aSpaceRoom( + roomId = A_ROOM_ID, + roomType = RoomType.Room, + state = CurrentUserMembership.JOINED, + joinRule = JoinRule.Invite, + ) + val invitedRoom = aSpaceRoom( + roomId = A_ROOM_ID_2, + roomType = RoomType.Room, + state = CurrentUserMembership.INVITED, + joinRule = JoinRule.Invite, + ) + val roomWithUnknownMembership = aSpaceRoom( + roomId = A_ROOM_ID_3, + roomType = RoomType.Room, + state = null, + joinRule = JoinRule.Invite, + ) + val fakeSpaceRoomList = FakeSpaceRoomList( + initialSpaceRoomsValue = listOf(joinedRoom, invitedRoom, roomWithUnknownMembership), + paginateResult = { Result.success(Unit) }, + ) + val presenter = createSpacePresenter(spaceRoomList = fakeSpaceRoomList) + presenter.test { + awaitItem() + advanceUntilIdle() + val stateWithChildren = expectMostRecentItem() + assertThat(stateWithChildren.children).containsExactly(joinedRoom, invitedRoom, roomWithUnknownMembership) + } + } + @Test fun `present - removed rooms persist after flow update on partial failure`() = runTest { // On partial failure, successfully removed rooms should stay filtered even after flow updates diff --git a/features/startchat/api/src/main/kotlin/io/element/android/features/startchat/api/StartDMAction.kt b/features/startchat/api/src/main/kotlin/io/element/android/features/startchat/api/StartDMAction.kt index 6aa2ad5d98..2e5a92f18e 100644 --- a/features/startchat/api/src/main/kotlin/io/element/android/features/startchat/api/StartDMAction.kt +++ b/features/startchat/api/src/main/kotlin/io/element/android/features/startchat/api/StartDMAction.kt @@ -13,6 +13,11 @@ import io.element.android.libraries.architecture.AsyncAction import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.user.MatrixUser +/** + * Opens a direct message with a user, reusing the existing room when there is one. + * + * Progress is reported into the state passed in, so the caller only has to render it. + */ interface StartDMAction { /** * Try to find an existing DM with the given user, or create one if none exists. diff --git a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/components/UserListView.kt b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/components/UserListView.kt index c8587d9784..4b62820ef4 100644 --- a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/components/UserListView.kt +++ b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/components/UserListView.kt @@ -26,7 +26,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp import io.element.android.features.startchat.impl.userlist.UserListEvents import io.element.android.features.startchat.impl.userlist.UserListState -import io.element.android.features.startchat.impl.userlist.UserListStateProvider +import io.element.android.features.startchat.impl.userlist.UserListStatePreviewParam import io.element.android.libraries.designsystem.components.avatar.AvatarSize import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight @@ -129,7 +129,7 @@ fun UserListView( @PreviewsDayNight @Composable -internal fun UserListViewPreview(@PreviewParameter(UserListStateProvider::class) state: UserListState) = ElementPreview { +internal fun UserListViewPreview(@PreviewParameter(UserListStatePreviewParam::class) state: UserListState) = ElementPreview { UserListView( state = state, onSelectUser = {}, diff --git a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressStateProvider.kt b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressStatePreviewParam.kt similarity index 93% rename from features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressStateProvider.kt rename to features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressStatePreviewParam.kt index 5528a84196..3404a737a3 100644 --- a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressStateProvider.kt +++ b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.room.alias.ResolvedRoomAlias -open class JoinRoomByAddressStateProvider : PreviewParameterProvider { +open class JoinRoomByAddressStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aJoinRoomByAddressState(), diff --git a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressView.kt b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressView.kt index ffe6a47f0d..4d2babe70b 100644 --- a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressView.kt +++ b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/joinbyaddress/JoinRoomByAddressView.kt @@ -137,7 +137,7 @@ private fun RoomAddressField( @PreviewsDayNight @Composable internal fun JoinRoomByAddressViewPreview( - @PreviewParameter(JoinRoomByAddressStateProvider::class) state: JoinRoomByAddressState + @PreviewParameter(JoinRoomByAddressStatePreviewParam::class) state: JoinRoomByAddressState ) = ElementPreview { JoinRoomByAddressView(state = state) } diff --git a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatStateProvider.kt b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatStatePreviewParam.kt similarity index 97% rename from features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatStateProvider.kt rename to features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatStatePreviewParam.kt index 41a3551d1d..e8ac1d55a7 100644 --- a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatStateProvider.kt +++ b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatStatePreviewParam.kt @@ -21,7 +21,7 @@ import io.element.android.libraries.matrix.ui.components.aMatrixUser import io.element.android.libraries.usersearch.api.UserSearchResult import kotlinx.collections.immutable.persistentListOf -open class StartChatStateProvider : PreviewParameterProvider { +open class StartChatStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aCreateRoomRootState(), diff --git a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatView.kt b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatView.kt index 104a8cecf7..350cf15757 100644 --- a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatView.kt +++ b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/root/StartChatView.kt @@ -255,7 +255,7 @@ private fun CreateRoomActionButton( @PreviewsDayNight @Composable -internal fun StartChatViewPreview(@PreviewParameter(StartChatStateProvider::class) state: StartChatState) = +internal fun StartChatViewPreview(@PreviewParameter(StartChatStatePreviewParam::class) state: StartChatState) = ElementPreview { StartChatView( state = state, diff --git a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/userlist/UserListStateProvider.kt b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/userlist/UserListStatePreviewParam.kt similarity index 97% rename from features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/userlist/UserListStateProvider.kt rename to features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/userlist/UserListStatePreviewParam.kt index 91d047d238..190ff23ad2 100644 --- a/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/userlist/UserListStateProvider.kt +++ b/features/startchat/impl/src/main/kotlin/io/element/android/features/startchat/impl/userlist/UserListStatePreviewParam.kt @@ -19,7 +19,7 @@ import io.element.android.libraries.usersearch.api.UserSearchResult import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList -open class UserListStateProvider : PreviewParameterProvider { +open class UserListStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aUserListState(), diff --git a/features/startchat/impl/src/main/res/values-ar/translations.xml b/features/startchat/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..b4e96844c4 --- /dev/null +++ b/features/startchat/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,12 @@ + + + "إنشاء غرفة جديدة" + "دليل الغرف" + "حدث خطأ أثناء محاولة بدء محادثة" + "الانضمام إلى غرفة باستخدام العنوان" + "العنوان غير صالح" + "أدخل العنوان…" + "تم العثور على غرفة مطابقة" + "لم يتم العثور على الغرفة" + "مثلاً: #room-name:matrix.org" + diff --git a/features/startchat/impl/src/main/res/values-de/translations.xml b/features/startchat/impl/src/main/res/values-de/translations.xml index 7608517314..61137aea5b 100644 --- a/features/startchat/impl/src/main/res/values-de/translations.xml +++ b/features/startchat/impl/src/main/res/values-de/translations.xml @@ -5,7 +5,7 @@ "Beim Versuch, einen Chat zu starten, ist ein Fehler aufgetreten" "Chat per Adresse beitreten" "Keine gültige Adresse" - "Eintreten…" + "Chatraum Adresse eingeben …" "Passender Chat gefunden" "Chat nicht gefunden" "z. B. #room -name:matrix.org" diff --git a/features/startchat/impl/src/main/res/values-es/translations.xml b/features/startchat/impl/src/main/res/values-es/translations.xml index 64a9f02a17..dd4233ce50 100644 --- a/features/startchat/impl/src/main/res/values-es/translations.xml +++ b/features/startchat/impl/src/main/res/values-es/translations.xml @@ -5,7 +5,7 @@ "Se ha producido un error al intentar iniciar un chat" "Unirse a una sala por su dirección" "Dirección no válida" - "Introducir…" + "Introducir dirección…" "Sala encontrada" "No se encontró la sala" "p. ej., #nombre-de-la-sala:matrix.org" diff --git a/features/startchat/impl/src/main/res/values-fa/translations.xml b/features/startchat/impl/src/main/res/values-fa/translations.xml index 7cb1e1baee..4a4cd239de 100644 --- a/features/startchat/impl/src/main/res/values-fa/translations.xml +++ b/features/startchat/impl/src/main/res/values-fa/translations.xml @@ -5,7 +5,7 @@ "هنگام تلاش برای شروع چت خطایی روی داد" "پیوستن به اتاق با نشانی" "نشانی معتبری نیست" - "ورود…" + "آدرس را وارد کنید…" "اتاق مطابق پیدا شد" "اتاق پیدا نشد" "نمونه: ‪#room-name:matrix.org" diff --git a/features/startchat/impl/src/main/res/values-fr/translations.xml b/features/startchat/impl/src/main/res/values-fr/translations.xml index 9aaebd018f..74a099f93a 100644 --- a/features/startchat/impl/src/main/res/values-fr/translations.xml +++ b/features/startchat/impl/src/main/res/values-fr/translations.xml @@ -5,7 +5,7 @@ "Une erreur s’est produite lors de la tentative de création de la discussion" "Saisir une adresse de salon" "Ce n’est pas une adresse valide" - "Saisir…" + "Adresse du salon…" "Ce salon existe" "Salon non trouvé" "ex: #nom-du-salon:matrix.org" diff --git a/features/startchat/impl/src/main/res/values-ro/translations.xml b/features/startchat/impl/src/main/res/values-ro/translations.xml index 315191a182..d003475a9f 100644 --- a/features/startchat/impl/src/main/res/values-ro/translations.xml +++ b/features/startchat/impl/src/main/res/values-ro/translations.xml @@ -5,7 +5,7 @@ "A apărut o eroare la încercarea începerii conversației" "Gasiți o cameră după adresă" "Adresa nu e este validă" - "Introduceți…" + "Introduceți adresa…" "S-a găsit o cameră" "Nu a putut fi găsită nici o cameră" "de exemplu #nume-camera:matrix.org" diff --git a/features/startchat/impl/src/main/res/values-zh-rTW/translations.xml b/features/startchat/impl/src/main/res/values-zh-rTW/translations.xml index c6dcd50008..d104b0ce1b 100644 --- a/features/startchat/impl/src/main/res/values-zh-rTW/translations.xml +++ b/features/startchat/impl/src/main/res/values-zh-rTW/translations.xml @@ -5,7 +5,7 @@ "嘗試開始聊天時發生錯誤" "按地址加入聊天室" "不是有效的位址" - "輸入……" + "輸入地址⋯⋯" "找到相符的聊天室" "找不到聊天室" "例如 #room-name:matrix.org" diff --git a/features/userprofile/api/src/main/kotlin/io/element/android/features/userprofile/api/UserProfilePresenterFactory.kt b/features/userprofile/api/src/main/kotlin/io/element/android/features/userprofile/api/UserProfilePresenterFactory.kt index 4bf68ae324..80a21505f5 100644 --- a/features/userprofile/api/src/main/kotlin/io/element/android/features/userprofile/api/UserProfilePresenterFactory.kt +++ b/features/userprofile/api/src/main/kotlin/io/element/android/features/userprofile/api/UserProfilePresenterFactory.kt @@ -11,6 +11,12 @@ package io.element.android.features.userprofile.api import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.matrix.api.core.UserId +/** + * Creates the user profile presenter, so that other features can show a profile without depending on this one's implementation. + */ fun interface UserProfilePresenterFactory { + /** + * @param userId the user whose profile is shown. + */ fun create(userId: UserId): Presenter } diff --git a/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileStateProvider.kt b/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileStatePreviewParam.kt similarity index 97% rename from features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileStateProvider.kt rename to features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileStatePreviewParam.kt index 4e25284753..84a95e0b14 100644 --- a/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileStateProvider.kt +++ b/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileStatePreviewParam.kt @@ -21,7 +21,7 @@ import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.ui.components.aMatrixUser -open class UserProfileStateProvider : PreviewParameterProvider { +open class UserProfileStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aUserProfileState(), diff --git a/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileView.kt b/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileView.kt index c5a661dbac..b9f43db36d 100644 --- a/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileView.kt +++ b/features/userprofile/shared/src/main/kotlin/io/element/android/features/userprofile/shared/UserProfileView.kt @@ -147,7 +147,7 @@ private fun VerifyUserSection( @PreviewsDayNight @Composable internal fun UserProfileViewPreview( - @PreviewParameter(UserProfileStateProvider::class) state: UserProfileState + @PreviewParameter(UserProfileStatePreviewParam::class) state: UserProfileState ) = ElementPreview { UserProfileView( state = state, diff --git a/features/userprofile/shared/src/main/res/values-ar/translations.xml b/features/userprofile/shared/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..2292e8cb70 --- /dev/null +++ b/features/userprofile/shared/src/main/res/values-ar/translations.xml @@ -0,0 +1,19 @@ + + + "حظر" + "المستخدمون المحظورون لن يتمكّنوا من إرسال رسائل لك وكل رسائلهم ستُحجب. يمكنك إلغاء حظرهم متى ما أردت." + "حظر المستخدم" + "إلغاء الحظر" + "ستتمكن من رؤية كل رسائلهم مجدّداً." + "إلغاء حظر المستخدم" + "حظر" + "المستخدمون المحظورون لن يتمكّنوا من إرسال رسائل لك وكل رسائلهم ستُحجب. يمكنك إلغاء حظرهم متى ما أردت." + "حظر المستخدم" + "الملف الشخصي" + "إلغاء الحظر" + "ستتمكن من رؤية كل رسائلهم مجدّداً." + "إلغاء حظر المستخدم" + "استخدم تطبيق الويب للتحقق من هذا المستخدم." + "تحقّق من %1$s" + "حدث خطأ أثناء محاولة بدء محادثة" + diff --git a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationStateProvider.kt b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationStatePreviewParam.kt similarity index 97% rename from features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationStateProvider.kt rename to features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationStatePreviewParam.kt index 895f78cbdc..c8d70e03c0 100644 --- a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationStateProvider.kt +++ b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationStatePreviewParam.kt @@ -20,7 +20,7 @@ import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.api.verification.SessionVerificationRequestDetails import io.element.android.libraries.matrix.api.verification.VerificationRequest -open class IncomingVerificationStateProvider : PreviewParameterProvider { +open class IncomingVerificationStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anIncomingVerificationState(), diff --git a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationView.kt b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationView.kt index e86c83825b..64adc78aa0 100644 --- a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationView.kt +++ b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/incoming/IncomingVerificationView.kt @@ -264,7 +264,9 @@ private fun IncomingVerificationBottomMenu( @PreviewsDayNight @Composable -internal fun IncomingVerificationViewPreview(@PreviewParameter(IncomingVerificationStateProvider::class) state: IncomingVerificationState) = ElementPreview { +internal fun IncomingVerificationViewPreview(@PreviewParameter( + IncomingVerificationStatePreviewParam::class +) state: IncomingVerificationState) = ElementPreview { IncomingVerificationView( state = state, ) diff --git a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStateMachine.kt b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStateMachine.kt index 465fc20066..c97bf2cd2e 100644 --- a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStateMachine.kt +++ b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStateMachine.kt @@ -15,7 +15,6 @@ import com.freeletics.flowredux.dsl.FlowReduxStateMachine import io.element.android.features.verifysession.impl.util.andLogStateChange import io.element.android.features.verifysession.impl.util.logReceivedEvents import io.element.android.libraries.core.bool.orFalse -import io.element.android.libraries.core.data.tryOrNull import io.element.android.libraries.matrix.api.encryption.EncryptionService import io.element.android.libraries.matrix.api.encryption.RecoveryState import io.element.android.libraries.matrix.api.verification.SessionVerificationData @@ -23,6 +22,7 @@ import io.element.android.libraries.matrix.api.verification.SessionVerificationS import io.element.android.libraries.matrix.api.verification.VerificationRequest import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.timeout @@ -95,10 +95,13 @@ class OutgoingVerificationStateMachine( // If a key backup exists, wait until it's restored or a timeout happens val hasBackup = encryptionService.doesBackupExistOnServer().getOrNull().orFalse() if (hasBackup) { - tryOrNull { - encryptionService.recoveryStateStateFlow.filter { it == RecoveryState.ENABLED } + try { + encryptionService.recoveryStateStateFlow + .filter { it == RecoveryState.ENABLED || it == RecoveryState.DISABLED || it == RecoveryState.INCOMPLETE } .timeout(10.seconds) .first() + } catch (_: TimeoutCancellationException) { + // The backup was not restored in time, proceed to the Completed state anyway } } state.override { State.Completed.andLogStateChange() } diff --git a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStateProvider.kt b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStatePreviewParam.kt similarity index 97% rename from features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStateProvider.kt rename to features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStatePreviewParam.kt index 2da099df9f..ee3d5dd7a3 100644 --- a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStateProvider.kt +++ b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.verification.VerificationRequest -open class OutgoingVerificationStateProvider : PreviewParameterProvider { +open class OutgoingVerificationStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anOutgoingVerificationState( diff --git a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationView.kt b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationView.kt index 9131ad63fb..978ced6587 100644 --- a/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationView.kt +++ b/features/verifysession/impl/src/main/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationView.kt @@ -328,7 +328,9 @@ private fun OutgoingVerificationBottomMenu( @PreviewsDayNight @Composable -internal fun OutgoingVerificationViewPreview(@PreviewParameter(OutgoingVerificationStateProvider::class) state: OutgoingVerificationState) = ElementPreview { +internal fun OutgoingVerificationViewPreview(@PreviewParameter( + OutgoingVerificationStatePreviewParam::class +) state: OutgoingVerificationState) = ElementPreview { OutgoingVerificationView( state = state, onLearnMoreClick = {}, diff --git a/features/verifysession/impl/src/main/res/values-ar/translations.xml b/features/verifysession/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..104dbdacfa --- /dev/null +++ b/features/verifysession/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,54 @@ + + + "لا يمكنك التأكيد؟" + "إنشاء مفتاح استرداد جديد" + "اختر طريقة التحقق لإعداد المراسلة الآمنة." + "تأكيد هويتك الرقمية" + "استخدام جهاز آخر" + "استخدام مفتاح الاسترداد" + "يمكنك الآن قراءة الرسائل أو إرسالها بأمان، ويمكن لأي شخص تدردش معه أن يثق بهذا الجهاز أيضًا." + "تم التحقق من الجهاز" + "استخدام جهاز آخر" + "في انتظار الجهاز الآخر…" + "شيء ما لا يبدو سليماً. إما مهلة الطلب قد انتهت أو أن الطلب رُفِض." + "تأكد من تطابق الرموز التعبيرية أدناه مع تلك الظاهرة في جلستك الأخرى." + "قارن الرموز التعبيرية" + "أكّد أن الرموز التعبيرية أدناه تطابق الرموز المعروضة على جهاز المستخدم الآخر." + "أكّد أن الأرقام أدناه تطابق الأرقام المعروضة في جلستك الأخرى." + "قارن الأرقام" + "تم التحقق من جلستك الحالية. فيها وصول إلى رسائلك المشفّرة والمستخدمون الآخرون يرونها موثوقة." + "يمكنك الآن الوثوق بالهوية الرقمية لهذا المستخدم عند إرسال الرسائل أو تلقيها." + "تم التحقق من الجهاز" + "أدخل مفتاح الاسترداد" + "إما أن الطلب انتهت مهلته، أو تم رفضه، أو حدث عدم تطابق في التحقق." + "أثبت هويتك ليصبح لديك وصول إلى رسائلك المشفّرة السابقة." + "افتح جلسة موجودة" + "إعادة محاولة عملية التحقق" + "جاهز" + "بانتظار التطابق" + "قارِن مجموعة فريدة من الرموز التعبيرية." + "قارن بين الرموز التعبيرية المميزة، متأكداً من ورودها في نفس الترتيب." + "تم تسجيل الدخول" + "إما أن الطلب انتهت مهلته، أو تم رفضه، أو حدث عدم تطابق في التحقق." + "فشل التحقق" + "لا تتابع إلا إذا كنت أنت من بدأ هذا التحقق." + "تحقّق من الجهاز الآخر للحفاظ على أمان سجل رسائلك." + "تم التحقق من جلستك الحالية. فيها وصول إلى رسائلك المشفّرة والمستخدمون الآخرون يرونها موثوقة." + "تم التحقق من الجهاز" + "تم طلب التحقق" + "لا يتطابقون" + "يتطابقون" + "تأكّد من أن التطبيق مفتوح على الجهاز الآخر قبل بدء التحقق من هنا." + "افتح التطبيق على جهاز آخر تم التحقق منه" + "لمزيد من الأمان، تحقّق من هذا المستخدم بمقارنة مجموعة من الرموز التعبيرية على أجهزتكما. افعل ذلك باستخدام وسيلة موثوقة للتواصل." + "هل تريد التحقق من هذا المستخدم؟" + "لمزيد من الأمان، يريد مستخدم آخر التحقق من هويتك الرقمية. ستُعرض لك مجموعة من الرموز التعبيرية لمقارنتها." + "من المفترض أن تظهر نافذة منبثقة على الجهاز الآخر. ابدأ التحقق من هناك الآن." + "ابدأ التحقق على الجهاز الآخر" + "ابدأ التحقق على الجهاز الآخر" + "في انتظار المستخدم الآخر" + "بمجرد القبول، ستتمكن من متابعة التحقق." + "اِقبل طلب بدء عملية التحقق في جلستك الأخرة للاستمرار." + "بانتظار قبول الطلب" + "تجري إزالة الجهاز…" + diff --git a/features/verifysession/impl/src/main/res/values-es/translations.xml b/features/verifysession/impl/src/main/res/values-es/translations.xml index 52422393bf..de23ddc217 100644 --- a/features/verifysession/impl/src/main/res/values-es/translations.xml +++ b/features/verifysession/impl/src/main/res/values-es/translations.xml @@ -2,8 +2,8 @@ "¿No puedes confirmar?" "Crear una nueva clave de recuperación" - "Verifica este dispositivo para configurar la mensajería segura." - "Confirma que eres tú" + "Elige cómo verificar para configurar la mensajería segura." + "Confirma tu identidad digital" "Usar otro dispositivo" "Usar clave de recuperación" "Ahora puedes leer o enviar mensajes de forma segura y cualquier persona con la que chatees también puede confiar en este dispositivo." @@ -17,7 +17,7 @@ "Confirma que los números que aparecen a continuación coinciden con los mostrados en tu otra sesión." "Comparar números" "Ahora puedes leer o enviar mensajes de forma segura en tu otro dispositivo." - "Ahora puedes confiar en la identidad de este usuario al enviar o recibir mensajes." + "Ahora puedes confiar en la identidad digital de este usuario al enviar o recibir mensajes." "Dispositivo verificado" "Introduce la clave de recuperación" "O bien se agotó el tiempo de solicitud, se rechazó la solicitud o hubo una discrepancia en la verificación." @@ -42,7 +42,7 @@ "Abre la aplicación en otro dispositivo verificado" "Para mayor seguridad, verifica a este usuario comparando un conjunto de emojis en vuestros dispositivos. Hazlo utilizando una forma de comunicación de confianza." "¿Verificar a este usuario?" - "Para mayor seguridad, otro usuario quiere verificar tu identidad. Se te mostrará un conjunto de emojis para compararlos." + "Para mayor seguridad, otro usuario quiere verificar tu identidad digital. Se te mostrará un conjunto de emojis para compararlos." "Deberías ver una ventana emergente en el otro dispositivo. Inicia ahora la verificación desde allí." "Iniciar la verificación en el otro dispositivo" "Iniciar la verificación en el otro dispositivo" @@ -50,5 +50,5 @@ "Una vez aceptada, podrás continuar con la verificación." "Acepta la solicitud para iniciar el proceso de verificación en tu otra sesión para continuar." "A la espera de aceptar la solicitud" - "Cerrando sesión…" + "Eliminando dispositivo…" diff --git a/features/verifysession/impl/src/main/res/values-fa/translations.xml b/features/verifysession/impl/src/main/res/values-fa/translations.xml index d68ec29229..5f2b02584c 100644 --- a/features/verifysession/impl/src/main/res/values-fa/translations.xml +++ b/features/verifysession/impl/src/main/res/values-fa/translations.xml @@ -13,11 +13,14 @@ "يه چيزي درست به نظر نمياد یا زمان درخواست به پایان رسید یا درخواست رد شد." "تأیید تطابق شکلک‌های زیر با شکلک‌های نشان داده شده روی افزارهٔ دیگرتان." "مقایسهٔ شکلک‌ها" + "تأیید کنید که ایموجی‌های زیر با ایموجی‌های نمایش داده شده در دستگاه کاربر دیگر مطابقت دارند." "تأیید کنید که اعداد زیر با اعداد نشان داده شده در جلسه دیگر شما مطابقت دارند." "مقایسهٔ اعداد" "اکنون می‌توانید روی افزارهٔ دیگرتان با امنیت پیام فرستاده و بخوانید." + "اکنون می‌توانید هنگام ارسال یا دریافت پیام، به هویت دیجیتال این کاربر اعتماد کنید." "افزاره تأیید شده" "ورود کلید بازیابی" + "یا مهلت درخواست تمام شده، یا درخواست رد شده، یا عدم تطابق تأیید وجود داشته است." "برای دسترسی به تاریخچه پیام‌های رمزگذاری‌شده‌تان، ثابت کنید که خودتان هستید." "گشودن نشستی موجود" "تلاش برای تأیید دوباره" @@ -26,11 +29,25 @@ "مقایسهٔ مجموعه‌ای یکتا از شکلک‌ها." "شکلک‌ها را مقایسه کنید، از ترتیب نمایش آنان نیز مطمئن شوید." "وارد شده" + "یا مهلت درخواست تمام شده، یا درخواست رد شده، یا عدم تطابق تأیید وجود داشته است." "صحت‌سنجی شکست خورد" + "فقط در صورتی ادامه دهید که خودتان این تأیید را آغاز کرده باشید." + "برای ایمن نگه داشتن تاریخچه پیام‌هایتان، دستگاه دیگر را تأیید کنید." "اکنون می‌توانید روی افزارهٔ دیگرتان با امنیت پیام فرستاده و بخوانید." "افزاره تأیید شده" + "درخواست تأیید" "مطابق نیستند" "مطابقند" + "قبل از شروع تأیید از اینجا، مطمئن شوید که برنامه را در دستگاه دیگر باز کرده‌اید." + "برنامه را روی دستگاه تأیید شده دیگری باز کنید" + "برای امنیت بیشتر، با مقایسه مجموعه‌ای از ایموجی‌ها در دستگاه‌های خود، این کاربر را تأیید کنید. این کار را با استفاده از یک روش ارتباطی مطمئن انجام دهید." + "این کاربر را تایید می‌کنید؟" + "برای امنیت بیشتر، اگر کاربر دیگری بخواهد هویت دیجیتالی شما را تأیید کند، مجموعه‌ای از ایموجی‌ها برای مقایسه به شما نشان داده می‌شود." + "باید یک پنجره‌ی پاپ‌آپ روی دستگاه دیگر ببینید. اکنون تأیید را از آنجا شروع کنید." + "شروع تأیید در دستگاه دیگر" + "شروع تأیید در دستگاه دیگر" + "در انتظار کاربر دیگر" + "پس از پذیرش، می‌توانید به تأیید ادامه دهید." "برای ادامه، درخواست شروع فرآیند تأیید را در جلسه دیگر خود بپذیرید." "منظر پذیرش درخواست" "برداشتن افزاره…" diff --git a/features/verifysession/impl/src/main/res/values-pl/translations.xml b/features/verifysession/impl/src/main/res/values-pl/translations.xml index 39ce9f6fa3..01a9325ceb 100644 --- a/features/verifysession/impl/src/main/res/values-pl/translations.xml +++ b/features/verifysession/impl/src/main/res/values-pl/translations.xml @@ -11,16 +11,16 @@ "Użyj innego urządzenia" "Oczekiwanie na inne urządzenie…" "Coś tu nie gra. Albo upłynął limit czasu, albo żądanie zostało odrzucone." - "Upewnij się, że emoji poniżej pasują do tych pokazanych na innej sesji." + "Upewnij się, że zestaw emoji poniżej pasuje do tych na drugiej sesji." "Porównaj emoji" "Upewnij się, że emoji poniżej odpowiadają tym na urządzeniu drugiego użytkownika." - "Upewnij się, że liczby poniżej pasują do tych wyświetlanych na innej sesji." + "Upewnij się, że liczby poniżej pasują do tych wyświetlanych na drugiej sesji." "Porównaj liczby" "Teraz możesz bezpiecznie czytać i wysyłać wiadomości na swoim drugim urządzeniu." "Teraz możesz zaufać tożsamości tego użytkownika podczas wysyłania lub odbierania wiadomości." "Urządzenie zweryfikowane" "Wprowadź klucz przywracania" - "Albo upłynął limit czasu żądania, albo żądanie zostało odrzucone, albo wystąpił błąd weryfikacji." + "Upłynął limit czasu żądania, żądanie zostało odrzucone lub wystąpił błąd weryfikacji." "Udowodnij, że to ty, aby uzyskać dostęp do historii zaszyfrowanych wiadomości." "Otwórz istniejącą sesję" "Ponów weryfikację" @@ -29,9 +29,9 @@ "Porównaj unikalny zestaw emoji." "Porównaj unikalny zestaw emoji i upewnij się, że są w tej samej kolejności." "Zalogowano" - "Albo upłynął limit czasu żądania, albo żądanie zostało odrzucone, albo wystąpił błąd weryfikacji." + "Upłynął limit czasu żądania, żądanie zostało odrzucone lub wystąpił błąd weryfikacji." "Weryfikacja nie powiodła się" - "Kontynuuj tylko, jeśli to Ty zainicjowałeś tę weryfikację." + "Kontynuuj tylko jeśli to Ty zainicjowałeś proces weryfikacji." "Zweryfikuj drugie urządzenie, aby zabezpieczyć historię wiadomości." "Teraz możesz bezpiecznie czytać i wysyłać wiadomości na swoim drugim urządzeniu." "Urządzenie zweryfikowane" diff --git a/features/verifysession/impl/src/test/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationPresenterTest.kt b/features/verifysession/impl/src/test/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationPresenterTest.kt index c6cbfca281..577683d12e 100644 --- a/features/verifysession/impl/src/test/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationPresenterTest.kt +++ b/features/verifysession/impl/src/test/kotlin/io/element/android/features/verifysession/impl/outgoing/OutgoingVerificationPresenterTest.kt @@ -16,6 +16,7 @@ import io.element.android.features.verifysession.impl.outgoing.OutgoingVerificat import io.element.android.libraries.architecture.AsyncData import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.encryption.EncryptionService +import io.element.android.libraries.matrix.api.encryption.RecoveryState import io.element.android.libraries.matrix.api.verification.SessionVerificationData import io.element.android.libraries.matrix.api.verification.SessionVerificationService import io.element.android.libraries.matrix.api.verification.SessionVerifiedStatus @@ -216,6 +217,85 @@ class OutgoingVerificationPresenterTest { } } + @Test + fun `present - When verification is approved and a backup exists but recovery is disabled, the flow completes`() = runTest { + val service = unverifiedSessionService( + requestUserVerificationLambda = { }, + startSasVerificationLambda = { }, + approveVerificationLambda = { }, + ) + val encryptionService = FakeEncryptionService().apply { + givenDoesBackupExistOnServerResult(Result.success(true)) + recoveryStateStateFlow.value = RecoveryState.DISABLED + } + val presenter = createOutgoingVerificationPresenter( + service = service, + verificationRequest = anOutgoingUserVerificationRequest(), + encryptionService = encryptionService, + ) + presenter.test { + val state = requestVerificationAndAwaitVerifyingState(service) + state.eventSink(OutgoingVerificationViewEvents.ConfirmVerification) + assertThat(awaitItem().step).isInstanceOf(Step.Verifying::class.java) + service.emitVerificationFlowState(VerificationFlowState.DidFinish) + assertThat(awaitItem().step).isEqualTo(Step.Completed) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - When verification is approved and a backup exists but recovery is incomplete, the flow completes`() = runTest { + val service = unverifiedSessionService( + requestUserVerificationLambda = { }, + startSasVerificationLambda = { }, + approveVerificationLambda = { }, + ) + val encryptionService = FakeEncryptionService().apply { + givenDoesBackupExistOnServerResult(Result.success(true)) + recoveryStateStateFlow.value = RecoveryState.INCOMPLETE + } + val presenter = createOutgoingVerificationPresenter( + service = service, + verificationRequest = anOutgoingUserVerificationRequest(), + encryptionService = encryptionService, + ) + presenter.test { + val state = requestVerificationAndAwaitVerifyingState(service) + state.eventSink(OutgoingVerificationViewEvents.ConfirmVerification) + assertThat(awaitItem().step).isInstanceOf(Step.Verifying::class.java) + service.emitVerificationFlowState(VerificationFlowState.DidFinish) + assertThat(awaitItem().step).isEqualTo(Step.Completed) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `present - When verification is approved but the recovery state is not determined, the flow completes after the timeout`() = runTest { + val service = unverifiedSessionService( + requestUserVerificationLambda = { }, + startSasVerificationLambda = { }, + approveVerificationLambda = { }, + ) + val encryptionService = FakeEncryptionService().apply { + givenDoesBackupExistOnServerResult(Result.success(true)) + } + val presenter = createOutgoingVerificationPresenter( + service = service, + verificationRequest = anOutgoingUserVerificationRequest(), + encryptionService = encryptionService, + ) + presenter.test { + val state = requestVerificationAndAwaitVerifyingState(service) + state.eventSink(OutgoingVerificationViewEvents.ConfirmVerification) + assertThat(awaitItem().step).isInstanceOf(Step.Verifying::class.java) + service.emitVerificationFlowState(VerificationFlowState.DidFinish) + // The recovery state never leaves UNKNOWN, so the 10 seconds timeout fires and the flow completes anyway + this@runTest.advanceUntilIdle() + assertThat(awaitItem().step).isEqualTo(Step.Completed) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `present - When verification is declined, the flow is canceled`() = runTest { val service = unverifiedSessionService( diff --git a/features/viewfolder/api/src/main/kotlin/io/element/android/features/viewfolder/api/TextFileViewer.kt b/features/viewfolder/api/src/main/kotlin/io/element/android/features/viewfolder/api/TextFileViewer.kt index 29a7c9f9e8..5abc27546d 100644 --- a/features/viewfolder/api/src/main/kotlin/io/element/android/features/viewfolder/api/TextFileViewer.kt +++ b/features/viewfolder/api/src/main/kotlin/io/element/android/features/viewfolder/api/TextFileViewer.kt @@ -12,7 +12,16 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import kotlinx.collections.immutable.ImmutableList +/** + * Renders the contents of a text file, used by the log viewer in the developer options. + */ fun interface TextFileViewer { + /** + * Draws the file, one row per line. + * + * @param lines the already-read contents of the file. + * @param modifier layout modifier for the container. + */ @Composable fun Render( lines: ImmutableList, diff --git a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileStateProvider.kt b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileStatePreviewParam.kt similarity index 97% rename from features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileStateProvider.kt rename to features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileStatePreviewParam.kt index 1b20b5c947..8420cf8fd6 100644 --- a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileStateProvider.kt +++ b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.features.viewfolder.impl.file import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncData -open class ViewFileStateProvider : PreviewParameterProvider { +open class ViewFileStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aViewFileState(), diff --git a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileView.kt b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileView.kt index 23f92fc9ba..8b44f12ba8 100644 --- a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileView.kt +++ b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/file/ViewFileView.kt @@ -92,7 +92,7 @@ fun ViewFileView( @PreviewsDayNight @Composable -internal fun ViewFileViewPreview(@PreviewParameter(ViewFileStateProvider::class) state: ViewFileState) = ElementPreview { +internal fun ViewFileViewPreview(@PreviewParameter(ViewFileStatePreviewParam::class) state: ViewFileState) = ElementPreview { ViewFileView( state = state, onBackClick = {}, diff --git a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderStateProvider.kt b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderStatePreviewParam.kt similarity index 92% rename from features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderStateProvider.kt rename to features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderStatePreviewParam.kt index 2debe4cbf8..0fad56fe40 100644 --- a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderStateProvider.kt +++ b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.features.viewfolder.impl.model.Item import kotlinx.collections.immutable.toImmutableList -open class ViewFolderStateProvider : PreviewParameterProvider { +open class ViewFolderStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aViewFolderState(), diff --git a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderView.kt b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderView.kt index 86cd5302c8..89fb3da7f4 100644 --- a/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderView.kt +++ b/features/viewfolder/impl/src/main/kotlin/io/element/android/features/viewfolder/impl/folder/ViewFolderView.kt @@ -142,7 +142,7 @@ private fun ItemRow( @PreviewsDayNight @Composable -internal fun ViewFolderViewPreview(@PreviewParameter(ViewFolderStateProvider::class) state: ViewFolderState) = ElementPreview { +internal fun ViewFolderViewPreview(@PreviewParameter(ViewFolderStatePreviewParam::class) state: ViewFolderState) = ElementPreview { ViewFolderView( state = state, onNavigateTo = {}, diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ce602f0e93..46890d253f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -7,22 +7,22 @@ android_gradle_plugin = "9.3.1" # When updating this, please also update the version in the file ./idea/kotlinc.xml kotlin = "2.4.10" kotlinpoet = "2.3.0" -ksp = "2.3.10" +ksp = "2.3.11" firebaseAppDistribution = "5.3.0" # AndroidX core = "1.18.0" datastore = "1.2.1" constraintlayout = "2.2.2" -constraintlayout_compose = "1.1.1" +constraintlayout_compose = "1.1.2" lifecycle = "2.11.0" activity = "1.13.0" -media3 = "1.10.1" +media3 = "1.11.0" camera = "1.6.1" work = "2.11.2" # Compose -compose_bom = "2026.06.01" +compose_bom = "2026.08.00" # Coroutines coroutines = "1.11.0" @@ -32,7 +32,7 @@ accompanist = "0.37.3" # Test test_core = "1.7.0" -roborazzi = "1.70.0" +roborazzi = "1.72.0" # Jetbrain datetime = "0.8.0" @@ -54,7 +54,7 @@ haze = "1.7.2" dependencyAnalysis = "3.18.0" # DI -metro = "1.4.0" +metro = "1.4.2" # Auto service autoservice = "1.1.1" @@ -123,7 +123,7 @@ androidx_activity_activity = { module = "androidx.activity:activity", version.re androidx_activity_compose = { module = "androidx.activity:activity-compose", version.ref = "activity" } androidx_startup = "androidx.startup:startup-runtime:1.2.0" androidx_preference = "androidx.preference:preference:1.2.1" -androidx_webkit = "androidx.webkit:webkit:1.16.0" +androidx_webkit = "androidx.webkit:webkit:1.17.0" androidx_compose_bom = { module = "androidx.compose:compose-bom", version.ref = "compose_bom" } androidx_compose_material3 = { module = "androidx.compose.material3:material3", version = '1.5.0-alpha23' } @@ -149,7 +149,7 @@ accompanist_permission = { module = "com.google.accompanist:accompanist-permissi squareup_seismic = "com.squareup:seismic:1.0.3" # network -network_okhttp_bom = "com.squareup.okhttp3:okhttp-bom:5.4.0" +network_okhttp_bom = "com.squareup.okhttp3:okhttp-bom:5.5.0" network_okhttp_logging = { module = "com.squareup.okhttp3:logging-interceptor" } network_okhttp_okhttp = { module = "com.squareup.okhttp3:okhttp" } network_okhttp = { module = "com.squareup.okhttp3:okhttp" } @@ -175,7 +175,7 @@ test_truth = "com.google.truth:truth:1.4.5" test_parameter_injector = "com.google.testparameterinjector:test-parameter-injector:1.22" test_robolectric = "org.robolectric:robolectric:4.16.1" test_appyx_junit = { module = "com.bumble.appyx:testing-junit4", version.ref = "appyx" } -test_composable_preview_scanner = "io.github.sergio-sastre.ComposablePreviewScanner:android:0.9.1" +test_composable_preview_scanner = "io.github.sergio-sastre.ComposablePreviewScanner:android:0.9.2" test_detekt_api = { module = "io.gitlab.arturbosch.detekt:detekt-api", version.ref = "detekt" } test_detekt_test = { module = "io.gitlab.arturbosch.detekt:detekt-test", version.ref = "detekt" } @@ -185,7 +185,7 @@ test_detekt_test = { module = "io.gitlab.arturbosch.detekt:detekt-test", version # https://github.com/matrix-org/matrix-rust-components-kotlin/commits/main/sdk/sdk-android/src/main/kotlin/org/matrix/rustcomponents/sdk/matrix_sdk_ffi.kt # All new features should not be implemented in the pull request that upgrades the version, developers should # only fix API breaks and may add some TODOs. -matrix_sdk = "org.matrix.rustcomponents:sdk-android:26.08.05" +matrix_sdk = "org.matrix.rustcomponents:sdk-android:26.08.19" # Others coil = { module = "io.coil-kt.coil3:coil", version.ref = "coil" } @@ -199,7 +199,7 @@ serialization_json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-jso kotlinx_collections_immutable = "org.jetbrains.kotlinx:kotlinx-collections-immutable:0.5.1" showkase = { module = "com.airbnb.android:showkase", version.ref = "showkase" } showkase_processor = { module = "com.airbnb.android:showkase-processor", version.ref = "showkase" } -jsoup = "org.jsoup:jsoup:1.22.2" +jsoup = "org.jsoup:jsoup:1.23.1" appyx_core = { module = "com.bumble.appyx:core", version.ref = "appyx" } molecule-runtime = "app.cash.molecule:molecule-runtime:2.2.0" timber = "com.jakewharton.timber:timber:5.0.1" @@ -215,14 +215,14 @@ vanniktech_blurhash = "com.vanniktech:blurhash:0.3.0" telephoto_zoomableimage = { module = "me.saket.telephoto:zoomable-image-coil3", version.ref = "telephoto" } telephoto_flick = { module = "me.saket.telephoto:flick-android", version.ref = "telephoto" } statemachine = "com.freeletics.flowredux:compose:1.2.2" -maplibre = "org.maplibre.gl:android-sdk:13.4.1" +maplibre = "org.maplibre.gl:android-sdk:13.5.0" maplibre_ktx = "org.maplibre.gl:android-sdk-ktx-v7:3.0.2" -maplibre_compose = "org.maplibre.compose:maplibre-compose:0.13.1" +maplibre_compose = "org.maplibre.compose:maplibre-compose:0.14.0" maplibre_annotation = "org.maplibre.gl:android-plugin-annotation-v9:3.0.2" opusencoder = "io.element.android:opusencoder:1.2.0" zxing_cpp = "io.github.zxing-cpp:android:3.1.1" google_zxing = "com.google.zxing:core:3.5.4" -google_guava = "com.google.guava:guava:33.6.0-android" +google_guava = "com.google.guava:guava:33.7.0-android" haze = { module = "dev.chrisbanes.haze:haze", version.ref = "haze" } haze_materials = { module = "dev.chrisbanes.haze:haze-materials", version.ref = "haze" } @@ -230,7 +230,7 @@ color_picker = "io.mhssn:colorpicker:1.0.0" # Analytics posthog = "com.posthog:posthog-android:3.56.4" -sentry = "io.sentry:sentry-android:8.51.0" +sentry = "io.sentry:sentry-android:8.53.0" # main branch can be tested replacing the version with main-SNAPSHOT matrix_analytics_events = "com.github.matrix-org:matrix-analytics-events:0.37.0" @@ -242,7 +242,7 @@ sigpwned_emoji4j = "com.sigpwned:emoji4j-core:16.0.0" metro_runtime = { module = "dev.zacsweers.metro:runtime", version.ref = "metro" } # Element Call -element_call_embedded = "io.element.android:element-call-embedded:0.23.0" +element_call_embedded = "io.element.android:element-call-embedded:0.24.0" # Auto services google_autoservice = { module = "com.google.auto.service:auto-service", version.ref = "autoservice" } @@ -270,13 +270,13 @@ metro = { id = "dev.zacsweers.metro", version.ref = "metro" } detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } ktlint = "org.jlleitschuh.gradle.ktlint:14.2.0" dependencygraph = "com.savvasdalkitsis.module-dependency-graph:0.12" -dependencycheck = "org.owasp.dependencycheck:12.2.2" +dependencycheck = "org.owasp.dependencycheck:13.0.0" dependencyanalysis = { id = "com.autonomousapps.dependency-analysis", version.ref = "dependencyAnalysis" } paparazzi = "app.cash.paparazzi:2.0.0-alpha05" roborazzi = { id = "io.github.takahirom.roborazzi", version.ref = "roborazzi" } sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" } firebaseAppDistribution = { id = "com.google.firebase.appdistribution", version.ref = "firebaseAppDistribution" } -sonarqube = "org.sonarqube:7.3.1.8318" +sonarqube = "org.sonarqube:7.4.0.8496" licensee = "app.cash.licensee:1.14.1" compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } gms_google_services = { id = "com.google.gms.google-services", version = "4.5.0" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 84c5a9c661..760c45969c 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionSha256Sum=84fbba45c7f4c64abc77460e1c00f541e9f960e3c7ed2538f1ede19eacd873ae -distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.0-bin.zip +distributionSha256Sum=acd53f1edaf02f1a8ff99879f8a34b302661a057d9b063ae9e35b552f804d20a +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip networkTimeout=10000 retries=0 retryBackOffMs=500 diff --git a/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectStateProvider.kt b/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectStatePreviewParam.kt similarity index 90% rename from libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectStateProvider.kt rename to libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectStatePreviewParam.kt index 0c12d34352..78c2f895dd 100644 --- a/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectStateProvider.kt +++ b/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectStatePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.ui.components.aMatrixUserList import kotlinx.collections.immutable.toImmutableList -open class AccountSelectStateProvider : PreviewParameterProvider { +open class AccountSelectStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAccountSelectState(), diff --git a/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectView.kt b/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectView.kt index bfa1bf45b6..74f15f8cfa 100644 --- a/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectView.kt +++ b/libraries/accountselect/impl/src/main/kotlin/io/element/android/libraries/accountselect/impl/AccountSelectView.kt @@ -80,7 +80,7 @@ fun AccountSelectView( @PreviewsDayNight @Composable -internal fun AccountSelectViewPreview(@PreviewParameter(AccountSelectStateProvider::class) state: AccountSelectState) = ElementPreview { +internal fun AccountSelectViewPreview(@PreviewParameter(AccountSelectStatePreviewParam::class) state: AccountSelectState) = ElementPreview { AccountSelectView( state = state, onSelectAccount = {}, diff --git a/libraries/accountselect/test/build.gradle.kts b/libraries/accountselect/test/build.gradle.kts new file mode 100644 index 0000000000..c38cd8ac69 --- /dev/null +++ b/libraries/accountselect/test/build.gradle.kts @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ +plugins { + id("io.element.android-library") +} + +android { + namespace = "io.element.android.libraries.accountselect.test" +} + +dependencies { + implementation(projects.libraries.architecture) + implementation(projects.libraries.accountselect.api) + implementation(projects.tests.testutils) +} diff --git a/libraries/accountselect/test/src/main/kotlin/io/element/android/libraries/accountselect/test/FakeAccountSelectEntryPoint.kt b/libraries/accountselect/test/src/main/kotlin/io/element/android/libraries/accountselect/test/FakeAccountSelectEntryPoint.kt new file mode 100644 index 0000000000..acc5ba10df --- /dev/null +++ b/libraries/accountselect/test/src/main/kotlin/io/element/android/libraries/accountselect/test/FakeAccountSelectEntryPoint.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.accountselect.test + +import com.bumble.appyx.core.modality.BuildContext +import com.bumble.appyx.core.node.Node +import io.element.android.libraries.accountselect.api.AccountSelectEntryPoint +import io.element.android.tests.testutils.lambda.lambdaError + +class FakeAccountSelectEntryPoint( + private val createNodeResult: (BuildContext, AccountSelectEntryPoint.Callback) -> Node = { _, _ -> lambdaError() }, +) : AccountSelectEntryPoint { + override fun createNode( + parentNode: Node, + buildContext: BuildContext, + callback: AccountSelectEntryPoint.Callback, + ): Node = createNodeResult(buildContext, callback) +} diff --git a/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/media/PictureInPictureParamsExt.kt b/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/media/PictureInPictureParamsExt.kt new file mode 100644 index 0000000000..b17ec0260b --- /dev/null +++ b/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/media/PictureInPictureParamsExt.kt @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.androidutils.media + +import android.app.PictureInPictureParams +import android.content.res.Configuration +import android.os.Build +import android.util.Rational +import androidx.annotation.RequiresApi + +/** + * Set the aspect ratio of the Picture-in-Picture mode based on the current orientation of the other user's device. + */ +@RequiresApi(Build.VERSION_CODES.O) +fun PictureInPictureParams.Builder.setAspectRatioFromOrientation(orientation: Int): PictureInPictureParams.Builder { + val aspectRatio = if (orientation == Configuration.ORIENTATION_LANDSCAPE) { + // If landscape orientation, invert the aspect ratio + Rational(5, 3) + } else { + // In any other case, assume portrait orientation + Rational(3, 5) + } + return setAspectRatio(aspectRatio) +} diff --git a/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/LinkifyHelper.kt b/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/LinkifyHelper.kt index 441f819546..090936910e 100644 --- a/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/LinkifyHelper.kt +++ b/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/LinkifyHelper.kt @@ -16,6 +16,7 @@ import androidx.core.text.toSpannable import androidx.core.text.util.LinkifyCompat import io.element.android.libraries.core.extensions.runCatchingExceptions import timber.log.Timber +import java.net.URI /** * Helper class to linkify text while preserving existing URL spans. @@ -23,6 +24,8 @@ import timber.log.Timber * It also checks the linkified results to make sure URLs spans are not including trailing punctuation. */ object LinkifyHelper { + private val BRACKETED_AUTHORITY_URL_REGEX = Regex("""(?(start, newEnd)) { + spannable.removeSpan(span) + } + spannable.setSpan(URLSpan(url), start, newEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + } + // Restore old spans, remove new ones if there is a conflict for ((urlSpan, location) in oldURLSpans) { val (start, end) = location @@ -82,6 +108,15 @@ object LinkifyHelper { return spannable } + private fun String.hasBracketedHost(): Boolean { + val host = runCatchingExceptions { URI(this) }.getOrNull()?.host ?: return false + return host.startsWith('[') && host.endsWith(']') + } + + private fun Spannable.isEmailInsideFediverseHandle(urlSpan: URLSpan, start: Int): Boolean { + return urlSpan.url.startsWith("mailto:") && start > 0 && this[start - 1] == '@' + } + private fun adjustLinkifiedUrlSpanEndIndex(spannable: Spannable, start: Int, end: Int): Int { var end = end diff --git a/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/TextUtils.kt b/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/TextUtils.kt index dde63e79a6..5e78c3c1ac 100644 --- a/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/TextUtils.kt +++ b/libraries/androidutils/src/main/kotlin/io/element/android/libraries/androidutils/text/TextUtils.kt @@ -13,3 +13,5 @@ import java.nio.charset.Charset fun String.urlEncoded(charset: Charset = Charsets.UTF_8): String = URLEncoder.encode(this, charset.name()) fun String.urlDecoded(charset: Charset = Charsets.UTF_8): String = URLDecoder.decode(this, charset.name()) + +fun String.takeIfNotBlank(): String? = ifBlank { null } diff --git a/libraries/androidutils/src/main/res/values-ar/translations.xml b/libraries/androidutils/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..6449b128d1 --- /dev/null +++ b/libraries/androidutils/src/main/res/values-ar/translations.xml @@ -0,0 +1,4 @@ + + + "لم يُعثر على تطبيق ليتعامل مع هذا الحدث." + diff --git a/libraries/androidutils/src/test/kotlin/io/element/android/libraries/androidutils/text/LinkifierHelperTest.kt b/libraries/androidutils/src/test/kotlin/io/element/android/libraries/androidutils/text/LinkifierHelperTest.kt index bb7a272908..130d640d4a 100644 --- a/libraries/androidutils/src/test/kotlin/io/element/android/libraries/androidutils/text/LinkifierHelperTest.kt +++ b/libraries/androidutils/src/test/kotlin/io/element/android/libraries/androidutils/text/LinkifierHelperTest.kt @@ -36,6 +36,60 @@ class LinkifierHelperTest : RobolectricTest() { assertThat(urlSpans.first().url).isEqualTo("https://matrix.org") } + @Test + fun `linkification finds ipv6 URL`() { + val text = "A url http://[2001:db8::1]:8008/path" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans.size).isEqualTo(1) + assertThat(urlSpans.first().url).isEqualTo("http://[2001:db8::1]:8008/path") + } + + @Test + @Config(sdk = [30]) + fun `linkification of an ipv6 URL does not leave a phone number span`() { + shadowOf(newInstanceOf(TelephonyManager::class.java)).setSimCountryIso("DE") + val text = "A url http://[2001:db8::1]:8008/path" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans.size).isEqualTo(1) + assertThat(urlSpans.first().url).isEqualTo("http://[2001:db8::1]:8008/path") + } + + @Test + fun `linkification of an ipv6 URL trims trailing punctuation`() { + val text = "A url http://[::1]/x." + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans.size).isEqualTo(1) + assertThat(urlSpans.first().url).isEqualTo("http://[::1]/x") + } + + @Test + fun `linkification finds an ipv6 URL of any scheme`() { + val text = "A url ssh://[2001:db8::1]/path" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans.size).isEqualTo(1) + assertThat(urlSpans.first().url).isEqualTo("ssh://[2001:db8::1]/path") + } + + @Test + fun `linkification ignores a bracketed authority which is not an address`() { + val text = "A url http://[not-an-address]/path" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans).isEmpty() + } + + @Test + fun `linkification ignores bracketed text which is not a URL`() { + val text = "An array values[0]:1 and a bare [::1]" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans).isEmpty() + } + @Test fun `linkification finds partial URL`() { val text = "A partial url matrix.org/test" @@ -87,6 +141,45 @@ class LinkifierHelperTest : RobolectricTest() { assertThat(urlSpans.first().url).isEqualTo("tel:1234") } + @Test + fun `linkification ignores fediverse handle`() { + val text = "Follow me at @name@server.tld" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans).isEmpty() + } + + @Test + fun `linkification ignores fediverse handle at the start of the text`() { + val text = "@name@server.tld posted this" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans).isEmpty() + } + + @Test + fun `linkification finds email next to a fediverse handle`() { + val text = "@name@server.tld and john@doe.com" + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans.size).isEqualTo(1) + assertThat(urlSpans.first().url).isEqualTo("mailto:john@doe.com") + } + + @Test + fun `linkification keeps an existing mailto span preceded by an at sign`() { + val text = buildSpannedString { + append("Mail me @") + inSpans(URLSpan("mailto:john@doe.com")) { + append("john@doe.com") + } + } + val result = LinkifyHelper.linkify(text) + val urlSpans = result.toSpannable().getSpans() + assertThat(urlSpans.size).isEqualTo(1) + assertThat(urlSpans.first().url).isEqualTo("mailto:john@doe.com") + } + @Test fun `linkification handles trailing dot`() { val text = "A url https://matrix.org." diff --git a/libraries/audio/api/src/main/kotlin/io/element/android/libraries/audio/api/AudioFocus.kt b/libraries/audio/api/src/main/kotlin/io/element/android/libraries/audio/api/AudioFocus.kt index aeccaa9b8a..de2e5844d5 100644 --- a/libraries/audio/api/src/main/kotlin/io/element/android/libraries/audio/api/AudioFocus.kt +++ b/libraries/audio/api/src/main/kotlin/io/element/android/libraries/audio/api/AudioFocus.kt @@ -15,6 +15,9 @@ enum class AudioFocusRequester { MediaViewer, } +/** + * Claims and releases system audio focus, so that the app's own players do not talk over each other or over other apps. + */ interface AudioFocus { /** * Request audio focus for the given requester. diff --git a/libraries/audio/impl/build.gradle.kts b/libraries/audio/impl/build.gradle.kts index 419e81962c..c0db3c4f86 100644 --- a/libraries/audio/impl/build.gradle.kts +++ b/libraries/audio/impl/build.gradle.kts @@ -1,4 +1,5 @@ import extension.setupDependencyInjection +import extension.testCommonDependencies /* * Copyright (c) 2025 Element Creations Ltd. @@ -22,4 +23,6 @@ dependencies { implementation(libs.androidx.corektx) implementation(projects.libraries.di) + + testCommonDependencies(libs) } diff --git a/libraries/audio/impl/src/main/kotlin/io/element/android/libraries/audio/impl/DefaultAudioFocus.kt b/libraries/audio/impl/src/main/kotlin/io/element/android/libraries/audio/impl/DefaultAudioFocus.kt index bc6a42d2f9..a9bc6fdbfd 100644 --- a/libraries/audio/impl/src/main/kotlin/io/element/android/libraries/audio/impl/DefaultAudioFocus.kt +++ b/libraries/audio/impl/src/main/kotlin/io/element/android/libraries/audio/impl/DefaultAudioFocus.kt @@ -48,9 +48,8 @@ class DefaultAudioFocus( } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { - // For recording, ignore transient focus losses (e.g., notification sounds). - // The AudioRecord API keeps capturing regardless. - if (requester != AudioFocusRequester.RecordVoiceMessage) { + Timber.d("AudioFocus: transient loss ($it)") + if (requester.pausesOnTransientFocusLoss()) { onFocusLost() } } @@ -96,8 +95,8 @@ class DefaultAudioFocus( private fun AudioFocusRequester.toAudioUsage(): Int { return when (this) { AudioFocusRequester.ElementCall, - AudioFocusRequester.VoiceMessage, AudioFocusRequester.RecordVoiceMessage -> AudioAttributes.USAGE_VOICE_COMMUNICATION + AudioFocusRequester.VoiceMessage, AudioFocusRequester.MediaViewer -> AudioAttributes.USAGE_MEDIA } } @@ -105,12 +104,22 @@ private fun AudioFocusRequester.toAudioUsage(): Int { private fun AudioFocusRequester.toAudioStream(): Int { return when (this) { AudioFocusRequester.ElementCall, - AudioFocusRequester.VoiceMessage, AudioFocusRequester.RecordVoiceMessage -> AudioManager.STREAM_VOICE_CALL + AudioFocusRequester.VoiceMessage, AudioFocusRequester.MediaViewer -> AudioManager.STREAM_MUSIC } } +private fun AudioFocusRequester.pausesOnTransientFocusLoss(): Boolean { + return when (this) { + // The AudioRecord API keeps capturing regardless. + AudioFocusRequester.RecordVoiceMessage, + AudioFocusRequester.VoiceMessage -> false + AudioFocusRequester.ElementCall, + AudioFocusRequester.MediaViewer -> true + } +} + private fun AudioFocusRequester.willPausedWhenDucked(): Boolean { return when (this) { // (note that for Element Call, there is no action when the focus is lost) diff --git a/libraries/audio/impl/src/test/kotlin/io/element/android/libraries/audio/impl/DefaultAudioFocusTest.kt b/libraries/audio/impl/src/test/kotlin/io/element/android/libraries/audio/impl/DefaultAudioFocusTest.kt new file mode 100644 index 0000000000..d0e255dd41 --- /dev/null +++ b/libraries/audio/impl/src/test/kotlin/io/element/android/libraries/audio/impl/DefaultAudioFocusTest.kt @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * Copyright 2026 New Vector Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.audio.impl + +import android.media.AudioAttributes +import android.media.AudioManager +import androidx.core.content.getSystemService +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.audio.api.AudioFocusRequester +import io.element.android.tests.testutils.robolectric.RobolectricTest +import org.junit.Test +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf + +class DefaultAudioFocusTest : RobolectricTest() { + @Test + fun `voice message playback requests focus for media, not for a call`() { + assertThat(usageOf(AudioFocusRequester.VoiceMessage)).isEqualTo(AudioAttributes.USAGE_MEDIA) + } + + @Test + fun `media viewer playback requests focus for media`() { + assertThat(usageOf(AudioFocusRequester.MediaViewer)).isEqualTo(AudioAttributes.USAGE_MEDIA) + } + + @Test + fun `voice message recording requests focus for voice communication`() { + assertThat(usageOf(AudioFocusRequester.RecordVoiceMessage)).isEqualTo(AudioAttributes.USAGE_VOICE_COMMUNICATION) + } + + @Test + fun `element call requests focus for voice communication`() { + assertThat(usageOf(AudioFocusRequester.ElementCall)).isEqualTo(AudioAttributes.USAGE_VOICE_COMMUNICATION) + } + + @Test + fun `a transient focus loss does not pause a voice message`() { + assertThat(losesFocusOn(AudioFocusRequester.VoiceMessage, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)).isFalse() + assertThat(losesFocusOn(AudioFocusRequester.VoiceMessage, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)).isFalse() + } + + @Test + fun `a permanent focus loss pauses a voice message`() { + assertThat(losesFocusOn(AudioFocusRequester.VoiceMessage, AudioManager.AUDIOFOCUS_LOSS)).isTrue() + } + + @Test + fun `a transient focus loss does not stop a voice message recording`() { + assertThat(losesFocusOn(AudioFocusRequester.RecordVoiceMessage, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)).isFalse() + } + + @Test + fun `a transient focus loss still pauses the media viewer`() { + assertThat(losesFocusOn(AudioFocusRequester.MediaViewer, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)).isTrue() + } + + private fun losesFocusOn(requester: AudioFocusRequester, focusChange: Int): Boolean { + val context = RuntimeEnvironment.getApplication() + val audioManager = requireNotNull(context.getSystemService()) + var focusLost = false + DefaultAudioFocus(context).requestAudioFocus(requester) { focusLost = true } + val request = requireNotNull(shadowOf(audioManager).lastAudioFocusRequest) + request.listener.onAudioFocusChange(focusChange) + return focusLost + } + + private fun usageOf(requester: AudioFocusRequester): Int { + val context = RuntimeEnvironment.getApplication() + val audioManager = requireNotNull(context.getSystemService()) + DefaultAudioFocus(context).requestAudioFocus(requester) {} + val request = requireNotNull(shadowOf(audioManager).lastAudioFocusRequest) + return requireNotNull(request.audioFocusRequest).audioAttributes.usage + } +} diff --git a/libraries/cachestore/api/src/main/kotlin/io/element/android/libraries/cachestore/api/CacheStore.kt b/libraries/cachestore/api/src/main/kotlin/io/element/android/libraries/cachestore/api/CacheStore.kt index 5df446f688..bbfb7d3405 100644 --- a/libraries/cachestore/api/src/main/kotlin/io/element/android/libraries/cachestore/api/CacheStore.kt +++ b/libraries/cachestore/api/src/main/kotlin/io/element/android/libraries/cachestore/api/CacheStore.kt @@ -7,9 +7,33 @@ package io.element.android.libraries.cachestore.api +/** + * A generic on-disk key/value cache, where each entry records when it was written so callers can decide for themselves when it is stale. + */ interface CacheStore { + /** + * Stores an entry, replacing any previous one under the same key. + * + * @param key the entry to write. + * @param data the value along with the time it was obtained. + */ suspend fun storeData(key: String, data: CacheData) + + /** + * Reads an entry without applying any expiry of its own; judging staleness is up to the caller. + * + * @param key the entry to read. + * @return the value and its timestamp, or `null` when nothing is stored under that key. + */ suspend fun getData(key: String): CacheData? + + /** + * Removes one entry. + * + * @param key the entry to delete. + */ suspend fun deleteData(key: String) + + /** Empties the whole cache. */ suspend fun deleteAll() } diff --git a/libraries/cachestore/impl/src/main/kotlin/io/element/android/libraries/cachestore/impl/di/CacheStoreModule.kt b/libraries/cachestore/impl/src/main/kotlin/io/element/android/libraries/cachestore/impl/di/CacheStoreBindingContainer.kt similarity index 96% rename from libraries/cachestore/impl/src/main/kotlin/io/element/android/libraries/cachestore/impl/di/CacheStoreModule.kt rename to libraries/cachestore/impl/src/main/kotlin/io/element/android/libraries/cachestore/impl/di/CacheStoreBindingContainer.kt index 89de82a08f..c28cc0601c 100644 --- a/libraries/cachestore/impl/src/main/kotlin/io/element/android/libraries/cachestore/impl/di/CacheStoreModule.kt +++ b/libraries/cachestore/impl/src/main/kotlin/io/element/android/libraries/cachestore/impl/di/CacheStoreBindingContainer.kt @@ -22,10 +22,10 @@ import timber.log.Timber @BindingContainer @ContributesTo(AppScope::class) -object CacheStoreModule { +object CacheStoreBindingContainer { @Provides @SingleIn(AppScope::class) - fun provideCacheDatabase( + fun providesCacheDatabase( @ApplicationContext context: Context, ): CacheDatabase { val name = "cache_database" diff --git a/libraries/compound/src/main/kotlin/io/element/android/compound/theme/Theme.kt b/libraries/compound/src/main/kotlin/io/element/android/compound/theme/Theme.kt index bf5932da59..e519984e9f 100644 --- a/libraries/compound/src/main/kotlin/io/element/android/compound/theme/Theme.kt +++ b/libraries/compound/src/main/kotlin/io/element/android/compound/theme/Theme.kt @@ -8,8 +8,11 @@ package io.element.android.compound.theme -import androidx.compose.foundation.isSystemInDarkTheme +import android.content.res.Configuration import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map @@ -27,12 +30,28 @@ private fun Theme.coerceBlackTheme(allowBlackTheme: Boolean): Theme { @Composable fun Theme.isDark(): Boolean { return when (this) { - Theme.System -> isSystemInDarkTheme() + Theme.System -> isSystemThemeDark() Theme.Dark, Theme.Black -> true Theme.Light -> false } } +/** + * Whether the system-wide theme is dark. + * + * This deliberately does not use [androidx.compose.foundation.isSystemInDarkTheme], which reads the activity configuration: `AppCompatDelegate` rewrites + * that configuration whenever a non-system theme is selected, so it keeps reporting the previously forced value. The application configuration is left + * untouched by AppCompat and is what AppCompat itself reads to expand `MODE_NIGHT_FOLLOW_SYSTEM`. + */ +@Composable +private fun isSystemThemeDark(): Boolean { + val applicationContext = LocalContext.current.applicationContext + val activityConfiguration = LocalConfiguration.current + return remember(activityConfiguration) { + applicationContext.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES + } +} + fun Flow.mapToTheme(allowBlackTheme: Boolean): Flow = map { when (it) { null -> Theme.System diff --git a/libraries/compound/src/test/kotlin/io/element/android/compound/theme/ThemeTest.kt b/libraries/compound/src/test/kotlin/io/element/android/compound/theme/ThemeTest.kt index 3f43cfea67..57ae9dd332 100644 --- a/libraries/compound/src/test/kotlin/io/element/android/compound/theme/ThemeTest.kt +++ b/libraries/compound/src/test/kotlin/io/element/android/compound/theme/ThemeTest.kt @@ -11,19 +11,22 @@ package io.element.android.compound.theme import android.content.res.Configuration import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext import app.cash.molecule.RecompositionMode import app.cash.molecule.moleculeFlow import app.cash.turbine.test import com.google.common.truth.Truth.assertThat +import io.element.android.tests.testutils.robolectric.RobolectricTest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Test +import org.robolectric.RuntimeEnvironment -class ThemeTest { +class ThemeTest : RobolectricTest() { @Test fun `isDark for System dark returns true`() { `isDark for System`( - uiMode = Configuration.UI_MODE_NIGHT_YES, + systemUiMode = Configuration.UI_MODE_NIGHT_YES, expected = true, ) } @@ -31,21 +34,38 @@ class ThemeTest { @Test fun `isDark for System light return false`() { `isDark for System`( - uiMode = Configuration.UI_MODE_NIGHT_NO, + systemUiMode = Configuration.UI_MODE_NIGHT_NO, expected = false, ) } - fun `isDark for System`( - uiMode: Int, + @Test + fun `isDark for System ignores the night mode AppCompat forced on the activity`() { + `isDark for System`( + systemUiMode = Configuration.UI_MODE_NIGHT_YES, + activityUiMode = Configuration.UI_MODE_NIGHT_NO, + expected = true, + ) + `isDark for System`( + systemUiMode = Configuration.UI_MODE_NIGHT_NO, + activityUiMode = Configuration.UI_MODE_NIGHT_YES, + expected = false, + ) + } + + private fun `isDark for System`( + systemUiMode: Int, + activityUiMode: Int = systemUiMode, expected: Boolean, ) = runTest { + val application = RuntimeEnvironment.getApplication() + application.resources.configuration.uiMode = systemUiMode moleculeFlow(RecompositionMode.Immediate) { var result: Boolean? = null CompositionLocalProvider( - // Let set the system to dark + LocalContext provides application, LocalConfiguration provides Configuration().apply { - this.uiMode = uiMode + this.uiMode = activityUiMode }, ) { result = Theme.System.isDark() diff --git a/libraries/core/src/main/kotlin/io/element/android/libraries/core/extensions/BasicExtensions.kt b/libraries/core/src/main/kotlin/io/element/android/libraries/core/extensions/BasicExtensions.kt index fe563138ad..87d6350c65 100644 --- a/libraries/core/src/main/kotlin/io/element/android/libraries/core/extensions/BasicExtensions.kt +++ b/libraries/core/src/main/kotlin/io/element/android/libraries/core/extensions/BasicExtensions.kt @@ -8,6 +8,7 @@ package io.element.android.libraries.core.extensions +import java.text.Normalizer import java.util.Locale fun Boolean.toOnOff() = if (this) "ON" else "OFF" @@ -114,3 +115,14 @@ fun String.toSafeLength( this } } + +/** + * Remove accents and replace special characters by ASCII from the string. + * For instance, "é" will be replaced by "e", "ç" by "c", etc. + */ +fun String.normalized(): String { + // Normalize the string. + return Normalizer.normalize(this, Normalizer.Form.NFD) + // then keep only ASCII characters and replace non-ASCII characters with an empty string. + .replace("[^\\p{ASCII}]".toRegex(), "") +} diff --git a/libraries/core/src/main/kotlin/io/element/android/libraries/core/mimetype/MimeTypes.kt b/libraries/core/src/main/kotlin/io/element/android/libraries/core/mimetype/MimeTypes.kt index e7962f8bd6..3901a32059 100644 --- a/libraries/core/src/main/kotlin/io/element/android/libraries/core/mimetype/MimeTypes.kt +++ b/libraries/core/src/main/kotlin/io/element/android/libraries/core/mimetype/MimeTypes.kt @@ -63,4 +63,17 @@ object MimeTypes { val subType = components.last() return subType.isNotBlank() && subType != "*" } + + /** + * A mime type with a wildcard subtype is a filter, not a media type, so replace it with a + * concrete default for its top level type. + */ + fun String?.ensureDefaultSubtype(): String = when { + this == null -> OctetStream + hasSubtype(this) -> this + this == Images -> Jpeg + this == Videos -> Mp4 + this == Audio -> Mp3 + else -> OctetStream + } } diff --git a/libraries/core/src/main/kotlin/io/element/android/libraries/core/uri/UrlUtils.kt b/libraries/core/src/main/kotlin/io/element/android/libraries/core/uri/UrlUtils.kt index 666ee1d7ab..91402e3d11 100644 --- a/libraries/core/src/main/kotlin/io/element/android/libraries/core/uri/UrlUtils.kt +++ b/libraries/core/src/main/kotlin/io/element/android/libraries/core/uri/UrlUtils.kt @@ -20,12 +20,13 @@ fun String.isValidUrl(): Boolean { } /** - * Ensure string starts with "http". If it is not the case, "https://" is added, only if the String is not empty + * Ensure string starts with "http" (case-insensitively, so "HTTP://" / "HTTPS://" are respected). If it is + * not the case, "https://" is added, only if the String is not empty. */ fun String.ensureProtocol(): String { return when { isEmpty() -> this - !startsWith("http") -> "https://$this" + !startsWith("http", ignoreCase = true) -> "https://$this" else -> this } } diff --git a/libraries/core/src/test/kotlin/io/element/android/libraries/core/extensions/BasicExtensionsTest.kt b/libraries/core/src/test/kotlin/io/element/android/libraries/core/extensions/BasicExtensionsTest.kt index 0099a67a79..c3cae14843 100644 --- a/libraries/core/src/test/kotlin/io/element/android/libraries/core/extensions/BasicExtensionsTest.kt +++ b/libraries/core/src/test/kotlin/io/element/android/libraries/core/extensions/BasicExtensionsTest.kt @@ -74,4 +74,10 @@ class BasicExtensionsTest { val result = textWithDirectionOverrides.filterDirectionOverrides() assertEquals("123456789", result) } + + @Test + fun `normalized removes accents and replace special characters from text`() { + assertEquals("Stefan", "Ștefan".normalized()) + assertEquals("ca enleve etre", "ça enlève être".normalized()) + } } diff --git a/libraries/core/src/test/kotlin/io/element/android/libraries/core/mimetype/MimeTypesTest.kt b/libraries/core/src/test/kotlin/io/element/android/libraries/core/mimetype/MimeTypesTest.kt new file mode 100644 index 0000000000..f12b73b40b --- /dev/null +++ b/libraries/core/src/test/kotlin/io/element/android/libraries/core/mimetype/MimeTypesTest.kt @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.core.mimetype + +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.core.mimetype.MimeTypes.ensureDefaultSubtype +import org.junit.Test + +class MimeTypesTest { + @Test + fun `ensureDefaultSubtype keeps a mime type that already has a subtype`() { + assertThat(MimeTypes.Png.ensureDefaultSubtype()).isEqualTo(MimeTypes.Png) + assertThat(MimeTypes.Mp4.ensureDefaultSubtype()).isEqualTo(MimeTypes.Mp4) + assertThat(MimeTypes.Pdf.ensureDefaultSubtype()).isEqualTo(MimeTypes.Pdf) + } + + @Test + fun `ensureDefaultSubtype replaces a wildcard subtype with a concrete one`() { + assertThat(MimeTypes.Images.ensureDefaultSubtype()).isEqualTo(MimeTypes.Jpeg) + assertThat(MimeTypes.Videos.ensureDefaultSubtype()).isEqualTo(MimeTypes.Mp4) + assertThat(MimeTypes.Audio.ensureDefaultSubtype()).isEqualTo(MimeTypes.Mp3) + } + + @Test + fun `ensureDefaultSubtype falls back to octet stream`() { + assertThat(MimeTypes.Any.ensureDefaultSubtype()).isEqualTo(MimeTypes.OctetStream) + assertThat("text/*".ensureDefaultSubtype()).isEqualTo(MimeTypes.OctetStream) + assertThat(null.ensureDefaultSubtype()).isEqualTo(MimeTypes.OctetStream) + } +} diff --git a/libraries/core/src/test/kotlin/io/element/android/libraries/core/uri/UrlUtilsTest.kt b/libraries/core/src/test/kotlin/io/element/android/libraries/core/uri/UrlUtilsTest.kt new file mode 100644 index 0000000000..9a9d68dcaa --- /dev/null +++ b/libraries/core/src/test/kotlin/io/element/android/libraries/core/uri/UrlUtilsTest.kt @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.core.uri + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class UrlUtilsTest { + @Test + fun `ensureProtocol keeps an empty string unchanged`() { + assertThat("".ensureProtocol()).isEqualTo("") + } + + @Test + fun `ensureProtocol prepends https when there is no scheme`() { + assertThat("matrix.org".ensureProtocol()).isEqualTo("https://matrix.org") + } + + @Test + fun `ensureProtocol keeps an existing http or https scheme`() { + assertThat("https://matrix.org".ensureProtocol()).isEqualTo("https://matrix.org") + assertThat("http://matrix.org".ensureProtocol()).isEqualTo("http://matrix.org") + } + + @Test + fun `ensureProtocol keeps an uppercase scheme rather than double-prepending`() { + assertThat("HTTPS://matrix.org".ensureProtocol()).isEqualTo("HTTPS://matrix.org") + assertThat("Http://matrix.org".ensureProtocol()).isEqualTo("Http://matrix.org") + } +} diff --git a/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/EncryptionDecryptionService.kt b/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/EncryptionDecryptionService.kt index fc882bc54b..1e2866a20f 100644 --- a/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/EncryptionDecryptionService.kt +++ b/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/EncryptionDecryptionService.kt @@ -15,8 +15,35 @@ import javax.crypto.SecretKey * Simple service to provide encryption and decryption operations. */ interface EncryptionDecryptionService { + /** + * Creates a cipher ready to encrypt, for the callers that need the cipher itself, such as to bind it to a biometric prompt. + * + * @param key the key to encrypt with. + */ fun createEncryptionCipher(key: SecretKey): Cipher + + /** + * Creates a cipher ready to decrypt, for the callers that need the cipher itself. + * + * @param key the key to decrypt with. + * @param initializationVector the vector produced when the data was encrypted. + */ fun createDecryptionCipher(key: SecretKey, initializationVector: ByteArray): Cipher + + /** + * Encrypts data in one call. + * + * @param key the key to encrypt with. + * @param input the plaintext bytes. + * @return the ciphertext along with the initialization vector needed to decrypt it. + */ fun encrypt(key: SecretKey, input: ByteArray): EncryptionResult + + /** + * Decrypts data in one call. + * + * @param key the key the data was encrypted with. + * @param encryptionResult the ciphertext and its initialization vector, as returned by [encrypt]. + */ fun decrypt(key: SecretKey, encryptionResult: EncryptionResult): ByteArray } diff --git a/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/SecretKeyRepository.kt b/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/SecretKeyRepository.kt index b210664d9f..c68f3170b9 100644 --- a/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/SecretKeyRepository.kt +++ b/libraries/cryptography/api/src/main/kotlin/io/element/android/libraries/cryptography/api/SecretKeyRepository.kt @@ -16,10 +16,17 @@ import javax.crypto.SecretKey * Implementation should be able to store the generated key securely. */ interface SecretKeyRepository { + /** + * Whether a key exists for the given alias, re-emitted when it is created or deleted. + * + * @param alias the alias to watch. + */ fun hasKey(alias: String): Flow /** * Get or create a secret key for a given alias. + * Note that [requiresUserAuthentication] only applies when the key is created: an existing key keeps the protection it was created with. + * * @param alias the alias to use * @param requiresUserAuthentication true if the key should be protected by user authentication */ diff --git a/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/KeyStoreSecretKeyRepository.kt b/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/KeyStoreSecretKeyRepository.kt index bcd38695c4..fe27c49f36 100644 --- a/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/KeyStoreSecretKeyRepository.kt +++ b/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/KeyStoreSecretKeyRepository.kt @@ -26,6 +26,8 @@ import java.util.concurrent.ConcurrentHashMap import javax.crypto.KeyGenerator import javax.crypto.SecretKey +internal const val ANDROID_KEYSTORE = "AndroidKeyStore" + /** * Default implementation of [SecretKeyRepository] that uses the Android Keystore to store the keys. * The generated key uses AES algorithm, with a key size of 128 bits, and the GCM block mode. diff --git a/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/CryptographyModule.kt b/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/di/CryptographyBindingContainer.kt similarity index 79% rename from libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/CryptographyModule.kt rename to libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/di/CryptographyBindingContainer.kt index e9a9eb7b34..bdfe6f9e5d 100644 --- a/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/CryptographyModule.kt +++ b/libraries/cryptography/impl/src/main/kotlin/io/element/android/libraries/cryptography/impl/di/CryptographyBindingContainer.kt @@ -6,19 +6,18 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.libraries.cryptography.impl +package io.element.android.libraries.cryptography.impl.di import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.BindingContainer import dev.zacsweers.metro.ContributesTo import dev.zacsweers.metro.Provides +import io.element.android.libraries.cryptography.impl.ANDROID_KEYSTORE import java.security.KeyStore -internal const val ANDROID_KEYSTORE = "AndroidKeyStore" - @ContributesTo(AppScope::class) @BindingContainer -object CryptographyModule { +object CryptographyBindingContainer { @Provides fun providesAndroidKeyStore(): KeyStore { return KeyStore.getInstance(ANDROID_KEYSTORE).apply { diff --git a/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DateFormatter.kt b/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DateFormatter.kt index 1f5c88f008..84cbf5efdd 100644 --- a/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DateFormatter.kt +++ b/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DateFormatter.kt @@ -8,7 +8,17 @@ package io.element.android.libraries.dateformatter.api +/** + * Formats timestamps for display, in the user's locale and time zone. + */ interface DateFormatter { + /** + * Formats a timestamp according to [mode]. + * + * @param timestamp milliseconds since the epoch; a `null` value yields an empty string, so callers need no null check of their own. + * @param mode how much of the date and time to include; see [DateFormatterMode] for examples of each. + * @param useRelative true to prefer wording relative to today, such as "Today" or "This month", where the mode allows it. + */ fun format( timestamp: Long?, mode: DateFormatterMode = DateFormatterMode.Full, diff --git a/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DurationFormatter.kt b/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DurationFormatter.kt index ac297d10e9..712355c423 100644 --- a/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DurationFormatter.kt +++ b/libraries/dateformatter/api/src/main/kotlin/io/element/android/libraries/dateformatter/api/DurationFormatter.kt @@ -21,6 +21,11 @@ import kotlin.time.Duration * - 30 seconds → "30 seconds" */ interface DurationFormatter { + /** + * Formats the duration using its largest appropriate unit, rounding rather than listing several units. + * + * @param duration the duration to describe. + */ fun format(duration: Duration): String } diff --git a/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/di/DateFormatterModule.kt b/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/di/DateFormatterBindingContainer.kt similarity index 84% rename from libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/di/DateFormatterModule.kt rename to libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/di/DateFormatterBindingContainer.kt index c80324c149..ee8afe678f 100644 --- a/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/di/DateFormatterModule.kt +++ b/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/di/DateFormatterBindingContainer.kt @@ -19,7 +19,7 @@ import kotlin.time.Clock @BindingContainer @ContributesTo(AppScope::class) -object DateFormatterModule { +object DateFormatterBindingContainer { @Provides fun providesClock(): Clock = Clock.System @@ -27,5 +27,5 @@ object DateFormatterModule { fun providesLocale(): Locale = Locale.getDefault() @Provides - fun providesTimezone(): TimezoneProvider = TimezoneProvider { TimeZone.currentSystemDefault() } + fun providesTimezoneProvider(): TimezoneProvider = TimezoneProvider { TimeZone.currentSystemDefault() } } diff --git a/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModeProvider.kt b/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModePreviewParam.kt similarity index 86% rename from libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModeProvider.kt rename to libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModePreviewParam.kt index 48856cad7b..f00911294e 100644 --- a/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModeProvider.kt +++ b/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.libraries.dateformatter.impl.previews import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.dateformatter.api.DateFormatterMode -class DateFormatterModeProvider : PreviewParameterProvider { +class DateFormatterModePreviewParam : PreviewParameterProvider { override val values: Sequence get() = DateFormatterMode.entries.asSequence() } diff --git a/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModeViewPreview.kt b/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModeViewPreview.kt index e3cd9563a8..5e1d35a568 100644 --- a/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModeViewPreview.kt +++ b/libraries/dateformatter/impl/src/main/kotlin/io/element/android/libraries/dateformatter/impl/previews/DateFormatterModeViewPreview.kt @@ -34,7 +34,7 @@ import kotlin.time.Instant @Preview @Composable internal fun DateFormatterModeViewPreview( - @PreviewParameter(DateFormatterModeProvider::class) dateFormatterMode: DateFormatterMode, + @PreviewParameter(DateFormatterModePreviewParam::class) dateFormatterMode: DateFormatterMode, ) = ElementPreview { DateFormatterModeView(dateFormatterMode) } diff --git a/libraries/dateformatter/impl/src/main/res/values-ar/translations.xml b/libraries/dateformatter/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..9e8f6c94d4 --- /dev/null +++ b/libraries/dateformatter/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,5 @@ + + + "%1$s في %2$s" + "هذا الشهر" + diff --git a/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeepLinkCreator.kt b/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeepLinkCreator.kt index 2b46b15e46..938939c6f0 100644 --- a/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeepLinkCreator.kt +++ b/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeepLinkCreator.kt @@ -13,6 +13,17 @@ import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.matrix.api.core.ThreadId +/** + * Builds the app's internal deep links, used to point a notification or a shortcut at a precise place in the app. + */ fun interface DeepLinkCreator { + /** + * Builds a link to the most precise target the arguments allow, ignoring the deeper ones once an outer one is `null`. + * + * @param sessionId the session to open. + * @param roomId the room to open, or `null` to stop at the room list. + * @param threadId the thread to open within that room, or `null` for the main timeline. + * @param eventId the event to focus on, or `null` to open at the latest message. + */ fun create(sessionId: SessionId, roomId: RoomId?, threadId: ThreadId?, eventId: EventId?): String } diff --git a/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeeplinkParser.kt b/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeeplinkParser.kt index f0f8640a2d..7a711d8a3a 100644 --- a/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeeplinkParser.kt +++ b/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/DeeplinkParser.kt @@ -10,6 +10,13 @@ package io.element.android.libraries.deeplink.api import android.content.Intent +/** + * Extracts the app's own deep link data from an incoming intent; see [DeepLinkCreator] for the other direction. + */ fun interface DeeplinkParser { + /** + * @param intent the intent the app was started or resumed with. + * @return the session, room and event to open, or `null` when the intent is not one of the app's deep links. + */ fun getFromIntent(intent: Intent): DeeplinkData? } diff --git a/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/usecase/InviteFriendsUseCase.kt b/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/usecase/InviteFriendsUseCase.kt index 64287f918c..2c4406a482 100644 --- a/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/usecase/InviteFriendsUseCase.kt +++ b/libraries/deeplink/api/src/main/kotlin/io/element/android/libraries/deeplink/api/usecase/InviteFriendsUseCase.kt @@ -10,6 +10,12 @@ package io.element.android.libraries.deeplink.api.usecase import android.app.Activity +/** + * Opens the system share sheet with an invitation to install the app. + */ fun interface InviteFriendsUseCase { + /** + * @param activity the activity the share sheet is shown from. + */ fun execute(activity: Activity) } diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMolecule.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMolecule.kt index 8b0f17177b..08d2f05fbc 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMolecule.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMolecule.kt @@ -134,7 +134,7 @@ enum class ComposerAlertLevel { @PreviewsDayNight @Composable internal fun ComposerAlertMoleculePreview( - @PreviewParameter(ComposerAlertMoleculeParamsProvider::class) params: ComposerAlertMoleculeParams, + @PreviewParameter(ComposerAlertMoleculeParamsPreviewParam::class) params: ComposerAlertMoleculeParams, ) = ElementPreview { ComposerAlertMolecule( avatar = params.avatar, diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMoleculeParamsProvider.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMoleculeParamsPreviewParam.kt similarity index 91% rename from libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMoleculeParamsProvider.kt rename to libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMoleculeParamsPreviewParam.kt index cd1bc8a02b..487cd06dfc 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMoleculeParamsProvider.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/atomic/molecules/ComposerAlertMoleculeParamsPreviewParam.kt @@ -19,7 +19,7 @@ internal data class ComposerAlertMoleculeParams( val showIcon: Boolean = false, ) -internal class ComposerAlertMoleculeParamsProvider : PreviewParameterProvider { +internal class ComposerAlertMoleculeParamsPreviewParam : PreviewParameterProvider { private val allLevels = sequenceOf( ComposerAlertLevel.Info, ComposerAlertLevel.Critical diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/BigIcon.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/BigIcon.kt index 639d365625..cf6329ee66 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/BigIcon.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/BigIcon.kt @@ -160,7 +160,7 @@ internal fun BigIconPreview() = ElementPreview { horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { - items(BigIconStyleProvider().values.toList()) { style -> + items(BigIconStylePreviewParam().values.toList()) { style -> Box( contentAlignment = Alignment.Center ) { @@ -170,7 +170,7 @@ internal fun BigIconPreview() = ElementPreview { } } -internal class BigIconStyleProvider : PreviewParameterProvider { +internal class BigIconStylePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( BigIcon.Style.Default(Icons.Filled.CatchingPokemon), diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionIndicator.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionIndicator.kt new file mode 100644 index 0000000000..f1a58c243f --- /dev/null +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionIndicator.kt @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.designsystem.components.async + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import io.element.android.libraries.architecture.AsyncAction +import kotlinx.coroutines.delay +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.TimeMark +import kotlin.time.TimeSource + +private val DefaultShowDelay = 300.milliseconds +private val DefaultMinDisplayDuration = 500.milliseconds +private val DefaultFailureDuration = 500.milliseconds + +/** + * An [AsyncIndicatorHost] driven by an [AsyncAction], with anti-flicker timing. + * + * While [asyncAction] is [AsyncAction.Loading], [loading] is displayed, but only if the operation + * runs longer than [showDelay]; once shown it stays visible for at least [minDisplayDuration]. This + * prevents the indicator from flashing for operations that complete almost instantly. + * + * When [asyncAction] is [AsyncAction.Failure], [failure] is displayed immediately (failures are + * never debounced) and auto-dismisses after [failureDuration]. + * + * @param asyncAction the action whose progress drives the indicator. + * @param loading the composable to display while loading. + * @param failure the composable to display on failure. + * @param modifier the modifier to apply to the underlying [AsyncIndicatorHost]. + * @param state the [AsyncIndicatorState] backing the host. + * @param showDelay how long the loading state must persist before the indicator is shown. + * @param minDisplayDuration the minimum duration the loading indicator stays visible once shown. + * @param failureDuration how long the failure indicator stays visible before auto-dismissing. + */ +@Composable +fun AsyncActionIndicator( + asyncAction: AsyncAction<*>, + loading: @Composable () -> Unit, + failure: @Composable (Throwable) -> Unit, + modifier: Modifier = Modifier, + state: AsyncIndicatorState = rememberAsyncIndicatorState(), + showDelay: Duration = DefaultShowDelay, + minDisplayDuration: Duration = DefaultMinDisplayDuration, + failureDuration: Duration = DefaultFailureDuration, +) { + AsyncIndicatorHost(modifier = modifier, state = state) + AsyncActionIndicatorEffect( + asyncAction = asyncAction, + state = state, + showDelay = showDelay, + minDisplayDuration = minDisplayDuration, + failureDuration = failureDuration, + loading = loading, + failure = failure, + ) +} + +@Composable +internal fun AsyncActionIndicatorEffect( + asyncAction: AsyncAction<*>, + state: AsyncIndicatorState, + showDelay: Duration, + minDisplayDuration: Duration, + failureDuration: Duration, + loading: @Composable () -> Unit, + failure: @Composable (Throwable) -> Unit, + timeSource: TimeSource = TimeSource.Monotonic, +) { + // Referenced inside the restarting LaunchedEffect below, so keep them up to date. + val currentLoading by rememberUpdatedState(loading) + val currentFailure by rememberUpdatedState(failure) + // Mark set when the loader actually becomes visible, null while it is hidden. + var loaderShownAt by remember { mutableStateOf(null) } + LaunchedEffect(asyncAction) { + when (asyncAction) { + is AsyncAction.Loading -> { + // If the operation completes before this delay elapses, the effect is cancelled + // and the loader is never shown. + delay(showDelay) + state.enqueue(composable = currentLoading) + loaderShownAt = timeSource.markNow() + } + is AsyncAction.Failure -> { + // Always surface failures immediately, even if the loader was never shown. + val error = asyncAction.error + state.enqueue(durationMs = failureDuration.inWholeMilliseconds, composable = { currentFailure(error) }) + loaderShownAt = null + } + is AsyncAction.Success -> { + // Hold the loader for its minimum duration before clearing it. + loaderShownAt?.let { shownAt -> + val remaining = minDisplayDuration - shownAt.elapsedNow() + if (remaining > Duration.ZERO) delay(remaining) + } + state.clear() + loaderShownAt = null + } + else -> Unit + } + } +} diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionProvider.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionPreviewParam.kt similarity index 90% rename from libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionProvider.kt rename to libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionPreviewParam.kt index 2f7439e1c8..9fe699b828 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionProvider.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionPreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.libraries.designsystem.components.async import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.architecture.AsyncAction -open class AsyncActionProvider : PreviewParameterProvider> { +open class AsyncActionPreviewParam : PreviewParameterProvider> { override val values: Sequence> get() = sequenceOf( AsyncAction.Uninitialized, diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionView.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionView.kt index da1b0fc796..65dc628eb3 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionView.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/async/AsyncActionView.kt @@ -82,7 +82,7 @@ object AsyncActionViewDefaults { @PreviewsDayNight @Composable internal fun AsyncActionViewPreview( - @PreviewParameter(AsyncActionProvider::class) async: AsyncAction, + @PreviewParameter(AsyncActionPreviewParam::class) async: AsyncAction, ) = ElementPreview { AsyncActionView( async = async, diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarData.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarData.kt index ac7e426e65..99c45c67d9 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarData.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarData.kt @@ -8,9 +8,11 @@ package io.element.android.libraries.designsystem.components.avatar +import androidx.compose.runtime.Immutable import io.element.android.libraries.core.data.tryOrNull import java.text.BreakIterator +@Immutable data class AvatarData( val id: String, val name: String?, diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarRow.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarRow.kt index 25784aa501..b80105350d 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarRow.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarRow.kt @@ -24,7 +24,7 @@ import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp -import io.element.android.libraries.designsystem.components.avatar.internal.OverlapRatioProvider +import io.element.android.libraries.designsystem.components.avatar.internal.OverlapRatioPreviewParam import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.designsystem.text.toPx @@ -110,7 +110,7 @@ fun AvatarRow( @Composable @PreviewsDayNight -internal fun AvatarRowPreview(@PreviewParameter(OverlapRatioProvider::class) overlapRatio: Float) { +internal fun AvatarRowPreview(@PreviewParameter(OverlapRatioPreviewParam::class) overlapRatio: Float) { ElementPreview { ContentToPreview(overlapRatio) } @@ -118,7 +118,7 @@ internal fun AvatarRowPreview(@PreviewParameter(OverlapRatioProvider::class) ove @Composable @PreviewsDayNight -internal fun AvatarRowLastOnTopPreview(@PreviewParameter(OverlapRatioProvider::class) overlapRatio: Float) { +internal fun AvatarRowLastOnTopPreview(@PreviewParameter(OverlapRatioPreviewParam::class) overlapRatio: Float) { ElementPreview { ContentToPreview( overlapRatio = overlapRatio, @@ -129,7 +129,7 @@ internal fun AvatarRowLastOnTopPreview(@PreviewParameter(OverlapRatioProvider::c @Composable @PreviewsDayNight -internal fun AvatarRowRtlPreview(@PreviewParameter(OverlapRatioProvider::class) overlapRatio: Float) { +internal fun AvatarRowRtlPreview(@PreviewParameter(OverlapRatioPreviewParam::class) overlapRatio: Float) { CompositionLocalProvider( LocalLayoutDirection provides LayoutDirection.Rtl, ) { @@ -141,7 +141,7 @@ internal fun AvatarRowRtlPreview(@PreviewParameter(OverlapRatioProvider::class) @Composable @PreviewsDayNight -internal fun AvatarRowLastOnTopRtlPreview(@PreviewParameter(OverlapRatioProvider::class) overlapRatio: Float) { +internal fun AvatarRowLastOnTopRtlPreview(@PreviewParameter(OverlapRatioPreviewParam::class) overlapRatio: Float) { CompositionLocalProvider( LocalLayoutDirection provides LayoutDirection.Rtl, ) { diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarSize.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarSize.kt index eb27780073..b91f8c405c 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarSize.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/AvatarSize.kt @@ -8,9 +8,11 @@ package io.element.android.libraries.designsystem.components.avatar +import androidx.compose.runtime.Immutable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +@Immutable enum class AvatarSize(val dp: Dp) { CurrentUserTopBar(32.dp), CurrentRoomTopBar(32.dp), @@ -18,6 +20,7 @@ enum class AvatarSize(val dp: Dp) { IncomingCall(140.dp), RoomDetailsHeader(96.dp), RoomListItem(52.dp), + SearchRoomListItem(32.dp), ThreadsListItem(52.dp), SpaceListItem(52.dp), diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/internal/OverlapRatioProvider.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/internal/OverlapRatioPreviewParam.kt similarity index 88% rename from libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/internal/OverlapRatioProvider.kt rename to libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/internal/OverlapRatioPreviewParam.kt index 26a76c2fac..90f9c7c1c2 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/internal/OverlapRatioProvider.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/avatar/internal/OverlapRatioPreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.libraries.designsystem.components.avatar.internal import androidx.compose.ui.tooling.preview.PreviewParameterProvider -class OverlapRatioProvider : PreviewParameterProvider { +class OverlapRatioPreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( 0f, 0.25f, diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/media/WaveformPlaybackView.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/media/WaveformPlaybackView.kt index f91cf96a95..fe9507cb45 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/media/WaveformPlaybackView.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/media/WaveformPlaybackView.kt @@ -200,11 +200,15 @@ internal fun WaveformPlaybackViewPreview() = ElementPreview { } } -private fun ImmutableList.normalisedData(maxSamplesCount: Int): ImmutableList { +internal fun ImmutableList.normalisedData(maxSamplesCount: Int): ImmutableList { if (maxSamplesCount <= 0) { return persistentListOf() } + if (isEmpty()) { + return List(maxSamplesCount) { 0f }.toImmutableList() + } + // Filter the data to keep only the expected number of samples val result = if (this.size > maxSamplesCount) { (0.. { +open class ImageVectorPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( Icons.Default.BugReport, diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/preferences/components/PreferenceIcon.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/preferences/components/PreferenceIcon.kt index 59e818c18a..5a2e3518f2 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/preferences/components/PreferenceIcon.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/components/preferences/components/PreferenceIcon.kt @@ -86,7 +86,7 @@ private fun PreferenceIcon( @Preview(group = PreviewGroup.Preferences) @Composable -internal fun PreferenceIconPreview(@PreviewParameter(ImageVectorProvider::class) content: ImageVector?) = +internal fun PreferenceIconPreview(@PreviewParameter(ImageVectorPreviewParam::class) content: ImageVector?) = ElementThemedPreview { PreferenceIcon( icon = content, @@ -96,7 +96,7 @@ internal fun PreferenceIconPreview(@PreviewParameter(ImageVectorProvider::class) @Preview(group = PreviewGroup.Preferences) @Composable -internal fun PreferenceIconWithBadgePreview(@PreviewParameter(ImageVectorProvider::class) content: ImageVector?) = +internal fun PreferenceIconWithBadgePreview(@PreviewParameter(ImageVectorPreviewParam::class) content: ImageVector?) = ElementThemedPreview { PreferenceIcon( icon = content, diff --git a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/utils/BooleanProvider.kt b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/utils/BooleanPreviewParam.kt similarity index 86% rename from libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/utils/BooleanProvider.kt rename to libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/utils/BooleanPreviewParam.kt index c50e20dd66..05715464b5 100644 --- a/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/utils/BooleanProvider.kt +++ b/libraries/designsystem/src/main/kotlin/io/element/android/libraries/designsystem/utils/BooleanPreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.libraries.designsystem.utils import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class BooleanProvider : PreviewParameterProvider { +open class BooleanPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf(true, false) } diff --git a/libraries/designsystem/src/test/kotlin/io/element/android/libraries/designsystem/component/async/AsyncActionIndicatorTest.kt b/libraries/designsystem/src/test/kotlin/io/element/android/libraries/designsystem/component/async/AsyncActionIndicatorTest.kt new file mode 100644 index 0000000000..426aa71ce7 --- /dev/null +++ b/libraries/designsystem/src/test/kotlin/io/element/android/libraries/designsystem/component/async/AsyncActionIndicatorTest.kt @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.designsystem.component.async + +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import app.cash.molecule.RecompositionMode +import app.cash.molecule.moleculeFlow +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.architecture.AsyncAction +import io.element.android.libraries.designsystem.components.async.AsyncActionIndicatorEffect +import io.element.android.libraries.designsystem.components.async.AsyncIndicatorState +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Test +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.TestTimeSource +import kotlin.time.TimeSource + +@OptIn(ExperimentalCoroutinesApi::class) +class AsyncActionIndicatorTest { + private val showDelay = 300.milliseconds + private val minDisplay = 500.milliseconds + + @Test + fun `loader is not shown before the show delay elapses`() = runTest { + val state = AsyncIndicatorState() + val action = mutableStateOf>(AsyncAction.Uninitialized) + indicatorFlow(action, state).test { + action.value = AsyncAction.Loading + advanceTimeBy(100.milliseconds) + runCurrent() + assertThat(state.currentAnimationState.targetState).isFalse() + // Once the show delay has fully elapsed, the loader is shown. + advanceTimeBy(300.milliseconds) + runCurrent() + assertThat(state.currentAnimationState.targetState).isTrue() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `loader is never shown when the operation completes before the show delay`() = runTest { + val state = AsyncIndicatorState() + val action = mutableStateOf>(AsyncAction.Uninitialized) + indicatorFlow(action, state).test { + action.value = AsyncAction.Loading + advanceTimeBy(100.milliseconds) + runCurrent() + action.value = AsyncAction.Success(Unit) + advanceTimeBy(1000.milliseconds) + runCurrent() + assertThat(state.currentAnimationState.targetState).isFalse() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `failure is shown immediately, without waiting for the show delay`() = runTest { + val state = AsyncIndicatorState() + val action = mutableStateOf>(AsyncAction.Uninitialized) + indicatorFlow(action, state).test { + action.value = AsyncAction.Failure(Exception("failed")) + runCurrent() + assertThat(state.currentAnimationState.targetState).isTrue() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `loader stays visible for the minimum duration once shown`() = runTest { + val state = AsyncIndicatorState() + val action = mutableStateOf>(AsyncAction.Uninitialized) + val timeSource = TestTimeSource() + indicatorFlow(action, state, timeSource).test { + // Show the loader. + action.value = AsyncAction.Loading + advanceTimeBy(400.milliseconds) + runCurrent() + assertThat(state.currentAnimationState.targetState).isTrue() + // 200ms of display has already elapsed when the operation succeeds. + timeSource += 200.milliseconds + action.value = AsyncAction.Success(Unit) + runCurrent() + // Still within the minimum display duration (200ms shown, 300ms remaining) -> stays visible. + advanceTimeBy(200.milliseconds) + runCurrent() + assertThat(state.currentAnimationState.targetState).isTrue() + // Past the minimum display duration -> cleared. + advanceTimeBy(200.milliseconds) + runCurrent() + assertThat(state.currentAnimationState.targetState).isFalse() + cancelAndIgnoreRemainingEvents() + } + } + + private fun indicatorFlow( + action: State>, + state: AsyncIndicatorState, + timeSource: TimeSource = TimeSource.Monotonic, + ): Flow = moleculeFlow(RecompositionMode.Immediate) { + AsyncActionIndicatorEffect( + asyncAction = action.value, + state = state, + showDelay = showDelay, + minDisplayDuration = minDisplay, + failureDuration = minDisplay, + loading = {}, + failure = {}, + timeSource = timeSource, + ) + state.currentAnimationState.targetState + } +} diff --git a/libraries/designsystem/src/test/kotlin/io/element/android/libraries/designsystem/components/media/WaveformNormalisationTest.kt b/libraries/designsystem/src/test/kotlin/io/element/android/libraries/designsystem/components/media/WaveformNormalisationTest.kt new file mode 100644 index 0000000000..23557704ce --- /dev/null +++ b/libraries/designsystem/src/test/kotlin/io/element/android/libraries/designsystem/components/media/WaveformNormalisationTest.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 Element Creations Ltd. + * Copyright 2025 New Vector Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.designsystem.components.media + +import com.google.common.truth.Truth.assertThat +import kotlinx.collections.immutable.persistentListOf +import org.junit.Test + +class WaveformNormalisationTest { + @Test + fun `an empty waveform is padded to the requested number of samples`() { + val result = persistentListOf().normalisedData(30) + assertThat(result).hasSize(30) + assertThat(result.toSet()).containsExactly(0f) + } + + @Test + fun `an empty waveform stays empty when there is no room to display it`() { + assertThat(persistentListOf().normalisedData(0)).isEmpty() + assertThat(persistentListOf().normalisedData(-1)).isEmpty() + } + + @Test + fun `a waveform shorter than the display count is kept as it is`() { + val waveform = persistentListOf(0.1f, 0.2f, 0.3f) + assertThat(waveform.normalisedData(30)).containsExactly(0.1f, 0.2f, 0.3f).inOrder() + } + + @Test + fun `a waveform longer than the display count is downsampled`() { + val waveform = persistentListOf(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f) + assertThat(waveform.normalisedData(3)).hasSize(3) + } +} diff --git a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerPresenter.kt b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerPresenter.kt index a20b53a480..ac83b49533 100644 --- a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerPresenter.kt +++ b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerPresenter.kt @@ -11,7 +11,14 @@ import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.emoji.api.recentemojis.GetRecentEmojis fun interface EmojiPickerPresenter : Presenter { + /** + * Creates a presenter for one picker instance. + */ fun interface Factory { + /** + * @param getRecentEmojis how the picker sources its recent tab; pass [io.element.android.libraries.emoji.api.recentemojis.EmptyGetRecentEmojis] + * for a picker that should have no recent tab at all. + */ fun create(getRecentEmojis: GetRecentEmojis): EmojiPickerPresenter } } diff --git a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerRenderer.kt b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerRenderer.kt index b3784b3c42..b273f41dae 100644 --- a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerRenderer.kt +++ b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/picker/EmojiPickerRenderer.kt @@ -13,9 +13,16 @@ import androidx.compose.ui.Modifier import io.element.android.emojibasebindings.Emoji import kotlinx.collections.immutable.ImmutableSet +/** + * Renders the emoji picker, so that callers can embed it without depending on its implementation. + * + * See [NoOpEmojiPickerRenderer] for a renderer that draws nothing, used where the picker is disabled. + */ @Immutable interface EmojiPickerRenderer { /** + * Draws the picker. + * * @param state opaque state produced by [EmojiPickerPresenter.present]. * @param onSelectEmoji invoked when the user taps an emoji (including a skin-tone variant). * @param selectedEmojis emojis to visually mark as already selected. diff --git a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/AddRecentEmoji.kt b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/AddRecentEmoji.kt index 5865568511..af2a1dfd7d 100644 --- a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/AddRecentEmoji.kt +++ b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/AddRecentEmoji.kt @@ -8,6 +8,12 @@ package io.element.android.libraries.emoji.api.recentemojis +/** + * Records that an emoji was just used, so it surfaces in the picker's recent list; see [GetRecentEmojis] for the read side. + */ fun interface AddRecentEmoji { + /** + * @param emoji the emoji that was just used, as its unicode representation. + */ suspend operator fun invoke(emoji: String): Result } diff --git a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/GetRecentEmojis.kt b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/GetRecentEmojis.kt index cf6015d799..276b0e7eba 100644 --- a/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/GetRecentEmojis.kt +++ b/libraries/emoji/api/src/main/kotlin/io/element/android/libraries/emoji/api/recentemojis/GetRecentEmojis.kt @@ -15,6 +15,7 @@ import kotlinx.collections.immutable.persistentListOf * Returns the list of recently used emojis for reactions. */ fun interface GetRecentEmojis { + /** Returns the recently used emojis, most recent first; see [EmptyGetRecentEmojis] for a picker with no recent tab. */ suspend operator fun invoke(): Result> } diff --git a/libraries/emoji/impl/build.gradle.kts b/libraries/emoji/impl/build.gradle.kts index 1cb274e6c0..59a1ad6575 100644 --- a/libraries/emoji/impl/build.gradle.kts +++ b/libraries/emoji/impl/build.gradle.kts @@ -36,5 +36,5 @@ dependencies { implementation(libs.matrix.emojibase.bindings) testImplementation(projects.libraries.matrix.test) - testCommonDependencies(libs) + testCommonDependencies(libs, includeTestComposeView = true) } diff --git a/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/DefaultEmojiPickerStateProvider.kt b/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/DefaultEmojiPickerStatePreviewParam.kt similarity index 96% rename from libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/DefaultEmojiPickerStateProvider.kt rename to libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/DefaultEmojiPickerStatePreviewParam.kt index 964e0f3b78..e649670da4 100644 --- a/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/DefaultEmojiPickerStateProvider.kt +++ b/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/DefaultEmojiPickerStatePreviewParam.kt @@ -19,7 +19,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -internal class DefaultEmojiPickerStateProvider : PreviewParameterProvider { +internal class DefaultEmojiPickerStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aDefaultEmojiPickerState(), diff --git a/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/EmojiPickerView.kt b/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/EmojiPickerView.kt index 94eaea1595..c41cbb3b57 100644 --- a/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/EmojiPickerView.kt +++ b/libraries/emoji/impl/src/main/kotlin/io/element/android/libraries/emoji/impl/picker/EmojiPickerView.kt @@ -62,7 +62,7 @@ internal fun EmojiPickerView( Column(modifier) { SearchBar( - modifier = Modifier.padding(bottom = 10.dp), + modifier = Modifier.padding(bottom = if (state.isSearchActive) 0.dp else 10.dp), queryState = state.searchQuery, resultState = state.searchResults, active = state.isSearchActive, @@ -166,7 +166,7 @@ private fun EmojiResults( @PreviewsDayNight @Composable -internal fun EmojiPickerViewPreview(@PreviewParameter(DefaultEmojiPickerStateProvider::class) state: DefaultEmojiPickerState) = ElementPreview { +internal fun EmojiPickerViewPreview(@PreviewParameter(DefaultEmojiPickerStatePreviewParam::class) state: DefaultEmojiPickerState) = ElementPreview { EmojiPickerView( state = state, onSelectEmoji = {}, diff --git a/libraries/emoji/impl/src/main/res/values-ar/translations.xml b/libraries/emoji/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..5a84323379 --- /dev/null +++ b/libraries/emoji/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,13 @@ + + + "أنشطة" + "أعلام" + "أكل وشرب" + "حيوانات وطبيعة" + "أشياء" + "الابتسامات والأشخاص" + "سفر وأماكن" + "الرموز التعبيرية الأخيرة" + "رموز" + "البحث عن رموز تعبيرية" + diff --git a/libraries/emoji/impl/src/main/res/values-es/translations.xml b/libraries/emoji/impl/src/main/res/values-es/translations.xml index 7a694296b2..d32846b145 100644 --- a/libraries/emoji/impl/src/main/res/values-es/translations.xml +++ b/libraries/emoji/impl/src/main/res/values-es/translations.xml @@ -7,5 +7,7 @@ "Objetos" "Emojis y personas" "Viajes y lugares" + "Emojis recientes" "Símbolos" + "Buscar emojis" diff --git a/libraries/emoji/impl/src/main/res/values-pl/translations.xml b/libraries/emoji/impl/src/main/res/values-pl/translations.xml index c59f2c6b54..9ac9d5dff9 100644 --- a/libraries/emoji/impl/src/main/res/values-pl/translations.xml +++ b/libraries/emoji/impl/src/main/res/values-pl/translations.xml @@ -4,7 +4,7 @@ "Flagi" "Jedzenie i napoje" "Zwierzęta i natura" - "Obiekty" + "Przedmioty" "Buźki i osoby" "Podróż i miejsca" "Ostatnie emoji" diff --git a/libraries/emoji/impl/src/test/kotlin/io/element/android/libraries/emoji/impl/picker/EmojiPickerViewTest.kt b/libraries/emoji/impl/src/test/kotlin/io/element/android/libraries/emoji/impl/picker/EmojiPickerViewTest.kt new file mode 100644 index 0000000000..4c0d7949cb --- /dev/null +++ b/libraries/emoji/impl/src/test/kotlin/io/element/android/libraries/emoji/impl/picker/EmojiPickerViewTest.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +@file:OptIn(ExperimentalTestApi::class) + +package io.element.android.libraries.emoji.impl.picker + +import androidx.activity.ComponentActivity +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.AndroidComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsEqualTo +import androidx.compose.ui.test.getBoundsInRoot +import androidx.compose.ui.test.hasScrollToIndexAction +import androidx.compose.ui.test.v2.runAndroidComposeUiTest +import androidx.compose.ui.unit.dp +import io.element.android.emojibasebindings.Emoji +import io.element.android.libraries.designsystem.theme.components.SearchBarResultState +import io.element.android.tests.testutils.robolectric.RobolectricTest +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentSetOf +import org.junit.Test +import org.robolectric.annotation.Config + +private val PICKER_HEIGHT = 600.dp + +class EmojiPickerViewTest : RobolectricTest() { + @Config(qualifiers = "w400dp-h800dp") + @Test + fun `the search results reach the bottom of the picker`() = runAndroidComposeUiTest { + setEmojiPickerView() + onNode(hasScrollToIndexAction()) + .getBoundsInRoot() + .bottom + .assertIsEqualTo(PICKER_HEIGHT, "emoji grid bottom") + } +} + +private fun AndroidComposeUiTest.setEmojiPickerView() { + setContent { + Box(Modifier.size(400.dp, PICKER_HEIGHT)) { + EmojiPickerView( + state = aDefaultEmojiPickerState( + isSearchActive = true, + searchQuery = "smile", + searchResults = SearchBarResultState.Results( + persistentListOf( + Emoji( + hexcode = "0x00", + label = "grinning face", + tags = persistentListOf("grinning"), + shortcodes = persistentListOf("smile"), + unicode = "😀", + skins = null, + ), + ) + ), + ), + onSelectEmoji = {}, + selectedEmojis = persistentSetOf(), + modifier = Modifier.fillMaxSize(), + ) + } + } +} diff --git a/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/PinnedMessagesBannerFormatter.kt b/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/PinnedMessagesBannerFormatter.kt index 67994f18b9..986e5dfe32 100644 --- a/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/PinnedMessagesBannerFormatter.kt +++ b/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/PinnedMessagesBannerFormatter.kt @@ -10,6 +10,12 @@ package io.element.android.libraries.eventformatter.api import io.element.android.libraries.matrix.api.timeline.item.event.EventTimelineItem +/** + * Formats the short summary of a pinned event shown in the banner at the top of a room. + */ interface PinnedMessagesBannerFormatter { + /** + * @param event the pinned event to describe. + */ fun format(event: EventTimelineItem): CharSequence } diff --git a/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/RoomLatestEventFormatter.kt b/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/RoomLatestEventFormatter.kt index abb5cc929d..7ddc65f57b 100644 --- a/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/RoomLatestEventFormatter.kt +++ b/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/RoomLatestEventFormatter.kt @@ -10,7 +10,25 @@ package io.element.android.libraries.eventformatter.api import io.element.android.libraries.matrix.api.roomlist.LatestEventValue +/** + * Formats the one-line preview of a room's latest event, as shown in the room list. + */ interface RoomLatestEventFormatter { + /** + * Formats an event that is still local, i.e. queued or being sent. + * + * @param latestEvent the local event to describe. + * @param isDmRoom whether the room is a direct message, which lets the sender name be left out. + * @return the preview text, or `null` when this kind of event should not be previewed. + */ fun format(latestEvent: LatestEventValue.Local, isDmRoom: Boolean): CharSequence? + + /** + * Formats an event that has been received from the server. + * + * @param latestEvent the remote event to describe. + * @param isDmRoom whether the room is a direct message, which lets the sender name be left out. + * @return the preview text, or `null` when this kind of event should not be previewed. + */ fun format(latestEvent: LatestEventValue.Remote, isDmRoom: Boolean): CharSequence? } diff --git a/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/TimelineEventFormatter.kt b/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/TimelineEventFormatter.kt index be601fb82a..67d263f168 100644 --- a/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/TimelineEventFormatter.kt +++ b/libraries/eventformatter/api/src/main/kotlin/io/element/android/libraries/eventformatter/api/TimelineEventFormatter.kt @@ -13,7 +13,16 @@ import io.element.android.libraries.matrix.api.timeline.item.event.EventContent import io.element.android.libraries.matrix.api.timeline.item.event.EventTimelineItem import io.element.android.libraries.matrix.api.timeline.item.event.getDisambiguatedDisplayName +/** + * Turns a state or membership event into the human readable sentence shown in the timeline, such as "Alice joined the room". + */ interface TimelineEventFormatter { + /** + * Convenience overload that reads the sender and ownership from the timeline item itself. + * + * @param event the timeline item to describe. + * @return the sentence to display, or `null` when this kind of event is not rendered as text. + */ fun format(event: EventTimelineItem): CharSequence? { return format( content = event.content, @@ -22,5 +31,13 @@ interface TimelineEventFormatter { senderDisambiguatedDisplayName = event.senderProfile.getDisambiguatedDisplayName(event.sender), ) } + + /** + * @param content the event content to describe. + * @param isOutgoing whether the event was sent by the current user, which selects the first-person wording. + * @param sender the user who sent the event. + * @param senderDisambiguatedDisplayName the sender's display name, already suffixed with their id when it is ambiguous in the room. + * @return the sentence to display, or `null` when this kind of event is not rendered as text. + */ fun format(content: EventContent, isOutgoing: Boolean, sender: UserId, senderDisambiguatedDisplayName: String): CharSequence? } diff --git a/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatter.kt b/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatter.kt index 1c5cd72977..e7bbdb1e7f 100644 --- a/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatter.kt +++ b/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatter.kt @@ -135,7 +135,7 @@ class DefaultRoomLatestEventFormatter( val message = when (val messageType: MessageType = type) { // Doesn't need a prefix is EmoteMessageType -> { - return "* $senderDisambiguatedDisplayName ${messageType.body}" + return "* ${senderDisambiguatedDisplayName.bidiIsolate()} ${messageType.body}" } is TextMessageType -> { messageType.toPlainText(permalinkParser) @@ -189,7 +189,7 @@ class DefaultRoomLatestEventFormatter( if (isOutgoing) { sp.getString(CommonStrings.common_you) } else { - senderDisambiguatedDisplayName + senderDisambiguatedDisplayName.bidiIsolate() } ) } diff --git a/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/PrefixWith.kt b/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/PrefixWith.kt index 1a04893e07..f0965e95af 100644 --- a/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/PrefixWith.kt +++ b/libraries/eventformatter/impl/src/main/kotlin/io/element/android/libraries/eventformatter/impl/PrefixWith.kt @@ -14,6 +14,12 @@ import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle +private const val FIRST_STRONG_ISOLATE = 0x2068 +private const val POP_DIRECTIONAL_ISOLATE = 0x2069 + +/** Wraps the string between Unicode isolate characters so its own direction cannot reorder the text around it. */ +internal fun String.bidiIsolate(): String = Char(FIRST_STRONG_ISOLATE) + this + Char(POP_DIRECTIONAL_ISOLATE) + internal fun CharSequence.prefixWith(prefix: String): AnnotatedString { return buildAnnotatedString { withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { diff --git a/libraries/eventformatter/impl/src/main/res/values-ar/translations.xml b/libraries/eventformatter/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..8b64ef4f6c --- /dev/null +++ b/libraries/eventformatter/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,73 @@ + + + "(الصورة غُيِّرت أيضاً)" + "غيّرَ %1$s صورته الشخصية" + "قمتَ بتغيير صورتك الشخصية" + "تم خفض رتبة %1$s إلى عضو" + "تم خفض رتبة %1$s إلى مشرف" + "غيّر %1$s اسمه من %2$s إلى %3$s" + "غيّرتَ اسمك من %1$s إلى %2$s" + "أزال %1$s اسمه (كان %2$s سابقاً)" + "قمتَ بحذف اسمك (كان %1$s سابقاً)" + "عيّن %1$s اسمه ليكون %2$s" + "عيّنتَ اسمك ليكون %1$s" + "تمت ترقية %1$s إلى مسؤول" + "تمت ترقية %1$s إلى مشرف" + "غيّر %1$s صورة الغرفة" + "قمتَ بتغيير صورة الغرفة" + "أزال %1$s صورة الغرفة" + "قمتَ بإزالة صورة الغرفة" + "%1$s حظر %2$s" + "قمتَ بحظر %1$s" + "حظرت %1$s: %2$s" + "قام %1$s بحظر %2$s: %3$s" + "%1$s أنشأ الغرفة" + "قمتَ بإنشاء الغرفة" + "%1$s دعا %2$s" + "قَبِل %1$s الدعوة" + "قمتَ بقبول الدعوة" + "قمتَ بدعوة %1$s" + "قام %1$s بدعوتك" + "انضمَّ %1$s إلى الغرفة" + "اِنضممت إلى الغرفة" + "طلب %1$s الانضمام" + "سمح %1$s لـ %2$s بالانضمام" + "قمتَ بالسماح لـ %1$s بالانضمام" + "قمتَ بطلب الانضمام" + "رفض %1$s طلب %2$s بالانضمام" + "قمتَ برفض طلب %1$s للانضمام" + "رفض %1$s طلب انضمامك" + "لم يعد %1$s مهتماً بالانضمام" + "قمتَ بإلغاء طلب انضمامك" + "غادر %1$s المجموعة" + "قمتَ بمغادرة المجموعة" + "غيّر %1$s اسم الغرفة إلى: %2$s" + "قمتَ بتغيير اسم الغرفة إلى: %1$s" + "حذف %1$s اسم الغرفة" + "قمتَ بحذف اسم الغرفة" + "%1$s لم يُجرِ أي تغييرات" + "لم تُجرِ أي تغييرات" + "غيّر %1$s الرسائل المثبّتة" + "غيّرت الرسائل المثبّتة" + "ثبّت %1$s رسالة" + "قمت بتثبيت رسالة" + "ألغى %1$s تثبيت رسالة" + "قمت بإلغاء تثبيت رسالة" + "رفض %1$s الدعوة" + "قمتَ برفض الدعوة" + "%1$s طرد %2$s" + "قمتَ بطرد %1$s" + "أزلت %1$s: %2$s" + "قام %1$s بإزالة %2$s: %3$s" + "أرسل %1$s دعوة إلى %2$s لينضم إلى الغرفة" + "قمتَ بإرسال دعوة إلى %1$s لينضم إلى الغرفة" + "تراجع %1$s عن دعوة %2$s للانضمام إلى الغرفة" + "قمتَ بالتراجع عن دعوة %1$s للانضمام إلى الغرفة" + "غيّر %1$s الموضوع إلى: %2$s" + "قمتَ بتغيير الموضوع إلى: %1$s" + "أزال %1$s موضوع الغرفة" + "قمتَ بإزالة موضوع الغرفة" + "%1$s فكّ الحظر عن %2$s" + "قمتَ بفك الحظر عن %1$s" + "أحدث %1$s تغييراً غير معلوم في عضويته" + diff --git a/libraries/eventformatter/impl/src/main/res/values-fa/translations.xml b/libraries/eventformatter/impl/src/main/res/values-fa/translations.xml index f7fd635d31..259bed9e5e 100644 --- a/libraries/eventformatter/impl/src/main/res/values-fa/translations.xml +++ b/libraries/eventformatter/impl/src/main/res/values-fa/translations.xml @@ -19,6 +19,8 @@ "چهرک اتاق را برداشتید" "%2$s به دست %1$s مسدود کرد" "%1$s را مسدود کردید" + "شما %1$s: %2$s را محروم کردید" + "%1$s محروم شد %2$s: %3$s" "%1$s اتاق را ایجاد کرد" "اتاق را ساختید" "%1$s از %2$s دعوت کرد" @@ -55,6 +57,8 @@ "دعوت را رد کردید" "%2$s به دست %1$s برداشته شد" "%1$s را برداشتید" + "شما %1$s: %2$s را حذف کردید" + "%1$s حذف شد %2$s: %3$s" "%1$s دعوتی برای پیوستن %2$s به اتاق فرستاد" "برای %1$s دعوت پیوستن به اتاق فرستادید" "%1$s دعوت پیوستن به اتاق %2$s را باطل کرد" diff --git a/libraries/eventformatter/impl/src/test/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatterTest.kt b/libraries/eventformatter/impl/src/test/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatterTest.kt index 791a363f77..ecd0509269 100644 --- a/libraries/eventformatter/impl/src/test/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatterTest.kt +++ b/libraries/eventformatter/impl/src/test/kotlin/io/element/android/libraries/eventformatter/impl/DefaultRoomLatestEventFormatterTest.kt @@ -91,7 +91,7 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { assertThat(result).isEqualTo(expected) } else { assertThat(result).isInstanceOf(AnnotatedString::class.java) - assertThat(result.toString()).isEqualTo("$senderName: $expected") + assertThat(result.toString()).isEqualTo("⁨$senderName⁩: $expected") } } } @@ -103,13 +103,13 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { val info = ImageInfo(null, null, null, null, null, null, null) val message = createLatestEvent(false, null, aStickerContent(body, info, aMediaSource(url = "url"))) val result = formatter.format(message, false) - val expectedBody = someoneElseId.value + ": Sticker: a sticker body" + val expectedBody = "⁨" + someoneElseId.value + "⁩: Sticker: a sticker body" // Check we have formatting assertThat(result is AnnotatedString).isTrue() // And there is a bold span for the 'Sticker' part val boldSpanStyle = (result as AnnotatedString).spanStyles.lastOrNull { it.item.fontWeight == FontWeight.Bold } assertThat(boldSpanStyle).isNotNull() - val spanStart = someoneElseId.value.length + 2 + val spanStart = someoneElseId.value.length + 4 assertThat(boldSpanStyle!!.start..boldSpanStyle.end).isEqualTo(spanStart..spanStart + 7) assertThat(result.toString()).isEqualTo(expectedBody) } @@ -130,7 +130,7 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { assertThat(result).isEqualTo(expected) } else { assertThat(result).isInstanceOf(AnnotatedString::class.java) - assertThat(result.toString()).isEqualTo("$senderName: $expected") + assertThat(result.toString()).isEqualTo("⁨$senderName⁩: $expected") } } } @@ -152,12 +152,29 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { assertWithMessage("$type was not properly handled").that(result).isEqualTo(expected) } else { assertWithMessage("$type does not create an AnnotatedString").that(result).isInstanceOf(AnnotatedString::class.java) - assertWithMessage("$type was not properly handled").that(result.toString()).isEqualTo("$senderName: $expected") + assertWithMessage("$type was not properly handled").that(result.toString()).isEqualTo("⁨$senderName⁩: $expected") } } } } + @Test + @Config(qualifiers = "en") + fun `a right to left sender name is isolated so it cannot reorder the preview`() { + val senderName = "مرحبا" + val body = "Hello" + val message = createLatestEvent( + sentByYou = false, + senderDisplayName = senderName, + content = MessageContent(body, null, false, null, TextMessageType(body, null)), + ) + val result = formatter.format(message, false) + assertThat(result.toString()).isEqualTo("⁨$senderName⁩: $body") + val boldSpanStyle = (result as AnnotatedString).spanStyles.first { it.item.fontWeight == FontWeight.Bold } + assertThat(boldSpanStyle.start).isEqualTo(0) + assertThat(boldSpanStyle.end).isEqualTo(senderName.length + 2) + } + // region Message contents @Test @@ -166,7 +183,7 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { testMessageContents( sentByYou = false, senderName = "Alice", - expectedPrefix = "Alice", + expectedPrefix = "⁨Alice⁩", ) } @@ -233,7 +250,7 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { is StickerMessageType -> "Sticker: Shared body" is FileMessageType -> "File: Shared body" is LocationMessageType -> "Shared location" - is EmoteMessageType -> "* $senderName ${type.body}" + is EmoteMessageType -> "* ⁨$senderName⁩ ${type.body}" is TextMessageType, is NoticeMessageType, is OtherMessageType -> body @@ -275,7 +292,7 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { is TextMessageType, is NoticeMessageType, is OtherMessageType -> "$expectedPrefix: $body" - is EmoteMessageType -> "* $senderName ${type.body}" + is EmoteMessageType -> "* ⁨$senderName⁩ ${type.body}" } val shouldCreateAnnotatedString = when (type) { is VideoMessageType -> true @@ -944,7 +961,7 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { assertThat(formatter.format(mineContentEvent, false).toString()).isEqualTo("You: Poll: Do you like polls?") val contentEvent = createLatestEvent(sentByYou = false, senderDisplayName = "Bob", content = pollContent) - assertThat(formatter.format(contentEvent, false).toString()).isEqualTo("Bob: Poll: Do you like polls?") + assertThat(formatter.format(contentEvent, false).toString()).isEqualTo("⁨Bob⁩: Poll: Do you like polls?") val result = formatter.format(contentEvent, false) // Check we have formatting @@ -952,7 +969,7 @@ class DefaultRoomLatestEventFormatterTest : RobolectricTest() { // And there is a bold span for the 'Poll' part val boldSpanStyle = (result as AnnotatedString).spanStyles.lastOrNull { it.item.fontWeight == FontWeight.Bold } assertThat(boldSpanStyle).isNotNull() - val spanStart = "Bob".length + 2 + val spanStart = "Bob".length + 4 assertThat(boldSpanStyle!!.start..boldSpanStyle.end).isEqualTo(spanStart..spanStart + 4) } diff --git a/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/Feature.kt b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/Feature.kt index 395fd04c6c..4fd8706d89 100644 --- a/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/Feature.kt +++ b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/Feature.kt @@ -10,6 +10,9 @@ package io.element.android.libraries.featureflag.api import io.element.android.libraries.core.meta.BuildMeta +/** + * Describes one feature flag: how it is identified, how it is presented in the developer options, and what it defaults to. + */ interface Feature { /** * Unique key to identify the feature. diff --git a/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlagService.kt b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlagService.kt index 6a8cb2fd9d..3dc791317f 100644 --- a/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlagService.kt +++ b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlagService.kt @@ -11,6 +11,9 @@ package io.element.android.libraries.featureflag.api import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first +/** + * Reads and, where a mutable provider is registered, changes the state of the feature flags. + */ interface FeatureFlagService { /** * @param feature the feature to check for diff --git a/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlags.kt b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlags.kt index 79b63f4455..4a8894e99c 100644 --- a/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlags.kt +++ b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeatureFlags.kt @@ -152,13 +152,6 @@ enum class FeatureFlags( defaultValue = { false }, isFinished = false, ), - UserStatus( - key = "feature.user_status", - title = "User status", - description = "Allow users to set a status (e.g. In a meeting, Away) visible to their contacts.", - defaultValue = { false }, - isFinished = false, - ), MessageSearch( key = "feature.message_search", title = "Message search", diff --git a/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeaturesProvider.kt b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeaturesProvider.kt new file mode 100644 index 0000000000..a342ccdd9b --- /dev/null +++ b/libraries/featureflag/api/src/main/kotlin/io/element/android/libraries/featureflag/api/FeaturesProvider.kt @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.featureflag.api + +/** + * Provides a list of available [Feature]s that the application supports. + * Used by [FeatureFlagService.getAvailableFeatures] to obtain a list of features + * that can be presented to the user. + * + * Multiple instances can exist within the application, and all instances are polled + * to provide features for the list. This means that additional features can be provided + * by compile-time extensions. + */ +fun interface FeaturesProvider { + fun provide(): List +} diff --git a/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagService.kt b/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagService.kt index 74967a574d..675cf7855c 100644 --- a/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagService.kt +++ b/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagService.kt @@ -14,6 +14,7 @@ import dev.zacsweers.metro.SingleIn import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.featureflag.api.Feature import io.element.android.libraries.featureflag.api.FeatureFlagService +import io.element.android.libraries.featureflag.api.FeaturesProvider import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf @@ -22,7 +23,7 @@ import kotlinx.coroutines.flow.flowOf class DefaultFeatureFlagService( private val providers: Set<@JvmSuppressWildcards FeatureFlagProvider>, private val buildMeta: BuildMeta, - private val featuresProvider: FeaturesProvider, + private val featuresProviders: Set, ) : FeatureFlagService { override fun isFeatureEnabledFlow(feature: Feature): Flow { return if (feature.isFinished) { @@ -47,7 +48,7 @@ class DefaultFeatureFlagService( includeFinishedFeatures: Boolean, isInLabs: Boolean, ): List { - return featuresProvider.provide().filter { flag -> + return featuresProviders.flatMap { provider -> provider.provide() }.filter { flag -> (includeFinishedFeatures || !flag.isFinished) && flag.isInLabs == isInLabs } diff --git a/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/FeaturesProvider.kt b/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeaturesProvider.kt similarity index 78% rename from libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/FeaturesProvider.kt rename to libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeaturesProvider.kt index e24ae66783..c96a781d82 100644 --- a/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/FeaturesProvider.kt +++ b/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeaturesProvider.kt @@ -9,15 +9,12 @@ package io.element.android.libraries.featureflag.impl import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.ContributesIntoSet import io.element.android.libraries.featureflag.api.Feature import io.element.android.libraries.featureflag.api.FeatureFlags +import io.element.android.libraries.featureflag.api.FeaturesProvider -fun interface FeaturesProvider { - fun provide(): List -} - -@ContributesBinding(AppScope::class) +@ContributesIntoSet(AppScope::class) class DefaultFeaturesProvider : FeaturesProvider { override fun provide(): List = FeatureFlags.entries } diff --git a/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/di/FeatureFlagModule.kt b/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/di/FeatureFlagBindingContainer.kt similarity index 96% rename from libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/di/FeatureFlagModule.kt rename to libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/di/FeatureFlagBindingContainer.kt index de3f8aa519..be4fa6f23f 100644 --- a/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/di/FeatureFlagModule.kt +++ b/libraries/featureflag/impl/src/main/kotlin/io/element/android/libraries/featureflag/impl/di/FeatureFlagBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.featureflag.impl.PreferencesFeatureFlagProvi @BindingContainer @ContributesTo(AppScope::class) -object FeatureFlagModule { +object FeatureFlagBindingContainer { @JvmStatic @Provides @ElementsIntoSet diff --git a/libraries/featureflag/impl/src/test/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagServiceTest.kt b/libraries/featureflag/impl/src/test/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagServiceTest.kt index 00bc687bb9..0ed6d8eafd 100644 --- a/libraries/featureflag/impl/src/test/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagServiceTest.kt +++ b/libraries/featureflag/impl/src/test/kotlin/io/element/android/libraries/featureflag/impl/DefaultFeatureFlagServiceTest.kt @@ -12,6 +12,7 @@ import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.featureflag.api.Feature +import io.element.android.libraries.featureflag.api.FeaturesProvider import io.element.android.libraries.featureflag.test.FakeFeature import io.element.android.libraries.matrix.test.core.aBuildMeta import kotlinx.coroutines.test.runTest @@ -166,5 +167,5 @@ private fun createDefaultFeatureFlagService( ) = DefaultFeatureFlagService( providers = providers, buildMeta = buildMeta, - featuresProvider = { features } + featuresProviders = setOf(FeaturesProvider { features }) ) diff --git a/libraries/fullscreenintent/impl/src/main/kotlin/io/element/android/libraries/fullscreenintent/impl/di/FullScreenIntentModule.kt b/libraries/fullscreenintent/impl/src/main/kotlin/io/element/android/libraries/fullscreenintent/impl/di/FullScreenIntentBindingContainer.kt similarity index 95% rename from libraries/fullscreenintent/impl/src/main/kotlin/io/element/android/libraries/fullscreenintent/impl/di/FullScreenIntentModule.kt rename to libraries/fullscreenintent/impl/src/main/kotlin/io/element/android/libraries/fullscreenintent/impl/di/FullScreenIntentBindingContainer.kt index 249485b15c..ae43cebd46 100644 --- a/libraries/fullscreenintent/impl/src/main/kotlin/io/element/android/libraries/fullscreenintent/impl/di/FullScreenIntentModule.kt +++ b/libraries/fullscreenintent/impl/src/main/kotlin/io/element/android/libraries/fullscreenintent/impl/di/FullScreenIntentBindingContainer.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.fullscreenintent.impl.FullScreenIntentPermis @ContributesTo(AppScope::class) @BindingContainer -interface FullScreenIntentModule { +interface FullScreenIntentBindingContainer { @Binds fun bindFullScreenIntentPermissionsPresenter(presenter: FullScreenIntentPermissionsPresenter): Presenter } diff --git a/libraries/indicator/api/src/main/kotlin/io/element/android/libraries/indicator/api/IndicatorService.kt b/libraries/indicator/api/src/main/kotlin/io/element/android/libraries/indicator/api/IndicatorService.kt index 0409a0f846..d2fde82d8a 100644 --- a/libraries/indicator/api/src/main/kotlin/io/element/android/libraries/indicator/api/IndicatorService.kt +++ b/libraries/indicator/api/src/main/kotlin/io/element/android/libraries/indicator/api/IndicatorService.kt @@ -15,9 +15,11 @@ import androidx.compose.runtime.State * A set of State to observe to display or not the indicators in the UI. */ interface IndicatorService { + /** Whether to show the red dot on the room list top bar, which aggregates the reasons the user should open the settings. */ @Composable fun showRoomListTopBarIndicator(): State + /** Whether to show the red dot on the chat backup setting, i.e. when recovery needs the user's attention. */ @Composable fun showSettingChatBackupIndicator(): State } diff --git a/libraries/indicator/impl/src/main/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorService.kt b/libraries/indicator/impl/src/main/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorService.kt index 0629799c74..1dd2a4c64c 100644 --- a/libraries/indicator/impl/src/main/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorService.kt +++ b/libraries/indicator/impl/src/main/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorService.kt @@ -9,11 +9,14 @@ package io.element.android.libraries.indicator.impl import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import dev.zacsweers.metro.ContributesBinding import io.element.android.libraries.di.SessionScope import io.element.android.libraries.indicator.api.IndicatorService @@ -43,12 +46,17 @@ class DefaultIndicatorService( override fun showSettingChatBackupIndicator(): State { val backupState by encryptionService.backupStateStateFlow.collectAsState() val recoveryState by encryptionService.recoveryStateStateFlow.collectAsState() + var doesBackupExistOnServer by remember { mutableStateOf(null) } + + LaunchedEffect(backupState) { + if (backupState == BackupState.UNKNOWN) { + doesBackupExistOnServer = encryptionService.doesBackupExistOnServer().getOrNull() + } + } return remember { derivedStateOf { - val showForBackup = backupState in listOf( - BackupState.UNKNOWN, - ) + val showForBackup = backupState == BackupState.UNKNOWN && doesBackupExistOnServer != true val showForRecovery = recoveryState in listOf( RecoveryState.DISABLED, RecoveryState.INCOMPLETE, diff --git a/libraries/indicator/impl/src/test/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorServiceTest.kt b/libraries/indicator/impl/src/test/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorServiceTest.kt index cd861ef530..3782e2c9f1 100644 --- a/libraries/indicator/impl/src/test/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorServiceTest.kt +++ b/libraries/indicator/impl/src/test/kotlin/io/element/android/libraries/indicator/impl/DefaultIndicatorServiceTest.kt @@ -42,8 +42,10 @@ class DefaultIndicatorServiceTest { } @Test - fun `test - showSettingChatBackupIndicator is true when BackupState is UNKNOWN`() = runTest { - val encryptionService = FakeEncryptionService() + fun `test - showSettingChatBackupIndicator is true when BackupState is UNKNOWN and no backup exists on the server`() = runTest { + val encryptionService = FakeEncryptionService().apply { + givenDoesBackupExistOnServerResult(Result.success(false)) + } val sessionVerificationService = FakeSessionVerificationService() val sut = DefaultIndicatorService( sessionVerificationService = sessionVerificationService, @@ -61,6 +63,24 @@ class DefaultIndicatorServiceTest { } } + @Test + fun `test - showSettingChatBackupIndicator is false when BackupState is UNKNOWN but a backup exists on the server`() = runTest { + val encryptionService = FakeEncryptionService().apply { + givenDoesBackupExistOnServerResult(Result.success(true)) + } + val sessionVerificationService = FakeSessionVerificationService() + val sut = DefaultIndicatorService( + sessionVerificationService = sessionVerificationService, + encryptionService = encryptionService, + ) + moleculeFlow(RecompositionMode.Immediate) { + sut.showSettingChatBackupIndicator().value + }.test { + assertThat(awaitItem()).isTrue() + assertThat(awaitItem()).isFalse() + } + } + @Test fun `test - showSettingChatBackupIndicator is true when recoveryState is DISABLED`() = runTest { val encryptionService = FakeEncryptionService() diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/ClientUrlContentFetcher.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/ClientUrlContentFetcher.kt new file mode 100644 index 0000000000..611bf7bf18 --- /dev/null +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/ClientUrlContentFetcher.kt @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.api + +/** + * An interface to fetch content from a URL using a simple GET request launched from a Matrix client. + */ +interface ClientUrlContentFetcher { + /** + * The domain of the public server for this homeserver. + */ + val server: String? + + /** + * The URL of the actual Matrix homeserver. + */ + val homeserverUrl: String + + /** + * Execute generic GET requests through the SDKs internal HTTP client. + */ + suspend fun getUrl(url: String): Result +} diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/HomeserverCapabilitiesProvider.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/HomeserverCapabilitiesProvider.kt index e914656f5f..fe05b88dc4 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/HomeserverCapabilitiesProvider.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/HomeserverCapabilitiesProvider.kt @@ -10,6 +10,8 @@ package io.element.android.libraries.matrix.api /** * Provides information about the capabilities of the homeserver. * + * The getters read a snapshot held by the SDK rather than querying the server on each call, so [refresh] must be used to pick up server-side changes. + * * Spec: https://spec.matrix.org/latest/client-server-api/#capabilities-negotiation */ interface HomeserverCapabilitiesProvider { diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClient.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClient.kt index 0dd8821a4f..3f98dcc509 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClient.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClient.kt @@ -54,59 +54,246 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow import java.util.Optional -interface MatrixClient { +/** + * Entry point for everything scoped to a single logged in session: the sub-services, room access, and account level operations. + * + * One instance exists per session, created on login or session restore and torn down by [logout], [clearCache] or account deactivation. + * Suspending members here report failures through a [Result] instead of throwing, and run their work off the main thread. + */ +interface MatrixClient : ClientUrlContentFetcher { + /** Identifier of the logged in user; a [SessionId] and a [UserId] are the same value. */ val sessionId: SessionId + + /** Identifier of this device, as assigned by the homeserver when the session was created. */ val deviceId: DeviceId - /** Base URL of the homeserver this client is connected to. */ - val homeserverUrl: String + /** Directories holding this session's databases, caches and downloaded media. */ val sessionPaths: SessionPaths + + /** + * Display name and avatar of the logged in user. + * Seeded from the local session store so a value is available before the first network fetch, then kept up to date by the SDK. + */ val userProfile: StateFlow + + /** Gives access to the list of rooms the user is a member of, or has been invited to. */ val roomListService: RoomListService + + /** Gives access to the spaces the user belongs to and their hierarchy. */ val spaceService: SpaceService + + /** Controls the sync loop of this session and exposes its state. */ val syncService: SyncService + + /** Handles verifying this session against the user's other devices or their recovery key. */ val sessionVerificationService: SessionVerificationService + + /** Manages the push gateways (pushers) registered on the homeserver for this session. */ val pushersService: PushersService + + /** Resolves incoming push notifications into renderable events. */ val notificationService: NotificationService + + /** Reads and writes the push notification rules of the account. */ val notificationSettingsService: NotificationSettingsService + + /** Gives access to end-to-end encryption state, recovery and key backup. */ val encryptionService: EncryptionService + + /** Gives access to the public room directory of the homeserver. */ val roomDirectoryService: RoomDirectoryService /** Whether this live client was built with a message search index attached. */ val isMessageSearchAvailable: Boolean + + /** Searches messages in the local index; only usable when [isMessageSearchAvailable] is `true`. */ val messageSearchService: MessageSearchService + + /** Reads and writes the account settings controlling whether media previews and avatars are shown. */ val mediaPreviewService: MediaPreviewService + + /** Downloads media content, thumbnails and files from the homeserver, caching them on disk. */ val matrixMediaLoader: MatrixMediaLoader + + /** + * Coroutine scope tied to the lifetime of this session, to be used for work that must stop when the session goes away. + * It is cancelled when the session is logged out or otherwise destroyed, so never use it for work that must outlive the session. + */ val sessionCoroutineScope: CoroutineScope + + /** The users the logged in user has ignored; starts empty and is updated by the SDK, including with an initial value. */ val ignoredUsersFlow: StateFlow> + + /** Notifies of membership changes the current user makes, so that callers can react to leaving or joining a room. */ val roomMembershipObserver: RoomMembershipObserver + + /** Emits updates about the live location beacons published by the current user. */ val ownBeaconInfoUpdates: Flow + + /** Scans media content before it is displayed, or `null` when no content scanner is configured for this session. */ val contentScanner: ContentScanner? + + /** Whether the session is in the process of shutting down, either because it is being logged out or its cache is being cleared. */ + val isShuttingDown: Boolean + + /** + * Returns the room with the given id if the user has joined it, along with its live [Timeline]. + * A new instance is created on each call and the caller owns it, so it must be closed once no longer needed. + * + * @param roomId the id of the room to open. + * @return the room, or `null` if it is unknown to the client or the user is not joined. + */ suspend fun getJoinedRoom(roomId: RoomId): JoinedRoom? + + /** + * Returns the room with the given id whatever the current membership is, without building a timeline. + * As with [getJoinedRoom], a new instance is created on each call and must be closed by the caller. + * + * @param roomId the id of the room to open. + * @return the room, or `null` if it is unknown to the client. + */ suspend fun getRoom(roomId: RoomId): BaseRoom? + + /** + * Looks for an existing direct message room shared with [userId]. + * + * @param userId the other member of the direct message room. + * @return the room id, or `null` if no direct message room exists with this user. + */ suspend fun findDM(userId: UserId): Result + + /** + * Returns the ids of every room the user has joined, as currently known by the client. + * Invited, knocked and left rooms are excluded. + */ suspend fun getJoinedRoomIds(): Result> + + /** + * Adds [userId] to the ignore list of the account, which hides their events and makes [ignoredUsersFlow] emit. + * + * @param userId the user to ignore. + */ suspend fun ignoreUser(userId: UserId): Result + + /** + * Removes [userId] from the ignore list of the account, which makes [ignoredUsersFlow] emit. + * + * @param userId the user to stop ignoring. + */ suspend fun unignoreUser(userId: UserId): Result + + /** + * Creates a room, applying the app's default power levels on top of [createRoomParams]. + * Waits a short while for the new room to come back through sync, but a timeout there is only logged: the result is still a success. + * + * @param createRoomParams the name, topic, preset, invitees and other settings of the room to create. + */ suspend fun createRoom(createRoomParams: CreateRoomParameters): Result + + /** + * Creates a direct message room with [userId], as a private, invite-only room with the user already invited. + * This does not check whether such a room already exists; use [findDM] first if you want to reuse one. + * + * @param userId the user to start the direct message with. + * @param isEncrypted whether the room should have end-to-end encryption enabled. + */ suspend fun createDM(userId: UserId, isEncrypted: Boolean): Result + + /** + * Fetches the current profile of any user from the homeserver, bypassing the local cache. + * + * @param userId the user whose profile is requested. + */ suspend fun getProfile(userId: UserId): Result + + /** + * Searches the homeserver's user directory. + * + * @param searchTerm the text to look for in user ids and display names. + * @param limit the maximum number of results to return. + */ suspend fun searchUsers(searchTerm: String, limit: Long): Result + + /** + * Changes the display name of the logged in user on the homeserver. + * + * @param displayName the new display name. + */ suspend fun setDisplayName(displayName: String): Result + + /** + * Uploads [data] as the new avatar of the logged in user. + * + * @param mimeType the MIME type of the image, for instance `image/jpeg`. + * @param data the raw bytes of the image. + */ suspend fun uploadAvatar(mimeType: String, data: ByteArray): Result + + /** Removes the avatar of the logged in user. */ suspend fun removeAvatar(): Result + + /** + * Sets the `m.status` profile field of the logged in user (MSC4426), refreshing [userProfile] if the server does not push the change itself. + * + * @param status the status to publish. + */ suspend fun setUserStatus(status: UserStatus): Result /** Clears both m.status and m.call profile fields (maps to DELETE on the profile endpoint per MSC4426). */ suspend fun clearUserStatus(): Result + + /** Whether the homeserver advertises support for user status (MSC4426). */ + suspend fun isUserStatusSupported(): Result + + /** Whether the homeserver advertises support for the Profiles sliding sync extension (MSC4262). */ + suspend fun isProfilesSlidingSyncExtensionSupported(): Result + + /** + * Enable or disable automatically setting the user's status to "in a call" (m.call) while in a call. + * + * @param enabled whether the status should be maintained automatically. + */ + fun enableAutomaticCallStatus(enabled: Boolean) + + /** + * Joins a room the client already knows about, then waits briefly for the new membership to arrive through sync. + * The returned [RoomInfo] is `null` when that wait times out, which is not treated as a failure: the join itself succeeded. + * + * @param roomId the id of the room to join. + */ suspend fun joinRoom(roomId: RoomId): Result + + /** + * Joins a room by id or by alias, resolving it through [serverNames] when the client does not know it yet. + * As with [joinRoom], the returned [RoomInfo] is `null` if the membership did not arrive through sync in time. + * + * @param roomIdOrAlias the id or the alias of the room to join. + * @param serverNames servers to ask about the room, used when it cannot be resolved locally. + */ suspend fun joinRoomByIdOrAlias(roomIdOrAlias: RoomIdOrAlias, serverNames: List): Result + + /** + * Sends a request to join a room whose join rule is knock, then waits briefly for the knocked membership to arrive through sync. + * As with [joinRoom], the returned [RoomInfo] is `null` if that wait times out. + * + * @param roomIdOrAlias the id or the alias of the room to knock on. + * @param message the reason shown to the room moderators; may be empty. + * @param serverNames servers to ask about the room, used when it cannot be resolved locally. + */ suspend fun knockRoom(roomIdOrAlias: RoomIdOrAlias, message: String, serverNames: List): Result + + /** + * Returns the number of bytes this session occupies on disk that [clearCache] would be able to reclaim. + * This covers the cache directory, the state database and the message search index, but not the crypto database. + */ suspend fun getCacheSize(): Long + + /** Returns the size of each individual store the SDK maintains for this session, as reported by the SDK. */ suspend fun getDatabaseSizes(): Result /** - * Will close the client and delete the cache data. + * Deletes the cached data of this session and destroys the client. + * The instance is unusable afterwards, so callers are expected to restart the session, unlike with [logout] the session itself is kept. */ suspend fun clearCache() @@ -119,29 +306,56 @@ interface MatrixClient { suspend fun logout(userInitiated: Boolean, ignoreSdkError: Boolean) /** - * Retrieve the user profile, will also eventually emit a new value to [userProfile]. + * Retrieve the profile of the logged in user, emitting it to [userProfile] and persisting it in the local session store on success. */ suspend fun getUserProfile(): Result + + /** + * Returns the web URL where the user can manage their account on the authentication provider, or `null` if the homeserver exposes none. + * + * @param action an optional section of the account management page to open directly, such as changing the password. + */ suspend fun getAccountManagementUrl(action: AccountManagementAction?): Result + + /** + * Uploads arbitrary content to the homeserver's media repository. + * + * @param mimeType the MIME type of the content being uploaded. + * @param data the raw bytes to upload. + * @return the `mxc://` URI the content is now available at. + */ suspend fun uploadMedia(mimeType: String, data: ByteArray): Result /** * Get a room info flow for a given room ID. - * The flow will emit a new value whenever the room info is updated. - * The flow will emit Optional.empty item if the room is not found. + * The flow will emit a new value whenever the room info is updated, skipping duplicates, and an empty [Optional] if the room is not found. + * + * @param roomId the id of the room to observe. */ fun getRoomInfoFlow(roomId: RoomId): Flow> + /** + * Whether [userId] is the logged in user, `false` for a `null` value. + * + * @param userId the user id to compare against this session's user. + */ fun isMe(userId: UserId?) = userId == sessionId + /** + * Adds a room to the account's list of recently visited rooms, which backs the room suggestions when sharing or forwarding. + * + * @param roomId the id of the room that was just visited. + */ suspend fun trackRecentlyVisitedRoom(roomId: RoomId): Result + + /** Returns the recently visited rooms of the account, most recent first. */ suspend fun getRecentlyVisitedRooms(): Result> /** * Resolves the given room alias to a roomID (and a list of servers), if possible. - * @param roomAlias the room alias to resolve - * @return the resolved room alias if any, an empty result if not found,or an error if the resolution failed. * + * @param roomAlias the room alias to resolve. + * @return the resolved room alias if any, an empty result if not found, or an error if the resolution failed. */ suspend fun resolveRoomAlias(roomAlias: RoomAlias): Result> @@ -152,6 +366,8 @@ interface MatrixClient { * event with it failed (e.g. sending an event via the Timeline), * so it's required to manually re-enable it as soon as * connectivity is back on the device. + * + * @param enabled whether the send queues of every room should be enabled. */ suspend fun setAllSendQueuesEnabled(enabled: Boolean) @@ -167,13 +383,11 @@ interface MatrixClient { */ fun userIdServerName(): String - /** - * Execute generic GET requests through the SDKs internal HTTP client. - */ - suspend fun getUrl(url: String): Result - /** * Get a room preview for a given room ID or alias. This is especially useful for rooms that the user is not a member of, or hasn't joined yet. + * + * @param roomIdOrAlias the id or the alias of the room to preview. + * @param serverNames servers to ask about the room, used when it cannot be resolved locally. */ suspend fun getRoomPreview(roomIdOrAlias: RoomIdOrAlias, serverNames: List): Result @@ -182,11 +396,21 @@ interface MatrixClient { */ suspend fun currentSlidingSyncVersion(): Result + /** Whether this account can be deactivated from the app, which depends on the authentication method used by the homeserver. */ fun canDeactivateAccount(): Boolean + + /** + * Deactivates the account on the homeserver, then destroys this client and deletes every local trace of the session. + * The password is only sent if the homeserver asks for re-authentication, and on failure the session is left untouched. + * + * @param password the account password, required to confirm the deactivation. + * @param eraseData whether the homeserver should also erase the messages the user sent. + */ suspend fun deactivateAccount(password: String, eraseData: Boolean): Result /** - * Check if the user can report a room. + * Whether the homeserver supports reporting a whole room, rather than individual events. + * Returns `false` if the capability cannot be determined. */ suspend fun canReportRoom(): Boolean @@ -207,14 +431,34 @@ interface MatrixClient { /** * Adds an emoji to the list of recent emoji reactions for this account. + * + * @param emoji the emoji that was just used. */ suspend fun addRecentEmoji(emoji: String): Result + /** + * Returns the raw JSON content of the global account data event of type [eventType], or null if it is not set. + * + * @param eventType the Matrix event type of the account data to read, for instance `m.direct`. + */ + suspend fun getAccountData(eventType: String): Result + + /** + * Sets the global account data event of type [eventType] to the raw JSON [content]. + * + * @param eventType the Matrix event type of the account data to write. + * @param content the new content, as a raw JSON object. + */ + suspend fun setAccountData(eventType: String, content: String): Result + /** * Marks the room with the provided [roomId] as read, sending a fully read receipt for [eventId]. * * This method should be used with caution as providing the [eventId] ourselves can result in incorrect read receipts. * Use [Timeline.markAsRead] instead when possible. + * + * @param roomId the id of the room to mark as read. + * @param eventId the event up to which the room is considered read. */ suspend fun markRoomAsFullyRead(roomId: RoomId, eventId: EventId): Result @@ -241,19 +485,16 @@ interface MatrixClient { /** * Performs a database optimization that should flush cached data and improve performance. + * A periodic background job already calls this for every session, so callers rarely need to trigger it by hand. */ suspend fun performDatabaseVacuum(): Result - /** - * Returns the URL of the map style configured on the server, if any. - */ - suspend fun getMapStyleUrl(): Result - /** * Resets the cached client `well-known` config by the SDK. */ suspend fun resetWellKnownConfig(): Result + /** Returns a provider for the capabilities the homeserver advertises, such as whether the display name can be changed. */ fun homeserverCapabilities(): HomeserverCapabilitiesProvider } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClientBuilder.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClientBuilder.kt new file mode 100644 index 0000000000..730561bbef --- /dev/null +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClientBuilder.kt @@ -0,0 +1,13 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.api + +/** + * An abstraction over the Matrix SDK's `ClientBuilder` to allow sharing it with other modules without exposing the SDK directly. + */ +interface MatrixClientBuilder diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClientProvider.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClientProvider.kt index 54f70845fa..08073d0cc0 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClientProvider.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/MatrixClientProvider.kt @@ -10,18 +10,26 @@ package io.element.android.libraries.matrix.api import io.element.android.libraries.matrix.api.core.SessionId +/** + * In-memory cache of the [MatrixClient] of every logged in session. + * + * Prefer injecting the [MatrixClient] directly: this provider is meant for the entry points that only know a [SessionId], such as push handling and workers. + */ interface MatrixClientProvider { /** - * Can be used to get or restore a MatrixClient with the given [SessionId]. - * If a [MatrixClient] is already in memory, it'll return it. Otherwise it'll try to restore one. - * Most of the time you want to use injected constructor instead of retrieving a MatrixClient with this provider. + * Returns the cached [MatrixClient] for [sessionId], restoring the session from storage and starting its sync if it is not in memory yet. + * Concurrent calls are serialised, so only one restore happens per session. + * + * @param sessionId the [SessionId] of the session to get or restore. + * @return the client, or a failure if the session could not be restored. */ suspend fun getOrRestore(sessionId: SessionId): Result /** - * Can be used to retrieve an existing [MatrixClient] with the given [SessionId]. - * @param sessionId the [SessionId] of the [MatrixClient] to retrieve. - * @return the [MatrixClient] if it exists. + * Returns the [MatrixClient] for [sessionId] only if it is already in memory, without attempting to restore it. + * + * @param sessionId the [SessionId] of the session to retrieve. + * @return the cached client, or `null` if that session is not currently held in memory. */ fun getOrNull(sessionId: SessionId): MatrixClient? } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/SdkMetadata.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/SdkMetadata.kt index 16f34807fc..939734e314 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/SdkMetadata.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/SdkMetadata.kt @@ -8,6 +8,14 @@ package io.element.android.libraries.matrix.api +/** + * Exposes build information about the bundled `matrix-rust-sdk`. + * + * Mostly used to identify the exact SDK revision in bug reports and in the user agent. + */ interface SdkMetadata { + /** + * The full git SHA of the commit the bundled `matrix-rust-sdk` was built from. + */ val sdkGitSha: String } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/TemporaryMatrixClient.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/TemporaryMatrixClient.kt new file mode 100644 index 0000000000..5013362f85 --- /dev/null +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/TemporaryMatrixClient.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.api + +import java.lang.AutoCloseable + +/** + * A Matrix client in an 'unauthenticated' state that can still be used to resolve URLs. + * + * Note: this client implements an [AutoCloseable] interface, so using [AutoCloseable.close] or [AutoCloseable.use] will clean up any resources associated + * with it, such as temporary files. + */ +interface TemporaryMatrixClient : ClientUrlContentFetcher, AutoCloseable diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/TemporaryMatrixClientFactory.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/TemporaryMatrixClientFactory.kt new file mode 100644 index 0000000000..c3244b4742 --- /dev/null +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/TemporaryMatrixClientFactory.kt @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.api + +/** + * Factory to create a temporary [TemporaryMatrixClient] for a given home server URL. + */ +interface TemporaryMatrixClientFactory { + /** + * Builds an unauthenticated client pointing at [serverName], backed by a fresh set of temporary session directories. + * The caller owns the returned client and must close it to delete those directories. + * + * @param serverName the domain of the public-facing server for the actual homeserver + */ + suspend fun create(serverName: String): Result +} diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/analytics/GetDatabaseSizesUseCase.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/analytics/GetDatabaseSizesUseCase.kt index fde02fb2c6..1ca9adfaca 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/analytics/GetDatabaseSizesUseCase.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/analytics/GetDatabaseSizesUseCase.kt @@ -9,6 +9,14 @@ package io.element.android.libraries.matrix.api.analytics import io.element.android.libraries.matrix.api.core.SessionId +/** + * Reads the on-disk size of a session's SDK stores, so they can be reported as analytics. + */ fun interface GetDatabaseSizesUseCase { + /** + * Returns the size of each store of the given session. + * + * @param sessionId the session whose stores are measured. + */ operator fun invoke(sessionId: SessionId): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/MatrixAuthenticationService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/MatrixAuthenticationService.kt index 04d1d13593..3ff1eaa337 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/MatrixAuthenticationService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/MatrixAuthenticationService.kt @@ -16,23 +16,41 @@ import io.element.android.libraries.matrix.api.auth.qrlogin.QrCodeLoginStep import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.matrix.api.core.UserId +/** + * Creates and restores sessions: password login, OAuth login, QR code login, and importing a session from another client. + * + * [setHomeserver] must be called before any login attempt, since it is what tells the SDK which server to authenticate against. + * Every successful login stores the session and notifies the listeners registered through [listenToNewMatrixClients]. + */ interface MatrixAuthenticationService { /** * Restore a session from a [sessionId]. * Do not restore anything it the access token is not valid anymore. * Generally this method should not be used directly, prefer using [MatrixClientProvider.getOrRestore] instead. + * + * @param sessionId the session to restore. */ suspend fun restoreSession(sessionId: SessionId): Result /** * Set the homeserver to use for authentication, and return its details. + * + * @param homeserver the homeserver URL or server name to authenticate against. */ suspend fun setHomeserver(homeserver: String): Result + /** + * Logs in with a password on the homeserver previously set through [setHomeserver]. + * + * @param username the user id or its local part. + * @param password the account password. + */ suspend fun login(username: String, password: String): Result /** * Import a session that was created using another client, for instance Element Web. + * + * @param externalSession the tokens and identifiers of the session to import. */ suspend fun importCreatedSession(externalSession: ExternalSession): Result @@ -42,6 +60,9 @@ interface MatrixAuthenticationService { /** * Get the OAuth url to display to the user. + * + * @param prompt whether the authentication server should show the sign-in or the account-creation page. + * @param loginHint the user identifier to pre-fill on that page, or `null` to leave it empty. */ suspend fun getOAuthUrl( prompt: OAuthPrompt, @@ -55,11 +76,17 @@ interface MatrixAuthenticationService { /** * Set the existing data about Element Classic session, if any. + * + * @param session the session found in a local Element Classic install, or `null` when there is none to migrate. */ fun setElementClassicSession(session: ElementClassicSession?) /** * Check if the provided secrets from Element Classic session contain a key backup. + * + * @param userId the user the secrets belong to. + * @param secrets the raw secrets exported from Element Classic. + * @param backupInfo the raw backup description exported alongside them. */ fun doSecretsContainBackupKey( userId: UserId, @@ -69,11 +96,23 @@ interface MatrixAuthenticationService { /** * Attempt to log in using the [callbackUrl] provided by the OAuth page. + * + * @param callbackUrl the redirect URL the authentication server sent the user back to, carrying the authorization code. */ suspend fun loginWithOAuth(callbackUrl: String): Result + /** + * Logs in by acting on a QR code shown by an already signed in device, reporting each step of the exchange as it happens. + * + * @param qrCodeData the decoded QR code, obtained from [io.element.android.libraries.matrix.api.auth.qrlogin.MatrixQrCodeLoginDataFactory]. + * @param progress called on every step of the flow, so the UI can follow along. + */ suspend fun loginWithQrCode(qrCodeData: MatrixQrCodeLoginData, progress: (QrCodeLoginStep) -> Unit): Result - /** Listen to new Matrix clients being created on authentication. */ + /** + * Listen to new Matrix clients being created on authentication. + * + * @param lambda called with each client created by a successful login or session restore. + */ fun listenToNewMatrixClients(lambda: (MatrixClient) -> Unit) } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthConfig.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthConfig.kt index 3256d0545c..b3ee0878d5 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthConfig.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthConfig.kt @@ -11,6 +11,8 @@ package io.element.android.libraries.matrix.api.auth import io.element.android.libraries.matrix.api.BuildConfig object OAuthConfig { + // This *can* be null if the build time config field is not set + @Suppress("UNNECESSARY_SAFE_CALL") val CLIENT_URI = BuildConfig.OAUTH_CLIENT_URI_PATH?.let { // Concatenate the base URI and the path, ensuring there is exactly one '/' between them "${BuildConfig.CLIENT_URI.trimEnd('/')}/${it.trimStart('/')}" diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthRedirectUrlProvider.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthRedirectUrlProvider.kt index 669d47501d..648884e930 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthRedirectUrlProvider.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/OAuthRedirectUrlProvider.kt @@ -8,6 +8,10 @@ package io.element.android.libraries.matrix.api.auth +/** + * Provides the redirect URL registered for OAuth login, which the authentication server sends the user back to once they have signed in. + */ interface OAuthRedirectUrlProvider { + /** Returns the redirect URL, built from the app's custom URL scheme so that the system hands the callback back to the app. */ fun provide(): String } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginData.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginData.kt index 413f17af63..f800ad2ba1 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginData.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginData.kt @@ -8,6 +8,12 @@ package io.element.android.libraries.matrix.api.auth.qrlogin +/** + * The decoded content of a login QR code, as produced by [MatrixQrCodeLoginDataFactory]. + * + * The underlying data is opaque to the app: it is passed back to the SDK to perform the login. + */ interface MatrixQrCodeLoginData { + /** The homeserver advertised by the QR code, or `null` when it does not carry one. */ fun serverName(): String? } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginDataFactory.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginDataFactory.kt index b0e3089501..21d77b74f2 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginDataFactory.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/auth/qrlogin/MatrixQrCodeLoginDataFactory.kt @@ -8,6 +8,14 @@ package io.element.android.libraries.matrix.api.auth.qrlogin +/** + * Decodes the raw bytes of a scanned QR code into login data the SDK can use. + */ interface MatrixQrCodeLoginDataFactory { + /** + * Parses the scanned bytes, failing with a [QrCodeDecodeException] when they are not a valid Matrix login QR code. + * + * @param data the raw content read from the QR code. + */ fun parseQrCodeData(data: ByteArray): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/ProgressCallback.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/ProgressCallback.kt index a7abc0f797..5c8a75e384 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/ProgressCallback.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/ProgressCallback.kt @@ -8,6 +8,15 @@ package io.element.android.libraries.matrix.api.core +/** + * Reports the progress of a long running transfer, such as a media upload or download. + */ interface ProgressCallback { + /** + * Called as the transfer advances, possibly many times and from a background thread. + * + * @param current the number of bytes transferred so far. + * @param total the total number of bytes to transfer. + */ fun onProgress(current: Long, total: Long) } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/SendHandle.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/SendHandle.kt index f3b8904fff..02c8a85d58 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/SendHandle.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/core/SendHandle.kt @@ -8,6 +8,10 @@ package io.element.android.libraries.matrix.api.core +/** + * A handle on an event sitting in a room's send queue, obtained from a timeline item that failed to send. + */ fun interface SendHandle { + /** Puts the event back in the send queue for another attempt. */ suspend fun retry(): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/encryption/EncryptionService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/encryption/EncryptionService.kt index f82cdc1969..e036a198df 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/encryption/EncryptionService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/encryption/EncryptionService.kt @@ -14,13 +14,32 @@ import io.element.android.libraries.matrix.api.encryption.identity.IdentityState import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow +/** + * Gives access to the end-to-end encryption state of the session: key backup, recovery, and the trust of other users' identities. + */ interface EncryptionService { + /** + * The state of the room key backup on the server. + * Reports [BackupState.WAITING_FOR_SYNC] for as long as the session is not actively syncing, since the real state is unknown until then. + */ val backupStateStateFlow: StateFlow + + /** + * The state of recovery, i.e. whether the secrets needed to restore the keys on a new device are available. + * As with [backupStateStateFlow], it reports a waiting-for-sync state until the session is syncing. + */ val recoveryStateStateFlow: StateFlow + + /** Progress of the [enableRecovery] call currently in flight, to be observed while that call is running. */ val enableRecoveryProgressStateFlow: StateFlow + + /** Whether this is the only device of the account, which matters because logging out of it can make the room keys unrecoverable. */ val isLastDevice: StateFlow + + /** Whether the account has another device this one could be verified against; it stays loading until the first answer arrives. */ val hasDevicesToVerifyAgainst: StateFlow> + /** Enables the room key backup on the server, so that the keys survive losing every device. */ suspend fun enableBackups(): Result /** @@ -39,12 +58,16 @@ interface EncryptionService { */ suspend fun resetRecoveryKey(): Result + /** Disables recovery, which deletes the secrets from server-side storage; the key backup itself is left in place. */ suspend fun disableRecovery(): Result + /** Whether a room key backup currently exists on the server, whether or not this device is the one using it. */ suspend fun doesBackupExistOnServer(): Result /** - * Note: accept both recoveryKey and passphrase. + * Restores the secrets from server-side storage, which unlocks the room key backup for this device. + * + * @param recoveryKey the recovery key, or the passphrase it was derived from; both are accepted. */ suspend fun recover(recoveryKey: String): Result @@ -72,6 +95,8 @@ interface EncryptionService { /** * Remember this identity, ensuring it does not result in a pin violation. + * + * @param userId the user whose current identity should be pinned. */ suspend fun pinUserIdentity(userId: UserId): Result @@ -81,6 +106,8 @@ interface EncryptionService { * Useful when a user that was verified is not anymore, but it is not * possible to re-verify immediately. This allows to restore communication by reverting the * user trust from verified to TOFU verified. + * + * @param userId the user whose verification should be withdrawn. */ suspend fun withdrawVerification(userId: UserId): Result diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/CheckCodeSender.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/CheckCodeSender.kt index ecb440de83..a3a518f9ce 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/CheckCodeSender.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/CheckCodeSender.kt @@ -7,6 +7,9 @@ package io.element.android.libraries.matrix.api.linknewdevice +/** + * Lets the user confirm the two-digit check code displayed by the device being linked, which proves the channel is not being intercepted. + */ interface CheckCodeSender { /** * Validates the given [code]. Returns true if the code is valid, false otherwise. diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/ContinuationMessageSender.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/ContinuationMessageSender.kt new file mode 100644 index 0000000000..0a2ce273d5 --- /dev/null +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/ContinuationMessageSender.kt @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.api.linknewdevice + +/** + * Lets the user confirm or refuse a device linking request once they have approved it in the browser. + * + * Handed out with the step that is waiting for authorisation; exactly one of the two methods is meant to be called. + */ +interface ContinuationMessageSender { + /** Tells the other device that the user refused the linking, which ends the flow. */ + suspend fun cancel(): Result + + /** Tells the other device that the user approved the linking, so the flow can carry on. */ + suspend fun confirm(): Result +} diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkDesktopHandler.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkDesktopHandler.kt index d600c1a8bf..26c2ed04c4 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkDesktopHandler.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkDesktopHandler.kt @@ -10,16 +10,32 @@ package io.element.android.libraries.matrix.api.linknewdevice import io.element.android.libraries.matrix.api.auth.qrlogin.QrCodeDecodeException import kotlinx.coroutines.flow.StateFlow +/** + * Drives the linking of a new device that cannot scan a QR code, such as a desktop: this device scans the code the other one displays. + * + * Progress is reported entirely through [linkDesktopStep]; there is one handler per attempt, obtained from + * [io.element.android.libraries.matrix.api.MatrixClient.createLinkDesktopHandler]. + */ interface LinkDesktopHandler { + /** Each step of the flow, from establishing the secure channel to syncing the secrets to the new device. */ val linkDesktopStep: StateFlow + + /** + * Runs the whole flow from the QR code just scanned, suspending until it finishes or fails. + * A code that cannot be decoded is reported as an invalid-QR-code step rather than as a thrown error. + * + * @param data the raw content read from the QR code shown by the other device. + */ suspend fun handleScannedQrCode(data: ByteArray) } sealed interface LinkDesktopStep { data object Uninitialized : LinkDesktopStep data object Starting : LinkDesktopStep + data class WaitingForAuth( val verificationUri: String, + val continuationMessageSender: ContinuationMessageSender, ) : LinkDesktopStep data class EstablishingSecureChannel( diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkMobileHandler.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkMobileHandler.kt index eb2d49b5b0..ae51eb1f0a 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkMobileHandler.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/linknewdevice/LinkMobileHandler.kt @@ -9,8 +9,17 @@ package io.element.android.libraries.matrix.api.linknewdevice import kotlinx.coroutines.flow.Flow +/** + * Drives the linking of a new device that is able to scan a QR code, by showing one on this already signed in device. + * + * Progress is reported entirely through [linkMobileStep]; there is one handler per attempt, obtained from + * [io.element.android.libraries.matrix.api.MatrixClient.createLinkMobileHandler]. + */ interface LinkMobileHandler { + /** Each step of the flow, from generating the QR code to syncing the secrets to the new device. */ val linkMobileStep: Flow + + /** Runs the whole flow, suspending until it finishes or fails; the outcome is reported through [linkMobileStep]. */ suspend fun start() } @@ -22,7 +31,12 @@ sealed interface LinkMobileStep { data object Starting : LinkMobileStep data class QrReady(val data: String) : LinkMobileStep data object QrRotating : LinkMobileStep - data class WaitingForAuth(val verificationUri: String) : LinkMobileStep + + data class WaitingForAuth( + val verificationUri: String, + val continuationMessageSender: ContinuationMessageSender, + ) : LinkMobileStep + data class QrScanned(val checkCodeSender: CheckCodeSender) : LinkMobileStep data class Error(val errorType: ErrorType) : LinkMobileStep data object SyncingSecrets : LinkMobileStep diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MatrixMediaLoader.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MatrixMediaLoader.kt index a36849b812..28ae0762ff 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MatrixMediaLoader.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MatrixMediaLoader.kt @@ -8,6 +8,9 @@ package io.element.android.libraries.matrix.api.media +/** + * Fetches media content from the homeserver, decrypting it on the way when the room is encrypted. + */ interface MatrixMediaLoader { /** * @param source to fetch the content for. diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaFile.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaFile.kt index b5cefe897b..ae6035da88 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaFile.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaFile.kt @@ -16,6 +16,7 @@ import java.io.File * When closed the file will be removed from the disk unless [persist] has been used. */ interface MediaFile : Closeable { + /** The absolute path of the file on disk; see [toFile] to get a [File] instead. */ fun path(): String /** diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaPreviewService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaPreviewService.kt index 39718ddfd2..660bb0b80e 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaPreviewService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/media/MediaPreviewService.kt @@ -10,6 +10,11 @@ package io.element.android.libraries.matrix.api.media import kotlinx.coroutines.flow.StateFlow +/** + * Reads and writes the account settings that decide whether media previews and invite avatars are shown. + * + * These are account data settings shared across clients, so the local value is only updated once the server has accepted the change. + */ interface MediaPreviewService { /** * Will fetch the media preview config from the server. @@ -24,11 +29,15 @@ interface MediaPreviewService { /** * Set the media preview display policy. This will update the value on the server and update the local value when successful. + * + * @param mediaPreviewValue whether media previews are shown always, never, or only in private rooms. */ suspend fun setMediaPreviewValue(mediaPreviewValue: MediaPreviewValue): Result /** * Set the invite avatars display policy. This will update the value on the server and update the local value when successful. + * + * @param hide true to hide the avatars of users and rooms the user has been invited by. */ suspend fun setHideInviteAvatars(hide: Boolean): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/mxc/MxcTools.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/mxc/MxcTools.kt index 09ceaa4712..c28bfa9933 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/mxc/MxcTools.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/mxc/MxcTools.kt @@ -8,6 +8,9 @@ package io.element.android.libraries.matrix.api.mxc +/** + * Helpers to work with Matrix Content (`mxc://`) URIs. + */ interface MxcTools { /** * Sanitizes an mxcUri to be used as a relative file path. diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notification/NotificationService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notification/NotificationService.kt index 369587cd10..3a3fbeaa19 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notification/NotificationService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notification/NotificationService.kt @@ -24,6 +24,9 @@ typealias GetNotificationDataResult = Result>): GetNotificationDataResult } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notificationsettings/NotificationSettingsService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notificationsettings/NotificationSettingsService.kt index 7ae1ca4886..7226de9a9d 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notificationsettings/NotificationSettingsService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/notificationsettings/NotificationSettingsService.kt @@ -11,28 +11,114 @@ package io.element.android.libraries.matrix.api.notificationsettings import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.room.RoomNotificationMode import io.element.android.libraries.matrix.api.room.RoomNotificationSettings -import io.element.android.libraries.matrix.api.room.RoomNotificationSettingsState import kotlinx.coroutines.flow.SharedFlow +/** + * Reads and writes the push rules of the account, which decide what generates a notification. + * + * Rules are account data shared across clients, so a change made here is visible on the user's other devices. + * Several methods take the encryption and one-to-one nature of a room, because Matrix keeps a separate default rule for each combination. + */ interface NotificationSettingsService { /** - * State of the current room notification settings flow ([RoomNotificationSettingsState.Unknown] if not started). + * Emits every time the push rules change, whether from this client or another one, without saying what changed. + * Callers are expected to re-read the values they display; only the most recent signal is buffered. */ val notificationSettingsChangeFlow: SharedFlow + + /** + * Returns the notification settings that apply to one room, which may come from a room specific rule or from the matching default. + * + * @param roomId the room to read the settings of. + * @param isEncrypted whether that room is encrypted, which selects the relevant default rule. + * @param isOneToOne whether that room is a direct message, which selects the relevant default rule. + */ suspend fun getRoomNotificationSettings(roomId: RoomId, isEncrypted: Boolean, isOneToOne: Boolean): Result + + /** + * Returns the default notification mode used by rooms that have no rule of their own. + * + * @param isEncrypted whether to read the default for encrypted rooms. + * @param isOneToOne whether to read the default for direct messages. + */ suspend fun getDefaultRoomNotificationMode(isEncrypted: Boolean, isOneToOne: Boolean): Result + + /** + * Changes the default notification mode for a whole category of rooms. + * + * @param isEncrypted whether to change the default for encrypted rooms. + * @param mode the new default mode. + * @param isDM whether to change the default for direct messages. + */ suspend fun setDefaultRoomNotificationMode(isEncrypted: Boolean, mode: RoomNotificationMode, isDM: Boolean): Result + + /** + * Sets a room specific notification mode, which from then on overrides the default for that room. + * + * @param roomId the room to change. + * @param mode the new mode for that room. + */ suspend fun setRoomNotificationMode(roomId: RoomId, mode: RoomNotificationMode): Result + + /** + * Removes the room specific rule so the room follows the matching default again. + * + * @param roomId the room to reset. + */ suspend fun restoreDefaultRoomNotificationMode(roomId: RoomId): Result + + /** + * Mutes a room, which is a room specific rule like any other and is undone by [unmuteRoom]. + * + * @param roomId the room to mute. + */ suspend fun muteRoom(roomId: RoomId): Result + + /** + * Unmutes a room, restoring either its previous room specific mode or the matching default. + * + * @param roomId the room to unmute. + * @param isEncrypted whether that room is encrypted, which selects the relevant default rule. + * @param isOneToOne whether that room is a direct message, which selects the relevant default rule. + */ suspend fun unmuteRoom(roomId: RoomId, isEncrypted: Boolean, isOneToOne: Boolean): Result + + /** Whether being mentioned through `@room` generates a notification. */ suspend fun isRoomMentionEnabled(): Result + + /** + * Sets whether being mentioned through `@room` generates a notification. + * + * @param enabled true to be notified of `@room` mentions. + */ suspend fun setRoomMentionEnabled(enabled: Boolean): Result + + /** Whether incoming calls generate a notification. */ suspend fun isCallEnabled(): Result + + /** + * Sets whether incoming calls generate a notification. + * + * @param enabled true to be notified of incoming calls. + */ suspend fun setCallEnabled(enabled: Boolean): Result + + /** Whether room invitations generate a notification. */ suspend fun isInviteForMeEnabled(): Result + + /** + * Sets whether room invitations generate a notification. + * + * @param enabled true to be notified of invitations. + */ suspend fun setInviteForMeEnabled(enabled: Boolean): Result + + /** The rooms that have an enabled rule of their own rather than following the defaults. */ suspend fun getRoomsWithUserDefinedRules(): Result> + + /** Whether the homeserver is able to push encrypted events to the device, which decides how much a notification can show before decryption. */ suspend fun canHomeServerPushEncryptedEventsToDevice(): Result + + /** The push rules as raw JSON, for debugging and bug reports; `null` when the server returned none. */ suspend fun getRawPushRules(): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/MatrixToConverter.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/MatrixToConverter.kt index cc3e2b5cf6..d6a2e71b8f 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/MatrixToConverter.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/MatrixToConverter.kt @@ -20,6 +20,9 @@ interface MatrixToConverter { * - https://riot.im/develop/#/room/#element-android:matrix.org -> https://matrix.to/#/#element-android:matrix.org * - https://app.element.io/#/room/#element-android:matrix.org -> https://matrix.to/#/#element-android:matrix.org * - https://www.example.org/#/room/#element-android:matrix.org -> https://matrix.to/#/#element-android:matrix.org + * + * @param uri the uri to convert. + * @return the equivalent matrix.to uri, or `null` when the input is not a permalink this converter recognises. */ fun convert(uri: Uri): Uri? } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkBuilder.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkBuilder.kt index 878b0e7a69..9140c312c7 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkBuilder.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkBuilder.kt @@ -11,8 +11,22 @@ package io.element.android.libraries.matrix.api.permalink import io.element.android.libraries.matrix.api.core.RoomAlias import io.element.android.libraries.matrix.api.core.UserId +/** + * Builds `matrix.to` permalinks, which are the shareable links to a user or a room; see [PermalinkParser] for the other direction. + */ interface PermalinkBuilder { + /** + * Builds a permalink to a user, failing with [PermalinkBuilderError.InvalidData] when the id is malformed. + * + * @param userId the user to link to. + */ fun permalinkForUser(userId: UserId): Result + + /** + * Builds a permalink to a room from its alias, failing with [PermalinkBuilderError.InvalidData] when the alias is malformed. + * + * @param roomAlias the room alias to link to. + */ fun permalinkForRoomAlias(roomAlias: RoomAlias): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkParser.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkParser.kt index 5365b8776a..467b147d98 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkParser.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/permalink/PermalinkParser.kt @@ -18,7 +18,10 @@ package io.element.android.libraries.matrix.api.permalink interface PermalinkParser { /** * Turns a uri string to a [PermalinkData]. + * A uri that is not a Matrix permalink is reported as a fallback link rather than as an error, so this never throws. * https://github.com/matrix-org/matrix-doc/blob/master/proposals/1704-matrix.to-permalinks.md + * + * @param uriString the uri to parse. */ fun parse(uriString: String): PermalinkData } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/pusher/PushersService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/pusher/PushersService.kt index 6764598235..1eafe8ab49 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/pusher/PushersService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/pusher/PushersService.kt @@ -8,7 +8,21 @@ package io.element.android.libraries.matrix.api.pusher +/** + * Registers and removes the pusher of this session, i.e. the HTTP gateway the homeserver sends push notifications to. + */ interface PushersService { + /** + * Registers or updates the pusher; calling it again with the same push key replaces the existing registration. + * + * @param setHttpPusherData the gateway URL, the push key and the other details the homeserver needs to reach the device. + */ suspend fun setHttpPusher(setHttpPusherData: SetHttpPusherData): Result + + /** + * Removes the pusher, so the homeserver stops sending push notifications to this device. + * + * @param unsetHttpPusherData the push key and app id identifying the registration to remove. + */ suspend fun unsetHttpPusher(unsetHttpPusherData: UnsetHttpPusherData): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/BaseRoom.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/BaseRoom.kt index d49343f998..ab65b00f08 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/BaseRoom.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/BaseRoom.kt @@ -66,21 +66,30 @@ interface BaseRoom : Closeable { */ fun isDm() = roomInfoFlow.value.isDm + /** + * The room this one replaced when it was upgraded, or `null` if this room has no predecessor. + * Errors are swallowed and reported as `null`. + */ fun predecessorRoom(): PredecessorRoom? /** * Try to load the room members and update the membersFlow. + * The first call may serve members from the local cache before the server response arrives; later calls always go to the server. */ suspend fun updateMembers() /** * Get the members of the room. Note: generally this should not be used, please use * [membersStateFlow] and [updateMembers] instead. + * + * @param limit the maximum number of members to return. */ suspend fun getMembers(limit: Int = 5): Result> /** * Will return an updated member or an error. + * + * @param userId the member to fetch. */ suspend fun getUpdatedMember(userId: UserId): Result @@ -103,6 +112,8 @@ interface BaseRoom : Closeable { /** * Gets the role of the user with the provided [userId] in the room. + * + * @param userId the member whose role is requested. */ suspend fun userRole(userId: UserId): Result @@ -113,11 +124,15 @@ interface BaseRoom : Closeable { /** * Gets the display name of the user with the provided [userId] in the room. + * + * @param userId the member whose room specific display name is requested. */ suspend fun userDisplayName(userId: UserId): Result /** * Gets the avatar of the user with the provided [userId] in the room. + * + * @param userId the member whose room specific avatar is requested. */ suspend fun userAvatarUrl(userId: UserId): Result @@ -138,6 +153,8 @@ interface BaseRoom : Closeable { /** * Sets the room as favorite or not, based on the [isFavorite] parameter. + * + * @param isFavorite true to mark the room as favorite, false to remove the flag. */ suspend fun setIsFavorite(isFavorite: Boolean): Result @@ -176,22 +193,29 @@ interface BaseRoom : Closeable { suspend fun getRoomVisibility(): Result /** - * Returns the visibility for this room in the room directory, fetching it from the homeserver if needed. + * Returns whether this room is encrypted, based on the latest encryption state known to the SDK rather than on the cached [RoomInfo]. */ suspend fun getUpdatedIsEncrypted(): Result /** * Store the given `ComposerDraft` in the state store of this room. + * + * @param composerDraft the unsent message content to remember. + * @param threadRoot the thread the draft belongs to, or `null` for the main timeline. */ suspend fun saveComposerDraft(composerDraft: ComposerDraft, threadRoot: ThreadId?): Result /** * Retrieve the `ComposerDraft` stored in the state store for this room. + * + * @param threadRoot the thread whose draft is requested, or `null` for the main timeline. */ suspend fun loadComposerDraft(threadRoot: ThreadId?): Result /** * Clear the `ComposerDraft` stored in the state store for this room. + * + * @param threadRoot the thread whose draft should be cleared, or `null` for the main timeline. */ suspend fun clearComposerDraft(threadRoot: ThreadId?): Result @@ -202,10 +226,27 @@ interface BaseRoom : Closeable { */ suspend fun reportRoom(reason: String?): Result + /** + * Declines the incoming call advertised by the given notification, letting the other devices of the room know. + * + * @param notificationEventId the id of the call notification event being declined. + */ suspend fun declineCall(notificationEventId: EventId): Result + /** + * Emits the id of each user who declines the call advertised by the given notification. + * Used to stop ringing once the callee has declined from another device. + * + * @param notificationEventId the id of the call notification event to watch. + */ suspend fun subscribeToCallDecline(notificationEventId: EventId): Flow + /** + * Returns the id of the thread the given event belongs to, fetching the event from the server if it is not cached locally. + * + * @param eventId the event whose thread is requested. + * @return the thread root id, or `null` if the event is not part of a thread. + */ suspend fun threadRootIdForEvent(eventId: EventId): Result /** @@ -213,5 +254,6 @@ interface BaseRoom : Closeable { */ fun destroy() + /** Same as [destroy], so that a room can be used with `use { }`. */ override fun close() = destroy() } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/JoinedRoom.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/JoinedRoom.kt index 6d8325427b..98498131f9 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/JoinedRoom.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/JoinedRoom.kt @@ -28,11 +28,28 @@ import io.element.android.libraries.matrix.api.widget.MatrixWidgetSettings import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow +/** + * A room the current user has joined, adding to [BaseRoom] everything that requires membership: sending events, moderation and room settings. + * + * An instance owns SDK resources, in particular [liveTimeline], so it must be closed once no longer needed. + */ interface JoinedRoom : BaseRoom { + /** + * A counter incremented every time a synced event is received on [liveTimeline], so callers can refresh data derived from the room. + * It carries no meaning beyond "something changed", and is only updated while it has subscribers. + */ val syncUpdateFlow: StateFlow + /** The members currently typing in the room, never including the current user; starts as an empty list. */ val roomTypingMembersFlow: Flow> + + /** Emits when the verification state of other members' identities changes, for instance after a member resets their identity. */ val identityStateChangesFlow: Flow> + + /** + * The notification settings that apply to this room. + * Starts as [RoomNotificationSettingsState.Unknown]: [updateRoomNotificationSettings] must be called to populate it. + */ val roomNotificationSettingsStateFlow: StateFlow /** @@ -45,6 +62,7 @@ interface JoinedRoom : BaseRoom { */ val liveTimeline: Timeline + /** Gives access to the paginated list of threads started in this room. */ val threadsListService: ThreadsListService /** @@ -55,6 +73,14 @@ interface JoinedRoom : BaseRoom { createTimelineParams: CreateTimelineParams, ): Result + /** + * Replaces the content of an event previously sent by the current user, by sending an edit of it. + * + * @param eventId the event to edit. + * @param body the new content, as plain text. + * @param htmlBody the new content as HTML, or `null` when the message has no formatted version. + * @param intentionalMentions the users and rooms this new content deliberately mentions. + */ suspend fun editMessage(eventId: EventId, body: String, htmlBody: String?, intentionalMentions: List): Result /** @@ -63,12 +89,28 @@ interface JoinedRoom : BaseRoom { */ suspend fun typingNotice(isTyping: Boolean): Result + /** + * Invites a user to this room. + * + * @param id the user to invite. + */ suspend fun inviteUserById(id: UserId): Result + /** + * Uploads [data] as the new avatar of the room, not of the current user. + * + * @param mimeType the MIME type of the image, for instance `image/jpeg`. + * @param data the raw bytes of the image. + */ suspend fun updateAvatar(mimeType: String, data: ByteArray): Result + /** Removes the avatar of the room. */ suspend fun removeAvatar(): Result + /** + * Refreshes [roomNotificationSettingsStateFlow], which moves to a pending state and then to a ready or error state. + * The failure is reported through that flow as well as through the returned [Result]. + */ suspend fun updateRoomNotificationSettings(): Result /** @@ -83,11 +125,15 @@ interface JoinedRoom : BaseRoom { /** * Update the room's visibility in the room directory. + * + * @param roomVisibility whether the room should be listed publicly in the directory. */ suspend fun updateRoomVisibility(roomVisibility: RoomVisibility): Result /** - * Update room history visibility for this room. + * Update room history visibility for this room, i.e. how much of the past a new member is allowed to read. + * + * @param historyVisibility the new history visibility to apply. */ suspend fun updateHistoryVisibility(historyVisibility: RoomHistoryVisibility): Result @@ -98,6 +144,8 @@ interface JoinedRoom : BaseRoom { * - `true` if the room alias didn't exist and it's now published. * - `false` if the room alias was already present so it couldn't be * published. + * + * @param roomAlias the alias to publish. */ suspend fun publishRoomAliasInRoomDirectory(roomAlias: RoomAlias): Result @@ -108,6 +156,8 @@ interface JoinedRoom : BaseRoom { * - `true` if the room alias was present and it's now removed from the * room directory. * - `false` if the room alias didn't exist so it couldn't be removed. + * + * @param roomAlias the alias to remove. */ suspend fun removeRoomAliasFromRoomDirectory(roomAlias: RoomAlias): Result @@ -117,26 +167,74 @@ interface JoinedRoom : BaseRoom { suspend fun enableEncryption(): Result /** - * Update the join rule for this room. + * Update the join rule for this room, i.e. who is allowed to join it. + * + * @param joinRule the new join rule to apply. */ suspend fun updateJoinRule(joinRule: JoinRule): Result + /** + * Changes the power level of individual members, which is how roles such as moderator or administrator are granted. + * + * @param changes the new power level to apply to each user. + */ suspend fun updateUsersRoles(changes: List): Result + /** + * Changes the power level required for each action in the room, such as inviting, kicking or changing the room name. + * + * @param roomPowerLevelsValues the new threshold for every action. + */ suspend fun updatePowerLevels(roomPowerLevelsValues: RoomPowerLevelsValues): Result + /** Restores the power levels required for each action to the defaults the room was created with. */ suspend fun resetPowerLevels(): Result + /** + * Changes the name of the room. + * + * @param name the new room name. + */ suspend fun setName(name: String): Result + /** + * Changes the topic of the room. + * + * @param topic the new room topic. + */ suspend fun setTopic(topic: String): Result + /** + * Reports an event to the homeserver moderators, optionally ignoring its sender at the same time. + * + * @param eventId the event being reported. + * @param reason the explanation sent to the moderators. + * @param blockUserId the sender to also add to the ignore list, or `null` to only report the event. + */ suspend fun reportContent(eventId: EventId, reason: String, blockUserId: UserId?): Result + /** + * Removes a member from the room; they are able to join again unless they are also banned. + * + * @param userId the member to remove. + * @param reason the reason recorded in the membership event, or `null` for none. + */ suspend fun kickUser(userId: UserId, reason: String? = null): Result + /** + * Bans a user from the room, removing them if they are a member and preventing them from joining again. + * + * @param userId the user to ban. + * @param reason the reason recorded in the membership event, or `null` for none. + */ suspend fun banUser(userId: UserId, reason: String? = null): Result + /** + * Lifts the ban on a user, allowing them to join the room again; it does not invite them back. + * + * @param userId the user to unban. + * @param reason the reason recorded in the membership event, or `null` for none. + */ suspend fun unbanUser(userId: UserId, reason: String? = null): Result /** @@ -161,6 +259,12 @@ interface JoinedRoom : BaseRoom { */ fun getWidgetDriver(widgetSettings: MatrixWidgetSettings): Result + /** + * Enables or disables the send queue of this room only; see [io.element.android.libraries.matrix.api.MatrixClient.setAllSendQueuesEnabled] + * for the session-wide equivalent and for why a queue disables itself. + * + * @param enabled whether the send queue of this room should be enabled. + */ suspend fun setSendQueueEnabled(enabled: Boolean) /** diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/NotJoinedRoom.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/NotJoinedRoom.kt index fd5e71ff9d..a47179cae7 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/NotJoinedRoom.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/NotJoinedRoom.kt @@ -12,7 +12,13 @@ import io.element.android.libraries.matrix.api.room.preview.RoomPreviewInfo /** A reference to a room either invited, knocked or banned. */ interface NotJoinedRoom : AutoCloseable { + /** What is publicly known about the room: name, topic, avatar, join rule and member count. */ val previewInfo: RoomPreviewInfo + + /** + * The local room, available when the user has a membership in it, for instance after being invited. + * It is `null` for a room only discovered through a preview, and closing this instance also closes it. + */ val localRoom: BaseRoom? /** diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/RoomMember.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/RoomMember.kt index 1874986d70..9155d47a08 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/RoomMember.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/RoomMember.kt @@ -104,4 +104,5 @@ fun RoomMember.toMatrixUser() = MatrixUser( userId = userId, displayName = displayName.takeUnless { membership == RoomMembershipState.BAN }, avatarUrl = avatarUrl.takeUnless { membership == RoomMembershipState.BAN }, + displayedStatus = displayedStatus, ) diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/alias/RoomAliasHelper.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/alias/RoomAliasHelper.kt index c23252961f..aecd2ab7f4 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/alias/RoomAliasHelper.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/alias/RoomAliasHelper.kt @@ -10,7 +10,21 @@ package io.element.android.libraries.matrix.api.room.alias import io.element.android.libraries.matrix.api.core.RoomAlias +/** + * Helpers to build and validate room aliases, delegating to the SDK so that the app and the server agree on what is acceptable. + */ interface RoomAliasHelper { + /** + * Turns a room display name into a usable alias local part, dropping the characters that are not allowed in an alias. + * + * @param name the room display name to derive the alias from. + */ fun roomAliasNameFromRoomDisplayName(name: String): String + + /** + * Whether the given alias is well-formed; this is a format check only and says nothing about the alias being taken. + * + * @param roomAlias the alias to validate. + */ fun isRoomAliasValid(roomAlias: RoomAlias): Boolean } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/join/JoinRoom.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/join/JoinRoom.kt index 4220b68f0d..a6b1f3d36b 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/join/JoinRoom.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/join/JoinRoom.kt @@ -11,7 +11,18 @@ package io.element.android.libraries.matrix.api.room.join import im.vector.app.features.analytics.plan.JoinedRoom import io.element.android.libraries.matrix.api.core.RoomIdOrAlias +/** + * Joins a room and reports the join to analytics, so that callers do not have to do both. + */ interface JoinRoom { + /** + * Joins the room, picking the right SDK call depending on whether an id or an alias was given, and captures an analytics event on success. + * A `Forbidden` answer from the server is translated into [Failures.UnauthorizedJoin] so callers can tell it apart from other errors. + * + * @param roomIdOrAlias the id or the alias of the room to join. + * @param serverNames servers to ask about the room, ignored when joining by alias. + * @param trigger what made the user join, recorded in the analytics event. + */ suspend operator fun invoke( roomIdOrAlias: RoomIdOrAlias, serverNames: List, diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/knock/KnockRequest.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/knock/KnockRequest.kt index 317157793e..386be0d5c9 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/knock/KnockRequest.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/knock/KnockRequest.kt @@ -11,20 +11,50 @@ package io.element.android.libraries.matrix.api.room.knock import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.UserId +/** + * A pending request from a user to join a room whose join rule is knock, along with the actions a moderator can take on it. + * + * Instances are snapshots handed out by [io.element.android.libraries.matrix.api.room.JoinedRoom.knockRequestsFlow]. + */ interface KnockRequest { + /** The id of the membership event carrying the request. */ val eventId: EventId + + /** The user asking to join. */ val userId: UserId + + /** The display name of the user asking to join, or `null` if they have none. */ val displayName: String? + + /** The avatar of the user asking to join, or `null` if they have none. */ val avatarUrl: String? + + /** The message the user attached to their request, or `null` if they sent none. */ val reason: String? + + /** When the request was made, in milliseconds since the epoch, or `null` if the server did not provide it. */ val timestamp: Long? + + /** Whether a moderator has already marked this request as seen, so that it is no longer highlighted as new. */ val isSeen: Boolean + /** Accepts the request, which makes the user a member of the room. */ suspend fun accept(): Result + /** + * Declines the request; the user is free to knock again. + * + * @param reason the explanation recorded in the membership event, or `null` for none. + */ suspend fun decline(reason: String?): Result + /** + * Declines the request and bans the user, so that they cannot knock again. + * + * @param reason the explanation recorded in the membership event, or `null` for none. + */ suspend fun declineAndBan(reason: String?): Result + /** Marks the request as seen, without accepting or declining it. */ suspend fun markAsSeen(): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/powerlevels/RoomPermissions.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/powerlevels/RoomPermissions.kt index a12f7d9606..19c01b9975 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/powerlevels/RoomPermissions.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/powerlevels/RoomPermissions.kt @@ -59,12 +59,16 @@ interface RoomPermissions : AutoCloseable { /** * Returns true if the current user is able to send a specific message type * in the room. + * + * @param message the kind of message the caller wants to send. */ fun canOwnUserSendMessage(message: MessageEventType): Boolean /** * Returns true if the current user is able to send a specific state event * type in the room. + * + * @param stateEvent the kind of state event the caller wants to send. */ fun canOwnUserSendState(stateEvent: StateEventType): Boolean @@ -77,48 +81,66 @@ interface RoomPermissions : AutoCloseable { /** * Returns true if the user with the given userId is able to ban in the * room. + * + * @param userId the member whose ability is checked. */ fun canUserBan(userId: UserId): Boolean /** * Returns true if the user with the given userId is able to invite in the * room. + * + * @param userId the member whose ability is checked. */ fun canUserInvite(userId: UserId): Boolean /** * Returns true if the user with the given userId is able to kick in the * room. + * + * @param userId the member whose ability is checked. */ fun canUserKick(userId: UserId): Boolean /** * Returns true if the user with the given userId is able to pin or unpin * events in the room. + * + * @param userId the member whose ability is checked. */ fun canUserPinUnpin(userId: UserId): Boolean /** * Returns true if the user with the given userId is able to redact * messages of other users in the room. + * + * @param userId the member whose ability is checked. */ fun canUserRedactOther(userId: UserId): Boolean /** * Returns true if the user with the given userId is able to redact * their own messages in the room. + * + * @param userId the member whose ability is checked. */ fun canUserRedactOwn(userId: UserId): Boolean /** * Returns true if the user with the given userId is able to send a * specific message type in the room. + * + * @param userId the member whose ability is checked. + * @param message the kind of message to check. */ fun canUserSendMessage(userId: UserId, message: MessageEventType): Boolean /** * Returns true if the user with the given userId is able to send a * specific state event type in the room. + * + * @param userId the member whose ability is checked. + * @param stateEvent the kind of state event to check. */ fun canUserSendState(userId: UserId, stateEvent: StateEventType): Boolean @@ -127,6 +149,8 @@ interface RoomPermissions : AutoCloseable { * notification in the room. * * The call may fail if there is an error in getting the power levels. + * + * @param userId the member whose ability is checked. */ fun canUserTriggerRoomNotification(userId: UserId): Boolean } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/threads/ThreadsListService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/threads/ThreadsListService.kt index 7f819c540c..f544211741 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/threads/ThreadsListService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/room/threads/ThreadsListService.kt @@ -9,10 +9,27 @@ package io.element.android.libraries.matrix.api.room.threads import kotlinx.coroutines.flow.Flow +/** + * Exposes the paginated list of threads of a single room, kept up to date by the SDK. + * + * The list grows through explicit [paginate] calls; [destroy] must be called to release the underlying SDK resources. + */ interface ThreadsListService { + /** + * The threads loaded so far, starting empty and re-emitted in full whenever the SDK sends an update. + * The underlying subscription is started on the first call and shared by later ones. + */ fun subscribeToItemUpdates(): Flow> + + /** The pagination state of the list, emitting the current value immediately so callers know whether more threads can be loaded. */ fun subscribeToPaginationUpdates(): Flow + + /** Loads the next page of threads, which will be reflected in [subscribeToItemUpdates]. */ suspend fun paginate(): Result + + /** Discards the loaded threads and starts the list again from the most recent one. */ suspend fun reset(): Result + + /** Releases the SDK resources and stops the item subscription; the service is unusable afterwards. */ fun destroy() } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryList.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryList.kt index c48bf54e9c..49de1bee89 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryList.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryList.kt @@ -10,12 +10,21 @@ package io.element.android.libraries.matrix.api.roomdirectory import kotlinx.coroutines.flow.Flow +/** + * A single, stateful search in the public room directory: one query at a time, with paginated results. + * + * Obtain an instance from [RoomDirectoryService.createRoomDirectoryList]. + */ interface RoomDirectoryList { /** * Starts a filtered search for the server. * If the filter is not provided it will search for all the rooms. You can specify a batch_size to control the number of rooms to fetch per request. * If the via_server is not provided it will search in the current homeserver by default. * This method will clear the current search results and start a new one + * + * @param filter the text to look for, or `null` to list every room. + * @param batchSize the number of rooms to fetch per request. + * @param viaServerName the server whose directory to search, or `null` to use the user's own homeserver. */ suspend fun filter(filter: String?, batchSize: Int, viaServerName: String?): Result diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryService.kt index 8f71cfb18c..65f83299cb 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomdirectory/RoomDirectoryService.kt @@ -10,6 +10,14 @@ package io.element.android.libraries.matrix.api.roomdirectory import kotlinx.coroutines.CoroutineScope +/** + * Gives access to the public room directory, i.e. the rooms a server advertises to users who have not joined them. + */ interface RoomDirectoryService { + /** + * Creates an independent directory search, which is stateful and holds one query at a time. + * + * @param scope the lifetime of the search; the underlying SDK resources are released when it completes, so there is nothing to close by hand. + */ fun createRoomDirectoryList(scope: CoroutineScope): RoomDirectoryList } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomlist/DynamicRoomList.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomlist/DynamicRoomList.kt index 952cee6f22..eee98b82e9 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomlist/DynamicRoomList.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/roomlist/DynamicRoomList.kt @@ -14,6 +14,7 @@ package io.element.android.libraries.matrix.api.roomlist * It lets load rooms on demand and filter them. */ interface DynamicRoomList : RoomList { + /** The number of rooms added to the list by each [loadMore] call, as chosen when the list was created. */ val pageSize: Int /** diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/scanner/ContentScannerUrlProvider.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/scanner/ContentScannerUrlProvider.kt deleted file mode 100644 index 600866f586..0000000000 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/scanner/ContentScannerUrlProvider.kt +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2026 Element Creations Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.libraries.matrix.api.scanner - -/** - * Provides the URL of the content scanner service for a given homeserver, if any is set up. - */ -fun interface ContentScannerUrlProvider { - /** - * Returns the URL of the content scanner service for the given [homeserver], or `null` if no content scanner is set up. - */ - suspend fun getContentScannerUrl(homeserver: String): Result -} diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/search/MessageSearchService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/search/MessageSearchService.kt index 3e20b163f2..d7d8c017e3 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/search/MessageSearchService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/search/MessageSearchService.kt @@ -10,6 +10,11 @@ package io.element.android.libraries.matrix.api.search import io.element.android.libraries.matrix.api.core.RoomId import kotlinx.coroutines.CoroutineScope +/** + * Creates the message search cursors backed by the local search index. + * + * Only usable when the session was built with the index attached, see [io.element.android.libraries.matrix.api.MatrixClient.isMessageSearchAvailable]. + */ interface MessageSearchService { /** * Create a new, independent search cursor. diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/server/UserServerResolver.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/server/UserServerResolver.kt index 3529b17d85..6c3c16b35e 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/server/UserServerResolver.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/server/UserServerResolver.kt @@ -8,6 +8,10 @@ package io.element.android.libraries.matrix.api.server +/** + * Resolves the server name of the logged in user, which is the part of their user id after the colon. + */ interface UserServerResolver { + /** Returns the server name, for instance `matrix.org` for `@alice:matrix.org`. */ fun resolve(): String } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/LeaveSpaceHandle.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/LeaveSpaceHandle.kt index 174ec20dc9..59b9657b58 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/LeaveSpaceHandle.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/LeaveSpaceHandle.kt @@ -10,6 +10,11 @@ package io.element.android.libraries.matrix.api.spaces import io.element.android.libraries.matrix.api.core.RoomId +/** + * Handles leaving a space, letting the user also choose which of its rooms to leave in the same operation. + * + * Obtain an instance from [SpaceService.getLeaveSpaceHandle]; the caller owns it and must [close] it. + */ interface LeaveSpaceHandle { /** * The id of the space to leave. diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceRoomList.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceRoomList.kt index 2ccee8d1ee..b29d721d07 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceRoomList.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceRoomList.kt @@ -16,22 +16,36 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import java.util.Optional +/** + * The paginated list of the children of a single space, kept up to date by the SDK. + * + * Obtain an instance from [SpaceService.spaceRoomList]; the caller owns it and must call [destroy] when done. + */ interface SpaceRoomList { sealed interface PaginationStatus { data object Loading : PaginationStatus data class Idle(val hasMoreToLoad: Boolean) : PaginationStatus } + /** The space whose children this list holds. */ val spaceId: RoomId + /** What is known about the space itself, starting empty until the SDK provides it. */ val currentSpaceFlow: StateFlow> + /** The children loaded so far, re-emitted in full on every update; the latest value is replayed to new collectors. */ val spaceRoomsFlow: Flow> + + /** Whether a page is being loaded and whether more children remain; see [loadAllIncrementally] to drain the list. */ val paginationStatusFlow: StateFlow + /** Loads the next page of children, which will be reflected in [spaceRoomsFlow]. */ suspend fun paginate(): Result + + /** Discards the loaded children and starts the list again from the beginning. */ suspend fun reset(): Result + /** Releases the SDK resources and cancels the internal scope; the list is unusable afterwards. */ fun destroy() } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceService.kt index 299209e188..a7126a4766 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/spaces/SpaceService.kt @@ -11,13 +11,35 @@ package io.element.android.libraries.matrix.api.spaces import io.element.android.libraries.matrix.api.core.RoomId import kotlinx.coroutines.flow.SharedFlow +/** + * Gives access to the spaces the user belongs to, their hierarchy, and the operations that change it. + */ interface SpaceService { + /** The spaces that have no joined parent, i.e. the roots of the hierarchy shown to the user; the latest value is replayed to new collectors. */ val topLevelSpacesFlow: SharedFlow> + + /** The filters the space list can be narrowed down with; as with [topLevelSpacesFlow], the latest value is replayed. */ val spaceFiltersFlow: SharedFlow> + + /** + * Returns the spaces the given room or space is a child of, restricted to the ones the user has joined. + * + * @param spaceId the room or space whose parents are requested. + */ suspend fun joinedParents(spaceId: RoomId): Result> + /** + * Returns what is known about a single space, or `null` if it is unknown or the lookup failed. + * + * @param spaceId the space to look up. + */ suspend fun getSpaceRoom(spaceId: RoomId): SpaceRoom? + /** + * Creates a paginated list of the children of a space; the caller owns it and must call `destroy` on it. + * + * @param id the space whose children are listed. + */ fun spaceRoomList(id: RoomId): SpaceRoomList /** @@ -25,6 +47,11 @@ interface SpaceService { */ suspend fun editableSpaces(): Result> + /** + * Creates a handle to leave a space, which lets the user also pick which of its rooms to leave; the caller must close it. + * + * @param spaceId the space the user wants to leave. + */ fun getLeaveSpaceHandle(spaceId: RoomId): LeaveSpaceHandle /** diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/sync/SyncService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/sync/SyncService.kt index ce0019d8dc..92f60352d7 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/sync/SyncService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/sync/SyncService.kt @@ -10,21 +10,31 @@ package io.element.android.libraries.matrix.api.sync import kotlinx.coroutines.flow.StateFlow +/** + * Drives the sync loop of a single session and exposes its current state. + * + * Both [startSync] and [stopSync] are idempotent and never throw: any error is wrapped in the returned [Result]. + */ interface SyncService { /** - * Tries to start the sync. If already syncing it has no effect. + * Tries to start the sync. If already syncing, or if the service has been destroyed, it has no effect. */ suspend fun startSync(): Result /** - * Tries to stop the sync. If service is not syncing it has no effect. + * Tries to stop the sync. If the service is not syncing, or has been destroyed, it has no effect. */ suspend fun stopSync(): Result /** * Flow of [SyncState]. Will be updated as soon as the current [SyncState] changes. + * Starts at [SyncState.Idle] and only emits on an actual change, for as long as the session lives. */ val syncState: StateFlow + /** + * Whether the client currently considers itself online, derived from [syncState]. + * This is `false` only while the state is [SyncState.Offline]; an idle or errored sync still counts as online. + */ val isOnline: StateFlow } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/Timeline.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/Timeline.kt index 8cb933205b..72483e68f1 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/Timeline.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/Timeline.kt @@ -31,6 +31,12 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.parcelize.Parcelize import java.io.File +/** + * A window over the events of a room, restricted by its [Mode], and the entry point for sending events to that room. + * + * A timeline owns SDK resources and must be closed once no longer needed, except the live timeline, which is owned by its room. + * Sending returns successfully as soon as the event has been handed to the room's send queue, not when the server has accepted it. + */ interface Timeline : AutoCloseable { data class PaginationStatus( val isPaginating: Boolean, @@ -54,18 +60,66 @@ interface Timeline : AutoCloseable { data class Thread(val threadRootId: ThreadId) : Mode } + /** What this timeline is a view over: the live room, a single event and its context, the pinned events, the media, or a thread. */ val mode: Mode + + /** + * Emits every time a membership change event is received in this timeline, without saying which one. + * Collecting it keeps the timeline subscribed to the SDK, so it should not be collected for longer than needed. + */ val membershipChangeEventReceived: Flow + + /** + * Emits every time an event coming from sync is received in this timeline, without saying which one. + * As with [membershipChangeEventReceived], collecting it keeps the timeline subscribed to the SDK. + */ val onSyncedEventReceived: Flow + + /** + * Sends a read receipt for a single event, which is how the unread state of the room is cleared. + * + * @param eventId the event the receipt points at. + * @param receiptType whether the receipt is public, private or only marks the fully read position. + */ suspend fun sendReadReceipt(eventId: EventId, receiptType: ReceiptType): Result + + /** + * Marks the whole timeline as read by sending a receipt on its latest event. + * + * @param receiptType whether the receipt is public, private or only marks the fully read position. + */ suspend fun markAsRead(receiptType: ReceiptType): Result + + /** + * Loads one more page of events and updates the matching pagination status flow. + * Fails with a `CannotPaginate` error when the corresponding status does not allow it, for instance because a pagination is already running. + * + * @param direction whether to load older or newer events. + * @return whether the end of the timeline has been reached in that direction. + */ suspend fun paginate(direction: PaginationDirection): Result + /** Whether older events are being loaded and whether more remain; pinned event timelines start with nothing more to load. */ val backwardPaginationStatus: StateFlow + + /** Whether newer events are being loaded and whether more remain; only a timeline focused on an event starts with more to load. */ val forwardPaginationStatus: StateFlow + /** + * The items to display, in timeline order, re-emitted on every change. + * Beyond the room events this also carries the virtual items the UI needs, such as date separators, loading indicators and the room beginning. + */ val timelineItems: Flow> + /** + * Sends a text message to the room this timeline belongs to. + * + * @param body the message content, as plain text. + * @param htmlBody the message content as HTML, or `null` to send it unformatted. + * @param intentionalMentions the users and rooms the message deliberately mentions, so that they are notified. + * @param msgType the Matrix message type to use, which distinguishes a normal message from an emote or a notice. + * @param asPlainText whether to send the message without any formatting, ignoring markdown in [body]. + */ suspend fun sendMessage( body: String, htmlBody: String?, @@ -74,6 +128,14 @@ interface Timeline : AutoCloseable { asPlainText: Boolean = false, ): Result + /** + * Replaces the content of a message, whether it has already been sent or is still local in the send queue. + * + * @param eventOrTransactionId the event to edit, identified by its event id once sent or by its transaction id while still local. + * @param body the new content, as plain text. + * @param htmlBody the new content as HTML, or `null` to send it unformatted. + * @param intentionalMentions the users and rooms the new content deliberately mentions. + */ suspend fun editMessage( eventOrTransactionId: EventOrTransactionId, body: String, @@ -81,12 +143,29 @@ interface Timeline : AutoCloseable { intentionalMentions: List, ): Result + /** + * Replaces the caption of an already sent media message, leaving the media itself untouched. + * + * @param eventOrTransactionId the media event to edit, identified by its event id or by its transaction id while still local. + * @param caption the new caption, or `null` to remove it. + * @param formattedCaption the new caption as HTML, or `null` to send it unformatted. + */ suspend fun editCaption( eventOrTransactionId: EventOrTransactionId, caption: String?, formattedCaption: String?, ): Result + /** + * Sends a message as a reply to another event. + * + * @param repliedToEventId the event being replied to. + * @param body the reply content, as plain text. + * @param htmlBody the reply content as HTML, or `null` to send it unformatted. + * @param intentionalMentions the users and rooms the reply deliberately mentions. + * @param fromNotification whether the reply was written from a notification rather than from the timeline. + * @param msgType the Matrix message type to use. + */ suspend fun replyMessage( repliedToEventId: EventId, body: String, @@ -96,6 +175,16 @@ interface Timeline : AutoCloseable { msgType: MsgType = MsgType.MSG_TYPE_TEXT, ): Result + /** + * Starts sending an image. The returned [MediaUploadHandler] tracks the upload and must be awaited by the caller to know the outcome. + * + * @param file the image to upload. + * @param thumbnailFile a pre-generated thumbnail, or `null` to send none. + * @param imageInfo the dimensions, size and MIME type of the image. + * @param caption the text shown along with the image, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendImage( file: File, thumbnailFile: File?, @@ -105,6 +194,16 @@ interface Timeline : AutoCloseable { inReplyToEventId: EventId?, ): Result + /** + * Starts sending a video, with the same upload contract as [sendImage]. + * + * @param file the video to upload. + * @param thumbnailFile a pre-generated thumbnail, or `null` to send none. + * @param videoInfo the duration, dimensions, size and MIME type of the video. + * @param caption the text shown along with the video, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendVideo( file: File, thumbnailFile: File?, @@ -114,6 +213,15 @@ interface Timeline : AutoCloseable { inReplyToEventId: EventId?, ): Result + /** + * Starts sending an audio file, with the same upload contract as [sendImage]; use [sendVoiceMessage] for a recorded voice message. + * + * @param file the audio file to upload. + * @param audioInfo the duration, size and MIME type of the audio. + * @param caption the text shown along with the audio, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendAudio( file: File, audioInfo: AudioInfo, @@ -122,6 +230,15 @@ interface Timeline : AutoCloseable { inReplyToEventId: EventId?, ): Result + /** + * Starts sending an arbitrary file, with the same upload contract as [sendImage]. + * + * @param file the file to upload. + * @param fileInfo the size and MIME type of the file. + * @param caption the text shown along with the file, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendFile( file: File, fileInfo: FileInfo, @@ -151,6 +268,14 @@ interface Timeline : AutoCloseable { inReplyToEventId: EventId?, ): Result + /** + * Starts sending a recorded voice message, with the same upload contract as [sendImage]. + * + * @param file the recorded audio to upload. + * @param audioInfo the duration, size and MIME type of the recording. + * @param waveform the amplitudes used to draw the waveform, normalised between 0 and 1. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendVoiceMessage( file: File, audioInfo: AudioInfo, @@ -158,6 +283,14 @@ interface Timeline : AutoCloseable { inReplyToEventId: EventId?, ): Result + /** + * Starts sending several media items as a single gallery message, with the same upload contract as [sendImage]. + * + * @param items the media making up the gallery, in the order they should appear. + * @param caption the text shown along with the gallery, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendGallery( items: List, caption: String?, @@ -165,12 +298,36 @@ interface Timeline : AutoCloseable { inReplyToEventId: EventId?, ): Result + /** + * Redacts an event, i.e. asks the server to remove its content; it also removes a local echo that has not been sent yet. + * + * @param eventOrTransactionId the event to redact, identified by its event id once sent or by its transaction id while still local. + * @param reason the explanation recorded in the redaction event, or `null` for none. + */ suspend fun redactEvent(eventOrTransactionId: EventOrTransactionId, reason: String?): Result + /** + * Adds the given reaction to an event, or removes it if the current user had already reacted with it. + * + * @param emoji the reaction key, usually an emoji. + * @param eventOrTransactionId the event to react to, identified by its event id or by its transaction id while still local. + * @return whether the reaction is now present. + */ suspend fun toggleReaction(emoji: String, eventOrTransactionId: EventOrTransactionId): Result + /** + * Forwards the content of an event to other rooms, as new messages sent by the current user. + * + * @param eventId the event whose content is forwarded. + * @param roomIds the rooms to forward it to. + */ suspend fun forwardEvent(eventId: EventId, roomIds: List): Result + /** + * Cancels an event that is still waiting in the send queue, by redacting its local echo. + * + * @param transactionId the transaction id of the local echo to drop. + */ suspend fun cancelSend(transactionId: TransactionId): Result = redactEvent(transactionId.toEventOrTransactionId(), reason = null) @@ -222,12 +379,20 @@ interface Timeline : AutoCloseable { */ suspend fun endPoll(pollStartId: EventId, text: String): Result + /** + * Resolves the content of a replied-to event so it can be rendered above the reply. + * Served from the loaded timeline items when possible, otherwise fetched through the SDK. + * + * @param eventId the event being replied to. + */ suspend fun loadReplyDetails(eventId: EventId): InReplyTo /** * Returns true if [eventId] is currently loaded in this timeline's window, even if the display * layer does not render it (e.g. filtered or state events). This distinguishes "in the window * but not displayed" from "genuinely outside the loaded window". + * + * @param eventId the event to look for. */ suspend fun isEventLoaded(eventId: EventId): Boolean @@ -237,6 +402,8 @@ interface Timeline : AutoCloseable { * * Returns `true` if we sent the request, `false` if the event was already * pinned. + * + * @param eventId the event to pin. */ suspend fun pinEvent(eventId: EventId): Result @@ -246,11 +413,13 @@ interface Timeline : AutoCloseable { * * Returns `true` if we sent the request, `false` if the event wasn't * pinned + * + * @param eventId the event to unpin. */ suspend fun unpinEvent(eventId: EventId): Result /** - * Get the latest event id of the timeline. + * Get the latest event id of the timeline, or `null` when it holds no event yet. */ suspend fun getLatestEventId(): Result } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/TimelineProvider.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/TimelineProvider.kt index 28e487f527..ef9d5d794e 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/TimelineProvider.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/TimelineProvider.kt @@ -18,6 +18,7 @@ import kotlinx.coroutines.flow.first * By default, the active timeline is the live timeline. */ fun interface TimelineProvider { + /** The timeline currently in use, or `null` while none is available yet; see [getActiveTimeline] to await a non-null value. */ fun activeTimelineFlow(): StateFlow } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/EventTimelineItem.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/EventTimelineItem.kt index f3982e83d2..91703f7fa4 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/EventTimelineItem.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/EventTimelineItem.kt @@ -60,14 +60,30 @@ data class EventTimelineItem( } } +/** + * Provides the debug information of a timeline item on demand, so the original event JSON is only fetched from the SDK when actually displayed. + */ fun interface TimelineItemDebugInfoProvider { + /** Returns the debug information of the item, including its original and latest edit JSON. */ operator fun invoke(): TimelineItemDebugInfo } +/** + * Provides the encryption warning to show next to a timeline item on demand, so the check is only run for items that are displayed. + */ fun interface MessageShieldProvider { + /** + * Returns the warning to display for this event, or `null` when there is nothing to warn about. + * + * @param strict whether to also report the weaker problems that are hidden by default. + */ operator fun invoke(strict: Boolean): MessageShield? } +/** + * Provides the send queue handle of a timeline item on demand, which is needed to retry or cancel a failed send. + */ fun interface SendHandleProvider { + /** Returns the send handle of the item, or `null` when it is not a local echo waiting in the send queue. */ operator fun invoke(): SendHandle? } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/MessageType.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/MessageType.kt index 2f61b8f58a..f2bd56ac57 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/MessageType.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/MessageType.kt @@ -128,4 +128,11 @@ sealed interface GalleryItemType { data class OtherMessageType( val msgType: String, val body: String, -) : MessageType +) : MessageType { + /** + * A `m.key.verification.request` carries a body meant for clients that cannot handle in-chat + * verification, so it must not be rendered as a message. + */ + val isKeyVerificationRequest: Boolean + get() = msgType == "m.key.verification.request" +} diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/ProfileDetails.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/ProfileDetails.kt index 73b0478d63..1a56e888fa 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/ProfileDetails.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/timeline/item/event/ProfileDetails.kt @@ -11,6 +11,7 @@ package io.element.android.libraries.matrix.api.timeline.item.event import androidx.compose.runtime.Immutable import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.user.DisplayedStatus +import io.element.android.libraries.matrix.api.user.MatrixUser @Immutable sealed interface ProfileDetails { @@ -60,3 +61,20 @@ fun ProfileDetails.getAvatarUrl(): String? { else -> null } } + +fun ProfileDetails.toMatrixUser(userId: UserId): MatrixUser { + return when (this) { + is ProfileDetails.Ready -> MatrixUser( + userId = userId, + displayName = displayName, + avatarUrl = avatarUrl, + displayedStatus = displayedStatus, + ) + else -> MatrixUser( + userId = userId, + displayName = null, + avatarUrl = null, + displayedStatus = null, + ) + } +} diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/tracing/TracingService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/tracing/TracingService.kt index d4ef27fd0d..f5de427ce0 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/tracing/TracingService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/tracing/TracingService.kt @@ -10,8 +10,21 @@ package io.element.android.libraries.matrix.api.tracing import timber.log.Timber +/** + * Routes the app's own logs into the SDK's tracing subsystem, so that Kotlin and Rust logs end up interleaved in the same files. + */ interface TracingService { + /** + * Creates a Timber tree that forwards what the app logs to the SDK tracing subsystem. + * + * @param target the tracing target name the logs are attributed to, used to tell subsystems apart in the output. + */ fun createTimberTree(target: String): Timber.Tree + /** + * Turns writing logs to files on or off at runtime, which is how the user-facing logging toggle is applied. + * + * @param config where to write the log files, or the disabled configuration to stop writing them. + */ fun updateWriteToFilesConfiguration(config: WriteToFilesConfiguration) } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/user/DisplayedStatus.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/user/DisplayedStatus.kt index 581658ff28..8e4ced7202 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/user/DisplayedStatus.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/user/DisplayedStatus.kt @@ -13,6 +13,9 @@ import kotlinx.parcelize.Parcelize @Immutable sealed interface DisplayedStatus : Parcelable { + /** Useful for adding extension methods. */ + companion object + /** Status set manually by the user via m.status. */ @Parcelize data class UserSet(val status: UserStatus) : DisplayedStatus @@ -21,6 +24,6 @@ sealed interface DisplayedStatus : Parcelable { @Parcelize data class InCall( /** Unix timestamp in seconds when the call was joined (from m.call.call_joined_ts). */ - val callJoinedTs: Long, + val callJoinedTs: Long?, ) : DisplayedStatus } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/verification/SessionVerificationService.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/verification/SessionVerificationService.kt index 38a00d833d..de9b11e882 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/verification/SessionVerificationService.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/verification/SessionVerificationService.kt @@ -13,6 +13,12 @@ import io.element.android.libraries.matrix.api.core.UserId import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow +/** + * Drives session verification: proving to the account that this device is trusted, and verifying other users. + * + * A verification is a stateful exchange between two devices, so at most one flow is active at a time and its progress is reported + * through [verificationFlowState] rather than through the return value of each call. + */ interface SessionVerificationService { /** * State of the current verification flow ([VerificationFlowState.Initial] if not started). @@ -37,6 +43,8 @@ interface SessionVerificationService { /** * Request verification of the user with the given [userId]. + * + * @param userId the other user to verify. */ suspend fun requestUserVerification(userId: UserId) @@ -62,17 +70,23 @@ interface SessionVerificationService { /** * Returns the verification service state to the initial step. + * + * @param cancelAnyPendingVerificationAttempt whether to also cancel a verification that is still in progress. */ suspend fun reset(cancelAnyPendingVerificationAttempt: Boolean) /** * Register a listener to be notified of incoming session verification requests. + * + * @param listener the listener to notify, or `null` to stop being notified. */ fun setListener(listener: SessionVerificationServiceListener?) /** * Set this particular request as the currently active one and register for * events pertaining it. + * + * @param verificationRequest the incoming request to make active. */ suspend fun acknowledgeVerificationRequest(verificationRequest: VerificationRequest.Incoming) @@ -82,7 +96,15 @@ interface SessionVerificationService { suspend fun acceptVerificationRequest() } +/** + * Notified when another device asks to verify this session; register one through [SessionVerificationService.setListener]. + */ interface SessionVerificationServiceListener { + /** + * Called when a verification request is received, so the app can prompt the user about it. + * + * @param verificationRequest the incoming request, to be passed to [SessionVerificationService.acknowledgeVerificationRequest] to act on it. + */ fun onIncomingSessionRequest(verificationRequest: VerificationRequest.Incoming) } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallAnalyticCredentialsProvider.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallAnalyticCredentialsProvider.kt index 5b2a691afc..1b45c4f1a0 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallAnalyticCredentialsProvider.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallAnalyticCredentialsProvider.kt @@ -8,10 +8,24 @@ package io.element.android.libraries.matrix.api.widget +/** + * Supplies the analytics and crash reporting credentials passed to the embedded Element Call widget. + * + * Every member is `null` when the corresponding service is not configured for this build, or when the user has not consented to analytics. + */ interface CallAnalyticCredentialsProvider { + /** The PostHog identifier of the current user, so call analytics can be tied to the same person as app analytics. */ val posthogUserId: String? + + /** The PostHog host the widget should send its events to. */ val posthogApiHost: String? + + /** The PostHog API key the widget should use. */ val posthogApiKey: String? + + /** The URL the widget should submit its rageshakes to. */ val rageshakeSubmitUrl: String? + + /** The Sentry DSN the widget should report its crashes to. */ val sentryDsn: String? } diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallWidgetSettingsProvider.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallWidgetSettingsProvider.kt index d0686e8e5f..92510c4b8f 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallWidgetSettingsProvider.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/CallWidgetSettingsProvider.kt @@ -10,7 +10,18 @@ package io.element.android.libraries.matrix.api.widget import java.util.UUID +/** + * Builds the widget settings used to embed Element Call in a room, applying the app's own preferences on top of the SDK defaults. + */ interface CallWidgetSettingsProvider { + /** + * @param baseUrl the URL Element Call is served from. + * @param widgetId a unique identifier for this widget instance. + * @param encrypted whether the room the call takes place in is encrypted. + * @param direct whether the call happens in a direct message room. + * @param isAudioCall whether the call should start without video. + * @param hasActiveCall whether a call is already ongoing in the room, which affects whether the user joins straight away. + */ suspend fun provide( baseUrl: String, widgetId: String = UUID.randomUUID().toString(), diff --git a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/MatrixWidgetDriver.kt b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/MatrixWidgetDriver.kt index d8cca95842..3b863279cf 100644 --- a/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/MatrixWidgetDriver.kt +++ b/libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/widget/MatrixWidgetDriver.kt @@ -10,10 +10,25 @@ package io.element.android.libraries.matrix.api.widget import kotlinx.coroutines.flow.Flow +/** + * Bridges a widget running in a WebView with the Matrix room it is embedded in, relaying the widget API messages in both directions. + * + * The driver owns SDK resources and must be closed once the widget goes away; Element Call is the main user of this. + */ interface MatrixWidgetDriver : AutoCloseable { + /** The id of the widget this driver serves, matching the one in its settings. */ val id: String + + /** The messages coming from the room that should be forwarded to the widget. */ val incomingMessages: Flow + /** Starts relaying messages and suspends for as long as the driver runs; calling it again while it is running does nothing. */ suspend fun run() + + /** + * Forwards a message from the widget to the room. Does nothing once the driver has been closed. + * + * @param message the raw widget API message emitted by the WebView. + */ suspend fun send(message: String) } diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClient.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClient.kt index 88b1f05909..a36184d6bd 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClient.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClient.kt @@ -49,7 +49,6 @@ import io.element.android.libraries.matrix.api.scanner.ContentScanner import io.element.android.libraries.matrix.api.spaces.SpaceService import io.element.android.libraries.matrix.api.sync.SlidingSyncVersion import io.element.android.libraries.matrix.api.sync.SyncState -import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.MatrixSearchUserResults import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.api.user.UserStatus @@ -58,7 +57,6 @@ import io.element.android.libraries.matrix.impl.exception.mapClientException import io.element.android.libraries.matrix.impl.linknewdevice.RustLinkDesktopHandler import io.element.android.libraries.matrix.impl.linknewdevice.RustLinkMobileHandler import io.element.android.libraries.matrix.impl.linknewdevice.RustQrCodeDataParser -import io.element.android.libraries.matrix.impl.mapper.map import io.element.android.libraries.matrix.impl.media.RustMediaLoader import io.element.android.libraries.matrix.impl.media.RustMediaPreviewService import io.element.android.libraries.matrix.impl.notification.RustNotificationService @@ -85,7 +83,9 @@ import io.element.android.libraries.matrix.impl.search.RustMessageSearchService import io.element.android.libraries.matrix.impl.spaces.RustSpaceService import io.element.android.libraries.matrix.impl.sync.RustSyncService import io.element.android.libraries.matrix.impl.sync.map -import io.element.android.libraries.matrix.impl.usersearch.UserSearchResultMapper +import io.element.android.libraries.matrix.impl.user.UserSearchResultMapper +import io.element.android.libraries.matrix.impl.user.into +import io.element.android.libraries.matrix.impl.user.map import io.element.android.libraries.matrix.impl.util.cancelAndDestroy import io.element.android.libraries.matrix.impl.util.mxCallbackFlow import io.element.android.libraries.matrix.impl.verification.RustSessionVerificationService @@ -126,13 +126,16 @@ import org.matrix.rustcomponents.sdk.IgnoredUsersListener import org.matrix.rustcomponents.sdk.Membership import org.matrix.rustcomponents.sdk.NotificationProcessSetup import org.matrix.rustcomponents.sdk.PowerLevels +import org.matrix.rustcomponents.sdk.ProfileListener import org.matrix.rustcomponents.sdk.RoomInfoListener import org.matrix.rustcomponents.sdk.SendQueueRoomErrorListener import org.matrix.rustcomponents.sdk.TaskHandle +import org.matrix.rustcomponents.sdk.UserProfile import org.matrix.rustcomponents.sdk.use import timber.log.Timber import java.io.File import java.util.Optional +import java.util.concurrent.atomic.AtomicBoolean import kotlin.jvm.optionals.getOrNull import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds @@ -143,7 +146,7 @@ import org.matrix.rustcomponents.sdk.SyncService as ClientSyncService @Suppress("LargeClass") class RustMatrixClient( override val sessionPaths: SessionPaths, - private val innerClient: Client, + val innerClient: Client, private val sessionStore: SessionStore, private val sessionDelegate: RustClientSessionDelegate, private val innerSyncService: ClientSyncService, @@ -160,6 +163,7 @@ class RustMatrixClient( ) : MatrixClient { override val sessionId: UserId = UserId(innerClient.userId()) override val deviceId: DeviceId = DeviceId(innerClient.deviceId()) + override val server: String? = innerClient.server() override val homeserverUrl: String = innerClient.homeserver() override val sessionCoroutineScope = appCoroutineScope.childScope(dispatchers.main, "Session-$sessionId") private val sessionDispatcher = dispatchers.io.limitedParallelism(64) @@ -271,8 +275,6 @@ class RustMatrixClient( private var clientDelegateTaskHandle: TaskHandle? = innerClient.setDelegate(sessionDelegate) - @Volatile private var localUserStatus: UserStatus? = null - private val _userProfile: MutableStateFlow = MutableStateFlow( MatrixUser( userId = sessionId, @@ -283,6 +285,14 @@ class RustMatrixClient( override val userProfile: StateFlow = _userProfile + private var ownProfileTaskHandle: TaskHandle? = null + + private val ownProfileListener = object : ProfileListener { + override fun onUpdate(profile: UserProfile) { + _userProfile.tryEmit(profile.map()) + } + } + override val ignoredUsersFlow = mxCallbackFlow> { // Fetch the initial value manually, the SDK won't return it automatically channel.trySend(innerClient.ignoredUsers().map(::UserId).toImmutableList()) @@ -296,6 +306,10 @@ class RustMatrixClient( .buffer(Channel.UNLIMITED) .stateIn(sessionCoroutineScope, started = SharingStarted.Eagerly, initialValue = persistentListOf()) + private val _isShuttingDown = AtomicBoolean(false) + override val isShuttingDown: Boolean + get() = _isShuttingDown.get() + init { // Make sure the session delegate has a reference to the client to be able to logout on auth error sessionDelegate.bindClient(this) @@ -303,8 +317,23 @@ class RustMatrixClient( sessionCoroutineScope.launch { // Start notification settings notificationSettingsService.start() + // Setup user profile logic + setupUserProfile() + } - // Update the user profile in the session store if needed + // Schedule regular database vacuuming to ensure DB performance remains optimal + scheduleDatabaseVacuum() + } + + private suspend fun setupUserProfile() { + // Subscribing to own profile updates only requires the Profiles sliding sync extension, + // not the full user status capability (which also needs the status profile field to be settable). + val supported = isProfilesSlidingSyncExtensionSupported().getOrDefault(false) + if (supported) { + // No need to seed the data here, it's already stored by the sdk. + ownProfileTaskHandle = innerClient.subscribeToOwnProfile(ownProfileListener) + } else { + // Seed from the session store so cold-start UI has something to render before the network fetch. sessionStore.getSession(sessionId.value)?.let { sessionData -> _userProfile.emit( MatrixUser( @@ -314,12 +343,8 @@ class RustMatrixClient( ) ) } - // Force a refresh of the profile getUserProfile() } - - // Schedule regular database vacuuming to ensure DB performance remains optimal - scheduleDatabaseVacuum() } override fun userIdServerName(): String { @@ -458,13 +483,8 @@ class RustMatrixClient( override suspend fun getUserProfile(): Result = getProfile(sessionId) .onSuccess { matrixUser -> - _userProfile.emit( - matrixUser.copy( - rawStatus = localUserStatus, - displayedStatus = localUserStatus?.let { DisplayedStatus.UserSet(it) }, - ) - ) // Also update our session storage + _userProfile.emit(matrixUser) sessionStore.updateUserProfile( sessionId = sessionId.value, displayName = matrixUser.displayName, @@ -495,25 +515,37 @@ class RustMatrixClient( } override suspend fun setUserStatus(status: UserStatus): Result = withContext(sessionDispatcher) { - localUserStatus = status - _userProfile.emit( - _userProfile.value.copy( - rawStatus = status, - displayedStatus = DisplayedStatus.UserSet(status), - ) - ) - Result.success(Unit) + runCatchingExceptions { + innerClient.setUserStatus(status.into()) + }.onSuccess { + // The subscription pushes the update on supported servers; only refresh manually as a fallback. + if (ownProfileTaskHandle == null) getUserProfile() + } } override suspend fun clearUserStatus(): Result = withContext(sessionDispatcher) { - localUserStatus = null - _userProfile.emit( - _userProfile.value.copy( - rawStatus = null, - displayedStatus = null, - ) - ) - Result.success(Unit) + runCatchingExceptions { + innerClient.clearUserStatus() + }.onSuccess { + // The subscription pushes the update on supported servers; only refresh manually as a fallback. + if (ownProfileTaskHandle == null) getUserProfile() + } + } + + override suspend fun isUserStatusSupported(): Result = withContext(sessionDispatcher) { + runCatchingExceptions { + innerClient.isUserStatusSupported() + } + } + + override suspend fun isProfilesSlidingSyncExtensionSupported(): Result = withContext(sessionDispatcher) { + runCatchingExceptions { + innerClient.isProfilesSlidingSyncExtensionSupported() + } + } + + override fun enableAutomaticCallStatus(enabled: Boolean) { + innerClient.enableAutomaticCallStatus(enabled) } override suspend fun joinRoom(roomId: RoomId): Result = withContext(sessionDispatcher) { @@ -621,6 +653,7 @@ class RustMatrixClient( sessionCoroutineScope.cancel() clientDelegateTaskHandle?.cancelAndDestroy() + ownProfileTaskHandle?.cancelAndDestroy() sessionVerificationService.destroy() sessionDelegate.clearCurrentClient() @@ -647,11 +680,13 @@ class RustMatrixClient( } override suspend fun clearCache() { + _isShuttingDown.set(true) innerClient.clearCaches(innerSyncService) destroy() } override suspend fun logout(userInitiated: Boolean, ignoreSdkError: Boolean) { + _isShuttingDown.set(true) sessionCoroutineScope.cancel() // Remove current delegate so we don't receive an auth error clientDelegateTaskHandle?.cancelAndDestroy() @@ -689,6 +724,8 @@ class RustMatrixClient( } override suspend fun deactivateAccount(password: String, eraseData: Boolean): Result = withContext(sessionDispatcher) { + _isShuttingDown.set(true) + Timber.w("Deactivating account") // Remove current delegate so we don't receive an auth error clientDelegateTaskHandle?.cancelAndDestroy() @@ -806,6 +843,18 @@ class RustMatrixClient( } } + override suspend fun getAccountData(eventType: String): Result = withContext(sessionDispatcher) { + runCatchingExceptions { + innerClient.accountData(eventType) + } + } + + override suspend fun setAccountData(eventType: String, content: String): Result = withContext(sessionDispatcher) { + runCatchingExceptions { + innerClient.setAccountData(eventType, content) + } + } + override suspend fun canLinkNewDevice(): Result = withContext(sessionDispatcher) { runCatchingExceptions { innerClient.isLoginWithQrCodeSupported() @@ -855,12 +904,6 @@ class RustMatrixClient( } } - override suspend fun getMapStyleUrl(): Result = withContext(sessionDispatcher) { - runCatchingExceptions { - innerClient.tileServer()?.mapStyleUrl - } - } - override suspend fun resetWellKnownConfig(): Result { return runCatchingExceptions { Timber.d("Resetting well-known config for session $sessionId") diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientBuilder.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientBuilder.kt new file mode 100644 index 0000000000..b2f952f35b --- /dev/null +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientBuilder.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl + +import io.element.android.libraries.matrix.api.MatrixClientBuilder +import org.matrix.rustcomponents.sdk.ClientBuilder + +/** + * A wrapper around the Matrix SDK's [ClientBuilder] to allow sharing it with other modules without exposing the SDK directly. + */ +class RustMatrixClientBuilder( + val inner: ClientBuilder, +) : MatrixClientBuilder diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactory.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactory.kt index de2c5c0141..0d593626bb 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactory.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactory.kt @@ -9,6 +9,7 @@ package io.element.android.libraries.matrix.impl import dev.zacsweers.metro.Inject +import io.element.android.features.enterprise.api.ClientBuilderEnterpriseHook import io.element.android.libraries.androidutils.crypto.ClientSecret import io.element.android.libraries.core.coroutine.CoroutineDispatchers import io.element.android.libraries.core.data.ByteUnit @@ -17,9 +18,8 @@ import io.element.android.libraries.di.CacheDirectory import io.element.android.libraries.di.annotations.AppCoroutineScope import io.element.android.libraries.featureflag.api.FeatureFlagService import io.element.android.libraries.featureflag.api.FeatureFlags -import io.element.android.libraries.matrix.api.core.UserId +import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.matrix.api.paths.SessionPaths -import io.element.android.libraries.matrix.api.scanner.ContentScannerUrlProvider import io.element.android.libraries.matrix.impl.analytics.UtdTracker import io.element.android.libraries.matrix.impl.paths.getSessionPaths import io.element.android.libraries.matrix.impl.proxy.ProxyProvider @@ -37,7 +37,6 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.withContext import org.matrix.rustcomponents.sdk.Client import org.matrix.rustcomponents.sdk.ClientBuilder -import org.matrix.rustcomponents.sdk.ContentScanner import org.matrix.rustcomponents.sdk.CrossProcessLockConfig import org.matrix.rustcomponents.sdk.RequestConfig import org.matrix.rustcomponents.sdk.Session @@ -70,7 +69,7 @@ class RustMatrixClientFactory( private val clientBuilderProvider: ClientBuilderProvider, private val sqliteStoreBuilderProvider: SqliteStoreBuilderProvider, private val workManagerScheduler: WorkManagerScheduler, - private val contentScannerUrlProvider: ContentScannerUrlProvider, + private val clientBuilderEnterpriseHook: ClientBuilderEnterpriseHook, ) { private val sessionDelegate = RustClientSessionDelegate( sessionStore = sessionStore, @@ -101,6 +100,7 @@ class RustMatrixClientFactory( ) .homeserverUrl(sessionData.homeserverUrl) .username(sessionData.userId) + .let { (clientBuilderEnterpriseHook(RustMatrixClientBuilder(it), SessionId(sessionData.userId)) as RustMatrixClientBuilder).inner } .use { it.build() } client.setMediaRetentionPolicy( @@ -135,26 +135,10 @@ class RustMatrixClientFactory( client.setUtdDelegate(UtdTracker(analyticsService)) - val domainName = UserId(client.userId()).domainName - // If a content scanner URL is available for the homeserver, create a RustContentScanner and set it on the client. - // This allows the SDK to use the content scanner for automatic media scanning. - // If no content scanner URL is available, the contentScanner will be null. - val contentScanner = domainName?.let { - contentScannerUrlProvider.getContentScannerUrl(domainName) - .getOrNull() - ?.let { contentScannerUrl -> - val contentScanner = ContentScanner(contentScannerUrl) - client.setContentScanner(contentScanner) - RustContentScanner( - client = client, - rustScanner = contentScanner, - ) - } - } - val syncService = client.syncService() .withSharePos(true) .withOfflineMode() + .withProfilesExtension() .finish() return RustMatrixClient( @@ -171,7 +155,7 @@ class RustMatrixClientFactory( featureFlagService = featureFlagService, analyticsService = analyticsService, workManagerScheduler = workManagerScheduler, - contentScanner = contentScanner, + contentScanner = client.contentScanner()?.let { RustContentScanner(client, it) }, isMessageSearchAvailable = isMessageSearchAvailable, ).also { Timber.tag("RustMatrixClient").i("Creating Client with access token '$anonymizedAccessToken' and refresh token '$anonymizedRefreshToken'") diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClient.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClient.kt new file mode 100644 index 0000000000..f5b1f2ba4e --- /dev/null +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClient.kt @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl + +import io.element.android.libraries.core.extensions.mapFailure +import io.element.android.libraries.core.extensions.runCatchingExceptions +import io.element.android.libraries.matrix.api.TemporaryMatrixClient +import io.element.android.libraries.matrix.api.paths.SessionPaths +import io.element.android.libraries.matrix.impl.exception.mapClientException +import org.matrix.rustcomponents.sdk.Client + +class RustTemporaryMatrixClient( + private val client: Client, + private val paths: SessionPaths?, +) : TemporaryMatrixClient { + override suspend fun getUrl(url: String): Result = runCatchingExceptions { + client.getUrl(url) + }.mapFailure { it.mapClientException() } + + override val server: String? = client.server() + override val homeserverUrl: String = client.homeserver() + + override fun close() { + client.close() + paths?.let { + if (it.fileDirectory.exists()) { + it.fileDirectory.deleteRecursively() + } + if (it.cacheDirectory.exists()) { + it.cacheDirectory.deleteRecursively() + } + } + } +} diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientFactory.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientFactory.kt new file mode 100644 index 0000000000..0e7d8bf2c5 --- /dev/null +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientFactory.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl + +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesBinding +import io.element.android.libraries.core.extensions.runCatchingExceptions +import io.element.android.libraries.matrix.api.TemporaryMatrixClient +import io.element.android.libraries.matrix.api.TemporaryMatrixClientFactory +import io.element.android.libraries.matrix.impl.paths.SessionPathsFactory + +@ContributesBinding(AppScope::class) +class RustTemporaryMatrixClientFactory( + private val sessionPathsFactory: SessionPathsFactory, + private val rustMatrixClientFactory: RustMatrixClientFactory, +) : TemporaryMatrixClientFactory { + override suspend fun create(serverName: String): Result { + return runCatchingExceptions { + val sessionPaths = sessionPathsFactory.create() + val client = rustMatrixClientFactory.getBaseClientBuilder( + sessionPaths = sessionPaths, + clientSecret = null, + slidingSyncType = ClientBuilderSlidingSync.Native, + isMessageSearchAvailable = false, + ) + .serverName(serverName) + .build() + RustTemporaryMatrixClient(client, sessionPaths) + } + } +} diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/AuthenticationException.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/AuthenticationException.kt index fac5227f6a..6a06ac0599 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/AuthenticationException.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/AuthenticationException.kt @@ -29,6 +29,7 @@ fun Throwable.mapAuthenticationException(): AuthenticationException { is ClientBuildException.WellKnownLookupFailed -> AuthenticationException.Generic(message) is ClientBuildException.EventCache -> AuthenticationException.Generic(message) is ClientBuildException.InvalidRawKey -> AuthenticationException.Generic(message) + is ClientBuildException.WellKnownLookupDisabled -> AuthenticationException.Generic(message) } is OAuthException -> when (this) { is OAuthException.Generic -> AuthenticationException.OAuth(message) diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationService.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationService.kt index dd9f73c381..a1dacbee91 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationService.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationService.kt @@ -11,6 +11,7 @@ package io.element.android.libraries.matrix.impl.auth import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding import dev.zacsweers.metro.SingleIn +import io.element.android.features.enterprise.api.ClientEnterpriseHook import io.element.android.features.enterprise.api.EnterpriseService import io.element.android.libraries.androidutils.crypto.ClientSecret import io.element.android.libraries.core.coroutine.CoroutineDispatchers @@ -35,6 +36,7 @@ import io.element.android.libraries.matrix.api.paths.SessionPaths import io.element.android.libraries.matrix.api.verification.SessionVerifiedStatus import io.element.android.libraries.matrix.impl.ClientBuilderSlidingSync import io.element.android.libraries.matrix.impl.RustMatrixClientFactory +import io.element.android.libraries.matrix.impl.RustTemporaryMatrixClient import io.element.android.libraries.matrix.impl.auth.qrlogin.QrErrorMapper import io.element.android.libraries.matrix.impl.auth.qrlogin.SdkQrCodeLoginData import io.element.android.libraries.matrix.impl.auth.qrlogin.toStep @@ -72,6 +74,7 @@ class RustMatrixAuthenticationService( private val oAuthConfigurationProvider: OAuthConfigurationProvider, private val enterpriseService: EnterpriseService, private val featureFlagService: FeatureFlagService, + private val clientEnterpriseHook: ClientEnterpriseHook, ) : MatrixAuthenticationService { // Any existing Element Classic session that we want to try to import secrets from during login. private var elementClassicSession: ElementClassicSession? = null @@ -133,9 +136,10 @@ class RustMatrixAuthenticationService( } currentClient = client + client.homeserverLoginDetails().map() }.onFailure { - clear() + clear(destroyClient = true) }.mapFailure { failure -> Timber.e(failure, "Failed to set homeserver to $homeserver") failure.mapAuthenticationException() @@ -164,11 +168,15 @@ class RustMatrixAuthenticationService( sessionPaths = currentSessionPaths, ) val matrixClient = rustMatrixClientFactory.create(client, sessionData, isMessageSearchAvailable()) + + // Apply enterprise hooks to the newly created client as soon as possible + clientEnterpriseHook(matrixClient) + newMatrixClientObservers.forEach { it.invoke(matrixClient) } sessionStore.addSession(sessionData) // Clean up the strong reference held here since it's no longer necessary - currentClient = null + clear(destroyClient = false) SessionId(sessionData.userId) }.mapFailure { failure -> @@ -240,6 +248,9 @@ class RustMatrixAuthenticationService( client.restoreSession(sessionData.toSession()) val matrixClient = rustMatrixClientFactory.create(client, sessionData, isMessageSearchAvailable()) + // Apply enterprise hooks to the newly created client as soon as possible + clientEnterpriseHook(matrixClient) + // We wait for the verification state to be known matrixClient.waitForKnownVerificationState() @@ -248,7 +259,7 @@ class RustMatrixAuthenticationService( sessionStore.addSession(sessionData) // Clean up the strong reference held here since it's no longer necessary - currentClient = null + clear(destroyClient = false) SessionId(sessionData.userId) } @@ -271,11 +282,12 @@ class RustMatrixAuthenticationService( deviceId = null, additionalScopes = emptyList(), ) + val getUrlResolver = RustTemporaryMatrixClient(client, sessionPaths) val url = oAuthAuthorizationData.loginUrl() .let { enterpriseService.tweakMasUrl( url = it, - homeserver = client.server() ?: client.homeserver(), + urlContentFetcher = getUrlResolver, ) } pendingOAuthAuthorizationData = oAuthAuthorizationData @@ -329,13 +341,17 @@ class RustMatrixAuthenticationService( sessionPaths = currentSessionPaths, ) val matrixClient = rustMatrixClientFactory.create(client, sessionData, isMessageSearchAvailable()) + + // Apply enterprise hooks to the newly created client as soon as possible + clientEnterpriseHook(matrixClient) + matrixClient.waitForKnownVerificationState() newMatrixClientObservers.forEach { it.invoke(matrixClient) } sessionStore.addSession(sessionData) // Clean up the strong reference held here since it's no longer necessary - currentClient = null + clear(destroyClient = false) SessionId(sessionData.userId) }.mapFailure { failure -> @@ -394,11 +410,15 @@ class RustMatrixAuthenticationService( sessionPaths = emptySessionPaths, ) val matrixClient = rustMatrixClientFactory.create(client, sessionData, isMessageSearchAvailable()) + + // Apply enterprise hooks to the newly created client as soon as possible + clientEnterpriseHook(matrixClient) + newMatrixClientObservers.forEach { it.invoke(matrixClient) } sessionStore.addSession(sessionData) // Clean up the strong reference held here since it's no longer necessary - currentClient = null + clear(destroyClient = false) SessionId(sessionData.userId) }.mapFailure { @@ -464,8 +484,10 @@ class RustMatrixAuthenticationService( .build() } - private fun clear() { - currentClient?.close() + private fun clear(destroyClient: Boolean) { + if (destroyClient) { + currentClient?.close() + } currentClient = null } diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/RoomModule.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/RoomBindingContainer.kt similarity index 96% rename from libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/RoomModule.kt rename to libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/RoomBindingContainer.kt index af6f0325d3..d598f85bad 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/RoomModule.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/RoomBindingContainer.kt @@ -18,7 +18,7 @@ import kotlinx.coroutines.CoroutineScope @BindingContainer @ContributesTo(RoomScope::class) -object RoomModule { +object RoomBindingContainer { @RoomCoroutineScope @Provides fun providesSessionCoroutineScope(room: BaseRoom): CoroutineScope { diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/SessionMatrixModule.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/SessionMatrixBindingContainer.kt similarity index 87% rename from libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/SessionMatrixModule.kt rename to libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/SessionMatrixBindingContainer.kt index e88dc382e8..f50c0a04cc 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/SessionMatrixModule.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/di/SessionMatrixBindingContainer.kt @@ -13,6 +13,7 @@ import dev.zacsweers.metro.ContributesTo import dev.zacsweers.metro.Provides import io.element.android.libraries.di.SessionScope import io.element.android.libraries.di.annotations.SessionCoroutineScope +import io.element.android.libraries.matrix.api.ClientUrlContentFetcher import io.element.android.libraries.matrix.api.HomeserverCapabilitiesProvider import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.api.core.DeviceId @@ -25,6 +26,7 @@ import io.element.android.libraries.matrix.api.room.RoomMembershipObserver import io.element.android.libraries.matrix.api.roomdirectory.RoomDirectoryService import io.element.android.libraries.matrix.api.roomlist.RoomListService import io.element.android.libraries.matrix.api.scanner.ContentScanner +import io.element.android.libraries.matrix.api.search.MessageSearchService import io.element.android.libraries.matrix.api.spaces.SpaceService import io.element.android.libraries.matrix.api.sync.SyncService import io.element.android.libraries.matrix.api.verification.SessionVerificationService @@ -32,7 +34,7 @@ import kotlinx.coroutines.CoroutineScope @BindingContainer @ContributesTo(SessionScope::class) -object SessionMatrixModule { +object SessionMatrixBindingContainer { @Provides fun providesSessionId(matrixClient: MatrixClient): SessionId { return matrixClient.sessionId @@ -54,7 +56,7 @@ object SessionMatrixModule { } @Provides - fun provideRoomMembershipObserver(matrixClient: MatrixClient): RoomMembershipObserver { + fun providesRoomMembershipObserver(matrixClient: MatrixClient): RoomMembershipObserver { return matrixClient.roomMembershipObserver } @@ -108,4 +110,14 @@ object SessionMatrixModule { fun providesContentScanner(matrixClient: MatrixClient): ContentScanner? { return matrixClient.contentScanner } + + @Provides + fun providesClientUrlContentFetcher(matrixClient: MatrixClient): ClientUrlContentFetcher { + return matrixClient + } + + @Provides + fun providesMessageSearchService(matrixClient: MatrixClient): MessageSearchService { + return matrixClient.messageSearchService + } } diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustContinuationMessageSender.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustContinuationMessageSender.kt new file mode 100644 index 0000000000..f4f17fb9a7 --- /dev/null +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustContinuationMessageSender.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl.linknewdevice + +import io.element.android.libraries.core.extensions.runCatchingExceptions +import io.element.android.libraries.matrix.api.linknewdevice.ContinuationMessageSender +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext +import timber.log.Timber +import org.matrix.rustcomponents.sdk.ContinuationMessageSender as FfiContinuationMessageSender + +class RustContinuationMessageSender( + private val inner: FfiContinuationMessageSender, + private val sessionDispatcher: CoroutineDispatcher, +) : ContinuationMessageSender { + override suspend fun cancel(): Result = withContext(sessionDispatcher) { + runCatchingExceptions { + inner.cancel() + }.onFailure { + Timber.e(it, "Error cancelling continuation message") + } + } + + override suspend fun confirm(): Result = withContext(sessionDispatcher) { + runCatchingExceptions { + inner.confirm() + }.onFailure { + Timber.e(it, "Error confirming continuation message") + } + } +} diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandler.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandler.kt index 83e657eb07..8c9695ae4b 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandler.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandler.kt @@ -75,6 +75,10 @@ class RustLinkDesktopHandler( GrantQrLoginProgress.SyncingSecrets -> LinkDesktopStep.SyncingSecrets is GrantQrLoginProgress.WaitingForAuth -> LinkDesktopStep.WaitingForAuth( verificationUri = verificationUri, + continuationMessageSender = RustContinuationMessageSender( + inner = continuationSender, + sessionDispatcher = sessionDispatcher, + ) ) is GrantQrLoginProgress.EstablishingSecureChannel -> LinkDesktopStep.EstablishingSecureChannel( checkCode = checkCode, diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandler.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandler.kt index a44a8d5943..33f1ad736d 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandler.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandler.kt @@ -84,7 +84,13 @@ class RustLinkMobileHandler( ) GrantGeneratedQrLoginProgress.Starting -> LinkMobileStep.Starting GrantGeneratedQrLoginProgress.SyncingSecrets -> LinkMobileStep.SyncingSecrets - is GrantGeneratedQrLoginProgress.WaitingForAuth -> LinkMobileStep.WaitingForAuth(verificationUri) + is GrantGeneratedQrLoginProgress.WaitingForAuth -> LinkMobileStep.WaitingForAuth( + verificationUri = verificationUri, + continuationMessageSender = RustContinuationMessageSender( + inner = continuationSender, + sessionDispatcher = sessionDispatcher, + ) + ) } } } diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/media/RustMediaLoader.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/media/RustMediaLoader.kt index d1401d2624..7b3a1d9f10 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/media/RustMediaLoader.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/media/RustMediaLoader.kt @@ -11,7 +11,7 @@ package io.element.android.libraries.matrix.impl.media import io.element.android.libraries.core.coroutine.CoroutineDispatchers import io.element.android.libraries.core.extensions.mapFailure import io.element.android.libraries.core.extensions.runCatchingExceptions -import io.element.android.libraries.core.mimetype.MimeTypes +import io.element.android.libraries.core.mimetype.MimeTypes.ensureDefaultSubtype import io.element.android.libraries.matrix.api.media.MatrixMediaLoader import io.element.android.libraries.matrix.api.media.MediaFile import io.element.android.libraries.matrix.api.media.MediaSource @@ -71,15 +71,8 @@ class RustMediaLoader( val mediaFile = innerClient.getMediaFile( mediaSource = mediaSource, filename = filename, - mimeType = when { - mimeType == null -> MimeTypes.OctetStream - MimeTypes.hasSubtype(mimeType) -> mimeType - // Fallback to a default mime type based on the main type, so that the SDK can create a file with the correct extension. - mimeType == MimeTypes.Images -> MimeTypes.Jpeg - mimeType == MimeTypes.Videos -> MimeTypes.Mp4 - mimeType == MimeTypes.Audio -> MimeTypes.Mp3 - else -> MimeTypes.OctetStream - }, + // Fallback to a default mime type based on the main type, so that the SDK can create a file with the correct extension. + mimeType = mimeType.ensureDefaultSubtype(), useCache = useCache, tempDir = cacheDirectory.path, ) diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/permalink/DefaultPermalinkParser.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/permalink/DefaultPermalinkParser.kt index e59530e874..a5f372d7d1 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/permalink/DefaultPermalinkParser.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/permalink/DefaultPermalinkParser.kt @@ -8,11 +8,13 @@ package io.element.android.libraries.matrix.impl.permalink +import android.net.Uri import androidx.core.net.toUri import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding import io.element.android.libraries.core.extensions.runCatchingExceptions import io.element.android.libraries.matrix.api.core.EventId +import io.element.android.libraries.matrix.api.core.MatrixPatterns import io.element.android.libraries.matrix.api.core.RoomAlias import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.core.UserId @@ -51,6 +53,10 @@ class DefaultPermalinkParser( matrixToConverter.convert(uri) ?: return PermalinkData.FallbackLink(uri) } + matrixToUri.userIdWithSlash()?.let { userId -> + return PermalinkData.UserLink(userId = userId) + } + val result = runCatchingExceptions { parseMatrixEntityFrom(matrixToUri.toString()) }.getOrNull() @@ -84,3 +90,17 @@ class DefaultPermalinkParser( } } } + +/** + * A slash is allowed in the local part of a user id, but it also separates an identifier from an + * event id in a permalink, so [parseMatrixEntityFrom] cannot tell the two apart. Only a user id can + * start with an `@`, so recover it here rather than letting the ambiguity reach the SDK. + */ +private fun Uri.userIdWithSlash(): UserId? { + val identifier = fragment + ?.removePrefix("/") + ?.substringBefore('?') + ?: return null + if (!identifier.startsWith("@") || !identifier.contains('/')) return null + return identifier.takeIf { MatrixPatterns.isUserId(it) }?.let(::UserId) +} diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/JoinedRustRoom.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/JoinedRustRoom.kt index 68fcf6287c..d454d7c775 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/JoinedRustRoom.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/JoinedRustRoom.kt @@ -53,6 +53,7 @@ import io.element.android.libraries.matrix.impl.room.threads.RustThreadsListServ import io.element.android.libraries.matrix.impl.roomdirectory.map import io.element.android.libraries.matrix.impl.timeline.RustTimeline import io.element.android.libraries.matrix.impl.timeline.item.event.TimelineEventContentMapper +import io.element.android.libraries.matrix.impl.user.map import io.element.android.libraries.matrix.impl.util.MessageEventContent import io.element.android.libraries.matrix.impl.util.mxCallbackFlow import io.element.android.libraries.matrix.impl.widget.RustWidgetDriver diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/RoomInfoMapper.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/RoomInfoMapper.kt index a972b3c130..33d7017ff9 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/RoomInfoMapper.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/RoomInfoMapper.kt @@ -16,12 +16,15 @@ import io.element.android.libraries.matrix.api.room.CurrentUserMembership import io.element.android.libraries.matrix.api.room.RoomInfo import io.element.android.libraries.matrix.api.room.RoomNotificationMode import io.element.android.libraries.matrix.api.room.powerlevels.RoomPowerLevels +import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.impl.room.history.map import io.element.android.libraries.matrix.impl.room.join.map import io.element.android.libraries.matrix.impl.room.member.RoomMemberMapper import io.element.android.libraries.matrix.impl.room.powerlevels.RoomPowerLevelsValuesMapper import io.element.android.libraries.matrix.impl.room.tombstone.map +import io.element.android.libraries.matrix.impl.user.from +import io.element.android.libraries.matrix.impl.user.into import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableMap import org.matrix.rustcomponents.sdk.Membership @@ -102,7 +105,9 @@ fun RustRoomNotificationMode.map(): RoomNotificationMode = when (this) { fun RoomHero.map(): MatrixUser = MatrixUser( userId = UserId(userId), displayName = displayName, - avatarUrl = avatarUrl + avatarUrl = avatarUrl, + displayedStatus = DisplayedStatus.from(status, call), + rawStatus = status?.into(), ) fun mapPowerLevels(roomPowerLevels: RustRoomPowerLevels): RoomPowerLevels { diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/member/RoomMemberMapper.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/member/RoomMemberMapper.kt index b2a530f806..bcff7fc153 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/member/RoomMemberMapper.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/member/RoomMemberMapper.kt @@ -11,7 +11,9 @@ package io.element.android.libraries.matrix.impl.room.member import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.room.RoomMember import io.element.android.libraries.matrix.api.room.RoomMembershipState +import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.impl.room.powerlevels.into +import io.element.android.libraries.matrix.impl.user.from import uniffi.matrix_sdk.RoomMemberRole import org.matrix.rustcomponents.sdk.MembershipState as RustMembershipState import org.matrix.rustcomponents.sdk.RoomMember as RustRoomMember @@ -30,8 +32,7 @@ object RoomMemberMapper { role = mapRole(roomMember.suggestedRoleForPowerLevel, powerLevel), membershipChangeReason = roomMember.membershipChangeReason, isServiceMember = roomMember.isServiceMember, - // TODO map this value when available - displayedStatus = null, + displayedStatus = DisplayedStatus.from(roomMember.status, roomMember.call), ) } diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/scanner/DefaultContentScannerUrlProvider.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/scanner/DefaultContentScannerUrlProvider.kt deleted file mode 100644 index b43dcfb3e8..0000000000 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/scanner/DefaultContentScannerUrlProvider.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2026 Element Creations Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.libraries.matrix.impl.scanner - -import dev.zacsweers.metro.AppScope -import dev.zacsweers.metro.ContributesBinding -import io.element.android.libraries.matrix.api.scanner.ContentScannerUrlProvider - -/** - * Default FOSS implementation of [ContentScannerUrlProvider] that returns `null` for the content scanner URL. - */ -@ContributesBinding(AppScope::class) -class DefaultContentScannerUrlProvider : ContentScannerUrlProvider { - override suspend fun getContentScannerUrl(homeserver: String): Result = Result.success(null) -} diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/RustTimeline.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/RustTimeline.kt index bd756bc002..c6a737e156 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/RustTimeline.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/RustTimeline.kt @@ -75,6 +75,7 @@ import org.matrix.rustcomponents.sdk.PollData import org.matrix.rustcomponents.sdk.SendAttachmentJoinHandle import org.matrix.rustcomponents.sdk.UploadParameters import org.matrix.rustcomponents.sdk.UploadSource +import org.matrix.rustcomponents.sdk.createCaptionEdit import org.matrix.rustcomponents.sdk.use import timber.log.Timber import uniffi.matrix_sdk.PaginationStatus @@ -341,7 +342,7 @@ class RustTimeline( formattedCaption: String?, ): Result = withContext(dispatcher) { runCatchingExceptions { - val editedContent = EditedContent.MediaCaption( + val editedContent = createCaptionEdit( caption = caption, formattedCaption = formattedCaption?.let { FormattedBody(body = it, format = MessageFormat.Html) @@ -365,7 +366,7 @@ class RustTimeline( fromNotification: Boolean, msgType: MsgType, ): Result = withContext(dispatcher) { - runCatchingExceptions { + runCatchingExceptions { val msg = MessageEventContent.from( body = body, htmlBody = htmlBody, diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/item/event/EventTimelineItemMapper.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/item/event/EventTimelineItemMapper.kt index 801d5fd146..3a568761ce 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/item/event/EventTimelineItemMapper.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/timeline/item/event/EventTimelineItemMapper.kt @@ -21,7 +21,9 @@ import io.element.android.libraries.matrix.api.timeline.item.event.ProfileDetail import io.element.android.libraries.matrix.api.timeline.item.event.ReactionSender import io.element.android.libraries.matrix.api.timeline.item.event.Receipt import io.element.android.libraries.matrix.api.timeline.item.event.TimelineItemEventOrigin +import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.impl.core.RustSendHandle +import io.element.android.libraries.matrix.impl.user.from import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList @@ -75,8 +77,7 @@ fun RustProfileDetails.map(): ProfileDetails { displayName = displayName, displayNameAmbiguous = displayNameAmbiguous, avatarUrl = avatarUrl, - // TODO map this value when available - displayedStatus = null, + displayedStatus = DisplayedStatus.from(status, call), ) } } diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/mapper/UserProfileMapper.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserProfileMapper.kt similarity index 71% rename from libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/mapper/UserProfileMapper.kt rename to libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserProfileMapper.kt index 14c813548a..c9c64d83b6 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/mapper/UserProfileMapper.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserProfileMapper.kt @@ -6,9 +6,10 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.libraries.matrix.impl.mapper +package io.element.android.libraries.matrix.impl.user import io.element.android.libraries.matrix.api.core.UserId +import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.MatrixUser import org.matrix.rustcomponents.sdk.UserProfile @@ -16,4 +17,6 @@ fun UserProfile.map() = MatrixUser( userId = UserId(userId), displayName = displayName, avatarUrl = avatarUrl, + rawStatus = status?.into(), + displayedStatus = DisplayedStatus.from(status, call) ) diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/usersearch/UserSearchResultMapper.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserSearchResultMapper.kt similarity index 86% rename from libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/usersearch/UserSearchResultMapper.kt rename to libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserSearchResultMapper.kt index 5a6481b4f8..f9b1503c8c 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/usersearch/UserSearchResultMapper.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserSearchResultMapper.kt @@ -6,10 +6,9 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.libraries.matrix.impl.usersearch +package io.element.android.libraries.matrix.impl.user import io.element.android.libraries.matrix.api.user.MatrixSearchUserResults -import io.element.android.libraries.matrix.impl.mapper.map import kotlinx.collections.immutable.toImmutableList import org.matrix.rustcomponents.sdk.SearchUsersResults diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserStatus.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserStatus.kt new file mode 100644 index 0000000000..1b8a738bf2 --- /dev/null +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/user/UserStatus.kt @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl.user + +import io.element.android.libraries.matrix.api.user.DisplayedStatus +import io.element.android.libraries.matrix.api.user.UserStatus +import org.matrix.rustcomponents.sdk.UserCall +import org.matrix.rustcomponents.sdk.UserStatus as RustUserStatus + +fun UserStatus.into(): RustUserStatus { + return RustUserStatus(emoji = emoji, text = text) +} + +fun RustUserStatus.into(): UserStatus { + return UserStatus(emoji = emoji, text = text) +} + +fun DisplayedStatus.Companion.from(userStatus: RustUserStatus?, userCall: UserCall?): DisplayedStatus? { + return when { + userStatus != null -> DisplayedStatus.UserSet(userStatus.into()) + userCall != null -> DisplayedStatus.InCall(userCall.callJoinedTs?.toLong()) + else -> null + } +} diff --git a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/verification/SessionVerificationRequestDetails.kt b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/verification/SessionVerificationRequestDetails.kt index d88f9fd6ce..c3b6d33b82 100644 --- a/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/verification/SessionVerificationRequestDetails.kt +++ b/libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/verification/SessionVerificationRequestDetails.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.matrix.api.core.FlowId import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.verification.SessionVerificationRequestDetails import io.element.android.libraries.matrix.api.verification.VerificationRequest -import io.element.android.libraries.matrix.impl.mapper.map +import io.element.android.libraries.matrix.impl.user.map import org.matrix.rustcomponents.sdk.SessionVerificationRequestDetails as RustSessionVerificationRequestDetails fun RustSessionVerificationRequestDetails.map() = SessionVerificationRequestDetails( diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactoryTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactoryTest.kt index d1536d949e..6d3afad5c3 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactoryTest.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientFactoryTest.kt @@ -11,7 +11,6 @@ package io.element.android.libraries.matrix.impl import com.google.common.truth.Truth.assertThat import io.element.android.libraries.featureflag.test.FakeFeatureFlagService import io.element.android.libraries.matrix.api.core.SessionId -import io.element.android.libraries.matrix.api.scanner.ContentScannerUrlProvider import io.element.android.libraries.matrix.impl.auth.FakeProxyProvider import io.element.android.libraries.matrix.impl.room.FakeTimelineEventFilterFactory import io.element.android.libraries.matrix.impl.storage.FakeSqliteStoreBuilderProvider @@ -52,7 +51,6 @@ fun TestScope.createRustMatrixClientFactory( ), clientBuilderProvider: ClientBuilderProvider = FakeClientBuilderProvider(), workManagerScheduler: FakeWorkManagerScheduler = FakeWorkManagerScheduler(), - contentScannerUrlProvider: ContentScannerUrlProvider = { Result.success(null) }, ) = RustMatrixClientFactory( cacheDirectory = cacheDirectory, appCoroutineScope = backgroundScope, @@ -67,5 +65,5 @@ fun TestScope.createRustMatrixClientFactory( clientBuilderProvider = clientBuilderProvider, sqliteStoreBuilderProvider = FakeSqliteStoreBuilderProvider(), workManagerScheduler = workManagerScheduler, - contentScannerUrlProvider = contentScannerUrlProvider, + clientBuilderEnterpriseHook = { builder, _ -> builder }, ) diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientTest.kt index 4ea4bb64e3..ea399b39df 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientTest.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustMatrixClientTest.kt @@ -32,9 +32,9 @@ import io.element.android.services.toolbox.test.systemclock.FakeSystemClock import io.element.android.tests.testutils.lambda.lambdaRecorder import io.element.android.tests.testutils.lambda.value import io.element.android.tests.testutils.testCoroutineDispatchers +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import org.junit.Test import org.matrix.rustcomponents.sdk.Client @@ -44,6 +44,9 @@ import org.matrix.rustcomponents.sdk.StoreSizes import org.matrix.rustcomponents.sdk.UserProfile import java.io.File +private const val AN_ACCOUNT_DATA_EVENT_TYPE = "org.example.custom" +private const val AN_ACCOUNT_DATA_CONTENT = """{"key":"value"}""" + class RustMatrixClientTest { @Test fun `ensure that sessionId and deviceId can be retrieved from the client`() = runTest { @@ -72,7 +75,8 @@ class RustMatrixClientTest { @Test fun `retrieving the UserProfile updates the database`() = runTest { - val updateUserProfileResult = lambdaRecorder { _, _, _ -> } + val profilePersisted = CompletableDeferred() + val updateUserProfileResult = lambdaRecorder { _, _, _ -> profilePersisted.complete(Unit) } val sessionStore = InMemorySessionStore( initialList = listOf( aSessionData( @@ -97,7 +101,7 @@ class RustMatrixClientTest { ), sessionStore = sessionStore, ) - advanceUntilIdle() + profilePersisted.await() updateUserProfileResult.assertions().isCalledOnce() .with( value(A_USER_ID.value), @@ -138,6 +142,30 @@ class RustMatrixClientTest { assertThat(createParameters?.historyVisibilityOverride).isEqualTo(RoomHistoryVisibility.Invited) } + @Test + fun `getAccountData returns the raw content provided by the client`() = runTest { + val accountDataResult = lambdaRecorder { AN_ACCOUNT_DATA_CONTENT } + val client = createRustMatrixClient( + client = FakeFfiClient(accountDataResult = accountDataResult) + ) + + assertThat(client.getAccountData(AN_ACCOUNT_DATA_EVENT_TYPE).getOrThrow()).isEqualTo(AN_ACCOUNT_DATA_CONTENT) + accountDataResult.assertions().isCalledOnce().with(value(AN_ACCOUNT_DATA_EVENT_TYPE)) + client.destroy() + } + + @Test + fun `setAccountData forwards the event type and the raw content to the client`() = runTest { + val setAccountDataResult = lambdaRecorder { _, _ -> } + val client = createRustMatrixClient( + client = FakeFfiClient(setAccountDataResult = setAccountDataResult) + ) + + assertThat(client.setAccountData(AN_ACCOUNT_DATA_EVENT_TYPE, AN_ACCOUNT_DATA_CONTENT).isSuccess).isTrue() + setAccountDataResult.assertions().isCalledOnce().with(value(AN_ACCOUNT_DATA_EVENT_TYPE), value(AN_ACCOUNT_DATA_CONTENT)) + client.destroy() + } + private fun TestScope.createRustMatrixClient( client: Client = FakeFfiClient(), sessionStore: SessionStore = InMemorySessionStore( diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientFactoryTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientFactoryTest.kt new file mode 100644 index 0000000000..d0b87ef53a --- /dev/null +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientFactoryTest.kt @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl + +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.featureflag.test.FakeFeatureFlagService +import io.element.android.libraries.matrix.impl.auth.FakeProxyProvider +import io.element.android.libraries.matrix.impl.paths.SessionPathsFactory +import io.element.android.libraries.matrix.impl.room.FakeTimelineEventFilterFactory +import io.element.android.libraries.matrix.impl.storage.FakeSqliteStoreBuilderProvider +import io.element.android.libraries.network.useragent.SimpleUserAgentProvider +import io.element.android.libraries.sessionstorage.api.SessionStore +import io.element.android.libraries.sessionstorage.test.InMemorySessionStore +import io.element.android.libraries.workmanager.test.FakeWorkManagerScheduler +import io.element.android.services.analytics.test.FakeAnalyticsService +import io.element.android.services.toolbox.test.systemclock.FakeSystemClock +import io.element.android.tests.testutils.testCoroutineDispatchers +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import org.junit.Test +import java.io.File + +class RustTemporaryMatrixClientFactoryTest { + @Test + fun `create returns a TemporaryMatrixClient`() = runTest { + val sut = createRustTemporaryMatrixClientFactory() + val result = sut.create("https://matrix.org") + assertThat(result.isSuccess).isTrue() + } + + @Test + fun `create can fail gracefully`() = runTest { + val sut = createRustTemporaryMatrixClientFactory( + rustMatrixClientFactory = createRustMatrixClientFactory( + clientBuilderProvider = FakeClientBuilderProvider( + provideResult = { throw IllegalStateException("Failed to create client builder") } + ) + ) + ) + val result = sut.create("https://matrix.org") + assertThat(result.isFailure).isTrue() + } + + private fun TestScope.createRustTemporaryMatrixClientFactory( + sessionPathsFactory: SessionPathsFactory = SessionPathsFactory(File("/base"), File("/cache")), + rustMatrixClientFactory: RustMatrixClientFactory = createRustMatrixClientFactory(), + ): RustTemporaryMatrixClientFactory { + return RustTemporaryMatrixClientFactory( + sessionPathsFactory = sessionPathsFactory, + rustMatrixClientFactory = rustMatrixClientFactory, + ) + } + + private fun TestScope.createRustMatrixClientFactory( + cacheDirectory: File = File("/cache"), + sessionStore: SessionStore = InMemorySessionStore( + updateUserProfileResult = { _, _, _ -> }, + ), + clientBuilderProvider: ClientBuilderProvider = FakeClientBuilderProvider(), + workManagerScheduler: FakeWorkManagerScheduler = FakeWorkManagerScheduler(), + ) = RustMatrixClientFactory( + cacheDirectory = cacheDirectory, + appCoroutineScope = backgroundScope, + coroutineDispatchers = testCoroutineDispatchers(), + sessionStore = sessionStore, + userAgentProvider = SimpleUserAgentProvider(), + proxyProvider = FakeProxyProvider(), + clock = FakeSystemClock(), + analyticsService = FakeAnalyticsService(), + featureFlagService = FakeFeatureFlagService(), + timelineEventFilterFactory = FakeTimelineEventFilterFactory(), + clientBuilderProvider = clientBuilderProvider, + sqliteStoreBuilderProvider = FakeSqliteStoreBuilderProvider(), + workManagerScheduler = workManagerScheduler, + clientBuilderEnterpriseHook = { builder, _ -> builder }, + ) +} diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientTest.kt new file mode 100644 index 0000000000..23e0cf2302 --- /dev/null +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/RustTemporaryMatrixClientTest.kt @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl + +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.matrix.api.exception.ClientException +import io.element.android.libraries.matrix.api.paths.SessionPaths +import io.element.android.libraries.matrix.impl.fixtures.fakes.FakeFfiClient +import io.element.android.tests.testutils.lambda.lambdaRecorder +import io.element.android.tests.testutils.lambda.value +import kotlinx.coroutines.test.runTest +import org.junit.Test +import org.matrix.rustcomponents.sdk.Client +import java.io.File +import kotlin.io.path.createTempDirectory +import org.matrix.rustcomponents.sdk.ClientException as RustClientException + +class RustTemporaryMatrixClientTest { + @Test + fun `getUrl method uses client getUrl`() = runTest { + val paths = SessionPaths( + fileDirectory = File("files"), + cacheDirectory = File("cache"), + ) + + val getUrlRecorder = lambdaRecorder { ByteArray(0) } + val client = createRustTemporaryMatrixClient( + client = FakeFfiClient( + getUrlResult = getUrlRecorder, + ), + paths = paths, + ) + val url = "https://example.com" + + client.getUrl(url) + + getUrlRecorder.assertions().isCalledOnce().with(value(url)) + } + + @Test + fun `getUrl method can fail gracefully and map errors to public ones`() = runTest { + val paths = SessionPaths( + fileDirectory = File("files"), + cacheDirectory = File("cache"), + ) + + val getUrlRecorder = lambdaRecorder { throw RustClientException.Generic("Error", null) } + val client = createRustTemporaryMatrixClient( + client = FakeFfiClient( + getUrlResult = getUrlRecorder, + ), + paths = paths, + ) + val url = "https://example.com" + + val result = client.getUrl(url) + + assertThat(result.isFailure).isTrue() + assertThat(result.exceptionOrNull()).isInstanceOf(ClientException.Generic::class.java) + } + + @Test + fun `close deletes the directories if they exist`() = runTest { + val paths = SessionPaths( + fileDirectory = createTempDirectory().toFile(), + cacheDirectory = createTempDirectory().toFile(), + ) + + val client = createRustTemporaryMatrixClient(paths = paths) + + assertThat(paths.fileDirectory.exists()).isTrue() + assertThat(paths.cacheDirectory.exists()).isTrue() + + client.close() + + assertThat(paths.fileDirectory.exists()).isFalse() + assertThat(paths.cacheDirectory.exists()).isFalse() + } + + private fun createRustTemporaryMatrixClient( + client: Client = FakeFfiClient(), + paths: SessionPaths, + ): RustTemporaryMatrixClient { + return RustTemporaryMatrixClient(client, paths) + } +} diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationServiceTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationServiceTest.kt index f5f3ffd10b..5d66e4f4bd 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationServiceTest.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/auth/RustMatrixAuthenticationServiceTest.kt @@ -23,6 +23,7 @@ import io.element.android.libraries.matrix.test.auth.FakeOAuthRedirectUrlProvide import io.element.android.libraries.matrix.test.core.aBuildMeta import io.element.android.libraries.sessionstorage.api.SessionStore import io.element.android.libraries.sessionstorage.test.InMemorySessionStore +import io.element.android.tests.testutils.lambda.lambdaRecorder import io.element.android.tests.testutils.testCoroutineDispatchers import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest @@ -50,6 +51,29 @@ class RustMatrixAuthenticationServiceTest { assertThat(sut.setHomeserver("matrix.org").isSuccess).isTrue() } + @Test + fun `setHomeserver can fail gracefully and clean up the temporary client`() = runTest { + val closeResult = lambdaRecorder {} + val sut = createRustMatrixAuthenticationService( + clientBuilderProvider = FakeClientBuilderProvider( + provideResult = { + FakeFfiClientBuilder( + buildResult = { + FakeFfiClient( + homeserverLoginDetailsResult = { + throw IllegalStateException("Failed to get homeserver login details") + }, + closeResult = closeResult, + ) + }, + ) + }, + ), + ) + assertThat(sut.setHomeserver("matrix.org").isFailure).isTrue() + closeResult.assertions().isCalledOnce() + } + private fun TestScope.createRustMatrixAuthenticationService( sessionStore: SessionStore = InMemorySessionStore(), clientBuilderProvider: ClientBuilderProvider = FakeClientBuilderProvider(), @@ -74,6 +98,7 @@ class RustMatrixAuthenticationServiceTest { ), enterpriseService = enterpriseService, featureFlagService = FakeFeatureFlagService(), + clientEnterpriseHook = {}, ) } } diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiClient.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiClient.kt index efae379415..86587da6c1 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiClient.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiClient.kt @@ -10,13 +10,16 @@ package io.element.android.libraries.matrix.impl.fixtures.fakes import io.element.android.libraries.matrix.impl.fixtures.factories.aRustSession import io.element.android.libraries.matrix.impl.fixtures.factories.aRustUserProfile +import io.element.android.libraries.matrix.impl.scanner.FakeFfiContentScanner import io.element.android.libraries.matrix.test.A_DEVICE_ID import io.element.android.libraries.matrix.test.A_HOMESERVER_URL +import io.element.android.libraries.matrix.test.A_SERVER_NAME import io.element.android.libraries.matrix.test.A_USER_ID import io.element.android.tests.testutils.lambda.lambdaError import io.element.android.tests.testutils.simulateLongTask import org.matrix.rustcomponents.sdk.Client import org.matrix.rustcomponents.sdk.ClientDelegate +import org.matrix.rustcomponents.sdk.ContentScanner import org.matrix.rustcomponents.sdk.CreateRoomParameters import org.matrix.rustcomponents.sdk.Encryption import org.matrix.rustcomponents.sdk.HomeserverCapabilities @@ -26,6 +29,7 @@ import org.matrix.rustcomponents.sdk.NoHandle import org.matrix.rustcomponents.sdk.NotificationClient import org.matrix.rustcomponents.sdk.NotificationProcessSetup import org.matrix.rustcomponents.sdk.NotificationSettings +import org.matrix.rustcomponents.sdk.ProfileListener import org.matrix.rustcomponents.sdk.PusherIdentifiers import org.matrix.rustcomponents.sdk.PusherKind import org.matrix.rustcomponents.sdk.RoomDirectorySearch @@ -44,6 +48,7 @@ class FakeFfiClient( private val userId: String = A_USER_ID.value, private val deviceId: String = A_DEVICE_ID.value, private val homeserver: String = A_HOMESERVER_URL, + private val server: String? = A_SERVER_NAME, private val notificationClient: NotificationClient = FakeFfiNotificationClient(), private val notificationSettings: NotificationSettings = FakeFfiNotificationSettings(), private val encryption: Encryption = FakeFfiEncryption(), @@ -55,11 +60,19 @@ class FakeFfiClient( private val getStoreSizesResult: () -> StoreSizes = { lambdaError() }, private val createRoomResult: (CreateRoomParameters) -> String = { lambdaError() }, private val homeserverCapabilities: HomeserverCapabilities = FakeFfiHomeserverCapabilities(), + private val accountDataResult: (String) -> String? = { lambdaError() }, + private val setAccountDataResult: (String, String) -> Unit = { _, _ -> lambdaError() }, + private val isUserStatusSupportedResult: () -> Boolean = { false }, + private val isProfilesSlidingSyncExtensionSupportedResult: () -> Boolean = { false }, + private val subscribeToOwnProfileResult: (ProfileListener) -> Unit = {}, + private val getUrlResult: (String) -> ByteArray = { lambdaError() }, + private val contentScannerResult: () -> ContentScanner = { FakeFfiContentScanner() }, private val closeResult: () -> Unit = {}, ) : Client(NoHandle) { override fun userId(): String = userId override fun deviceId(): String = deviceId override fun homeserver(): String = homeserver + override fun server(): String? = server override suspend fun notificationClient(processSetup: NotificationProcessSetup) = notificationClient override suspend fun getNotificationSettings(): NotificationSettings = notificationSettings override fun encryption(): Encryption = encryption @@ -92,6 +105,15 @@ class FakeFfiClient( return FakeFfiTaskHandle() } + override suspend fun isUserStatusSupported(): Boolean = isUserStatusSupportedResult() + + override suspend fun isProfilesSlidingSyncExtensionSupported(): Boolean = isProfilesSlidingSyncExtensionSupportedResult() + + override fun subscribeToOwnProfile(listener: ProfileListener): TaskHandle { + subscribeToOwnProfileResult(listener) + return FakeFfiTaskHandle() + } + override suspend fun getProfile(userId: String): UserProfile { return getProfileResult(userId) } @@ -114,5 +136,21 @@ class FakeFfiClient( return homeserverCapabilities } + override suspend fun accountData(eventType: String): String? = simulateLongTask { + accountDataResult(eventType) + } + + override suspend fun setAccountData(eventType: String, content: String) = simulateLongTask { + setAccountDataResult(eventType, content) + } + + override suspend fun getUrl(url: String): ByteArray = simulateLongTask { + getUrlResult(url) + } + + override suspend fun contentScanner(): ContentScanner = simulateLongTask { + contentScannerResult() + } + override fun close() = closeResult() } diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiSyncServiceBuilder.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiSyncServiceBuilder.kt index 2cb67f2519..5a2615aa2b 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiSyncServiceBuilder.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/fixtures/fakes/FakeFfiSyncServiceBuilder.kt @@ -15,5 +15,6 @@ import org.matrix.rustcomponents.sdk.SyncServiceBuilder class FakeFfiSyncServiceBuilder : SyncServiceBuilder(NoHandle) { override fun withOfflineMode(): SyncServiceBuilder = this override fun withSharePos(enable: Boolean): SyncServiceBuilder = this + override fun withProfilesExtension(): SyncServiceBuilder = this override suspend fun finish(): SyncService = FakeFfiSyncService() } diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/FakeContinuationMessageSender.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/FakeContinuationMessageSender.kt new file mode 100644 index 0000000000..d1544ec8bb --- /dev/null +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/FakeContinuationMessageSender.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl.linknewdevice + +import io.element.android.libraries.matrix.api.linknewdevice.ContinuationMessageSender +import io.element.android.tests.testutils.lambda.lambdaError +import io.element.android.tests.testutils.simulateLongTask + +class FakeContinuationMessageSender( + private val cancelResult: () -> Result = { lambdaError() }, + private val confirmResult: () -> Result = { lambdaError() }, +) : ContinuationMessageSender { + override suspend fun cancel(): Result = simulateLongTask { + cancelResult() + } + + override suspend fun confirm(): Result = simulateLongTask { + confirmResult() + } +} diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandlerTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandlerTest.kt index c0781972ac..8a0a046946 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandlerTest.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkDesktopHandlerTest.kt @@ -16,6 +16,8 @@ import io.element.android.libraries.matrix.api.linknewdevice.LinkDesktopStep import io.element.android.libraries.matrix.impl.fixtures.fakes.FakeFfiContinuationMessageSender import io.element.android.libraries.matrix.impl.fixtures.fakes.FakeFfiGrantLoginWithQrCodeHandler import io.element.android.libraries.matrix.test.QR_CODE_DATA +import io.element.android.tests.testutils.ExpectedResult +import io.element.android.tests.testutils.match import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch @@ -50,16 +52,18 @@ class RustLinkDesktopHandlerTest { runCurrent() // progress from the handler is mapped and emitted listOf( - GrantQrLoginProgress.Starting to LinkDesktopStep.Starting, - GrantQrLoginProgress.SyncingSecrets to LinkDesktopStep.SyncingSecrets, + GrantQrLoginProgress.Starting to ExpectedResult(LinkDesktopStep.Starting), + GrantQrLoginProgress.SyncingSecrets to ExpectedResult(LinkDesktopStep.SyncingSecrets), GrantQrLoginProgress.WaitingForAuth("aVerificationUri", FakeFfiContinuationMessageSender()) - to LinkDesktopStep.WaitingForAuth("aVerificationUri"), + to ExpectedResult( + resultClass = LinkDesktopStep.WaitingForAuth::class.java, + ), GrantQrLoginProgress.EstablishingSecureChannel(1.toUByte(), "1") - to LinkDesktopStep.EstablishingSecureChannel(1.toUByte(), "1"), - GrantQrLoginProgress.Done to LinkDesktopStep.Done, - ).forEach { (progress, expectedStep) -> + to ExpectedResult(LinkDesktopStep.EstablishingSecureChannel(1.toUByte(), "1")), + GrantQrLoginProgress.Done to ExpectedResult(LinkDesktopStep.Done), + ).forEach { (progress, expectedResult) -> handler.emitScanProgress(progress) - assertThat(awaitItem()).isEqualTo(expectedStep) + assertThat(awaitItem()).match(expectedResult) } // scan returns, no new event is emitted completable.complete(Unit) diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandlerTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandlerTest.kt index 8c0306c8ad..f1f568e3ca 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandlerTest.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/linknewdevice/RustLinkMobileHandlerTest.kt @@ -18,6 +18,8 @@ import io.element.android.libraries.matrix.impl.fixtures.fakes.FakeFfiContinuati import io.element.android.libraries.matrix.impl.fixtures.fakes.FakeFfiGrantLoginWithQrCodeHandler import io.element.android.libraries.matrix.impl.fixtures.fakes.FakeFfiQrCodeData import io.element.android.libraries.matrix.test.QR_CODE_DATA_RECIPROCATE +import io.element.android.tests.testutils.ExpectedResult +import io.element.android.tests.testutils.match import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch @@ -51,18 +53,18 @@ class RustLinkMobileHandlerTest { runCurrent() // progress from the handler is mapped and emitted listOf( - GrantGeneratedQrLoginProgress.Starting to LinkMobileStep.Starting::class.java, - GrantGeneratedQrLoginProgress.SyncingSecrets to LinkMobileStep.SyncingSecrets::class.java, + GrantGeneratedQrLoginProgress.Starting to ExpectedResult(LinkMobileStep.Starting), + GrantGeneratedQrLoginProgress.SyncingSecrets to ExpectedResult(LinkMobileStep.SyncingSecrets), GrantGeneratedQrLoginProgress.WaitingForAuth("aVerificationUri", FakeFfiContinuationMessageSender()) - to LinkMobileStep.WaitingForAuth::class.java, + to ExpectedResult(LinkMobileStep.WaitingForAuth::class.java), GrantGeneratedQrLoginProgress.QrScanned(FakeFfiCheckCodeSender()) - to LinkMobileStep.QrScanned::class.java, + to ExpectedResult(LinkMobileStep.QrScanned::class.java), GrantGeneratedQrLoginProgress.QrReady(FakeFfiQrCodeData(toBytesResult = { QR_CODE_DATA_RECIPROCATE })) - to LinkMobileStep.QrReady::class.java, - GrantGeneratedQrLoginProgress.Done to LinkMobileStep.Done::class.java, - ).forEach { (progress, expectedStepClass) -> + to ExpectedResult(LinkMobileStep.QrReady::class.java), + GrantGeneratedQrLoginProgress.Done to ExpectedResult(LinkMobileStep.Done), + ).forEach { (progress, expectedResult) -> handler.emitGenerateProgress(progress) - assertThat(awaitItem()).isInstanceOf(expectedStepClass) + assertThat(awaitItem()).match(expectedResult) } // generate returns, no new event is emitted completable.complete(Unit) diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/mapper/UserProfileMapperTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/mapper/UserProfileMapperTest.kt index 61e5886356..4ace520212 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/mapper/UserProfileMapperTest.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/mapper/UserProfileMapperTest.kt @@ -11,6 +11,7 @@ package io.element.android.libraries.matrix.impl.mapper import com.google.common.truth.Truth.assertThat import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.impl.fixtures.factories.aRustUserProfile +import io.element.android.libraries.matrix.impl.user.map import io.element.android.libraries.matrix.test.A_USER_ID import org.junit.Test diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/permalink/DefaultPermalinkParserTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/permalink/DefaultPermalinkParserTest.kt new file mode 100644 index 0000000000..416213a0b2 --- /dev/null +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/permalink/DefaultPermalinkParserTest.kt @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.impl.permalink + +import com.google.common.truth.Truth.assertThat +import io.element.android.libraries.matrix.api.core.UserId +import io.element.android.libraries.matrix.api.permalink.PermalinkData +import io.element.android.tests.testutils.robolectric.RobolectricTest +import org.junit.Test + +class DefaultPermalinkParserTest : RobolectricTest() { + @Test + fun `a matrix-to link to a user id with a slash is parsed as a user link`() { + val result = createParser().parse("https://matrix.to/#/@it/sme:matrix.org") + assertThat(result).isEqualTo(PermalinkData.UserLink(UserId("@it/sme:matrix.org"))) + } + + @Test + fun `an escaped slash in a user id is parsed as a user link`() { + val result = createParser().parse("https://matrix.to/#/@it%2Fsme:matrix.org") + assertThat(result).isEqualTo(PermalinkData.UserLink(UserId("@it/sme:matrix.org"))) + } + + @Test + fun `an element web link to a user id with a slash is parsed as a user link`() { + val result = createParser().parse("https://app.element.io/#/user/@it/sme:matrix.org") + assertThat(result).isEqualTo(PermalinkData.UserLink(UserId("@it/sme:matrix.org"))) + } + + @Test + fun `a user id with a slash that is not a valid user id is not a user link`() { + val result = createParser().parse("https://example.org/foo/@it/sme") + assertThat(result).isInstanceOf(PermalinkData.FallbackLink::class.java) + } + + private fun createParser() = DefaultPermalinkParser( + matrixToConverter = DefaultMatrixToConverter(), + ) +} diff --git a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/usersearch/UserSearchResultMapperTest.kt b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/usersearch/UserSearchResultMapperTest.kt index 3926b93d12..9134fdb6c7 100644 --- a/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/usersearch/UserSearchResultMapperTest.kt +++ b/libraries/matrix/impl/src/test/kotlin/io/element/android/libraries/matrix/impl/usersearch/UserSearchResultMapperTest.kt @@ -13,6 +13,7 @@ import io.element.android.libraries.matrix.api.user.MatrixSearchUserResults import io.element.android.libraries.matrix.api.user.MatrixUser import io.element.android.libraries.matrix.impl.fixtures.factories.aRustSearchUsersResults import io.element.android.libraries.matrix.impl.fixtures.factories.aRustUserProfile +import io.element.android.libraries.matrix.impl.user.UserSearchResultMapper import io.element.android.libraries.matrix.test.A_USER_ID import kotlinx.collections.immutable.toImmutableList import org.junit.Test diff --git a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeClientUrlContentFetcher.kt b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeClientUrlContentFetcher.kt new file mode 100644 index 0000000000..2018228985 --- /dev/null +++ b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeClientUrlContentFetcher.kt @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.test + +import io.element.android.libraries.matrix.api.ClientUrlContentFetcher +import io.element.android.tests.testutils.lambda.lambdaError + +class FakeClientUrlContentFetcher( + override val server: String = A_SERVER_NAME, + override val homeserverUrl: String = A_HOMESERVER_URL, + private val getUrlResult: (String) -> Result = { lambdaError() }, +) : ClientUrlContentFetcher { + override suspend fun getUrl(url: String): Result { + return getUrlResult(url) + } +} diff --git a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeMatrixClient.kt b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeMatrixClient.kt index cdf7cc85cf..6ba42270fe 100644 --- a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeMatrixClient.kt +++ b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeMatrixClient.kt @@ -79,6 +79,7 @@ class FakeMatrixClient( override val sessionId: SessionId = A_SESSION_ID, override val sessionPaths: SessionPaths = SessionPaths(fileDirectory = File("files"), cacheDirectory = File("cache")), override val deviceId: DeviceId = A_DEVICE_ID, + override val server: String = A_SERVER_NAME, override val homeserverUrl: String = A_HOMESERVER_URL, override val sessionCoroutineScope: CoroutineScope = TestScope(), private val userDisplayName: String? = A_USER_NAME, @@ -99,7 +100,7 @@ class FakeMatrixClient( override val roomMembershipObserver: RoomMembershipObserver = RoomMembershipObserver(), private val homeserverCapabilitiesProvider: FakeHomeserverCapabilitiesProvider = FakeHomeserverCapabilitiesProvider(), private val accountManagementUrlResult: (AccountManagementAction?) -> Result = { lambdaError() }, - private val resolveRoomAliasResult: (RoomAlias) -> Result> = { + private val resolveRoomAliasResult: suspend (RoomAlias) -> Result> = { Result.success( Optional.of(ResolvedRoomAlias(A_ROOM_ID, emptyList())) ) @@ -124,13 +125,16 @@ class FakeMatrixClient( private val getJoinedRoomIdsResult: () -> Result> = { Result.success(emptySet()) }, private val getRecentEmojisLambda: () -> Result> = { Result.success(emptyList()) }, private val addRecentEmojiLambda: (String) -> Result = { Result.success(Unit) }, + private val getAccountDataLambda: (String) -> Result = { lambdaError() }, + private val setAccountDataLambda: (String, String) -> Result = { _, _ -> lambdaError() }, private val markRoomAsFullyReadResult: (RoomId, EventId) -> Result = { _, _ -> lambdaError() }, private val markAllRoomsAsReadResult: () -> Result = { Result.success(Unit) }, private val performDatabaseVacuumLambda: () -> Result = { lambdaError() }, - private val getMapStyleUrlResult: () -> Result = { lambdaError() }, private val getDatabaseSizesLambda: () -> Result = { lambdaError() }, private val resetWellKnownConfigLambda: () -> Result = { lambdaError() }, + private val enableAutomaticCallStatusLambda: (Boolean) -> Unit = { }, override val contentScanner: ContentScanner? = null, + private val isShuttingDownResult: () -> Boolean = { false }, ) : MatrixClient { var setDisplayNameCalled: Boolean = false private set @@ -144,6 +148,8 @@ class FakeMatrixClient( private set var setUserStatusResult: Result = Result.success(Unit) var clearUserStatusResult: Result = Result.success(Unit) + var isUserStatusSupportedResult: Result = Result.success(true) + var isProfilesSlidingSyncExtensionSupportedResult: Result = Result.success(true) private val _userProfile: MutableStateFlow = MutableStateFlow(MatrixUser(sessionId, userDisplayName, userAvatarUrl)) override val userProfile: StateFlow = _userProfile @@ -288,6 +294,12 @@ class FakeMatrixClient( return clearUserStatusResult } + override suspend fun isUserStatusSupported(): Result = isUserStatusSupportedResult + + override suspend fun isProfilesSlidingSyncExtensionSupported(): Result = isProfilesSlidingSyncExtensionSupportedResult + + override fun enableAutomaticCallStatus(enabled: Boolean) = enableAutomaticCallStatusLambda(enabled) + override suspend fun joinRoom(roomId: RoomId): Result = joinRoomLambda(roomId) override suspend fun joinRoomByIdOrAlias(roomIdOrAlias: RoomIdOrAlias, serverNames: List): Result { @@ -298,6 +310,9 @@ class FakeMatrixClient( return knockRoomLambda(roomIdOrAlias, message, serverNames) } + override val isShuttingDown: Boolean + get() = isShuttingDownResult() + // Mocks fun givenCreateRoomResult(result: Result) { @@ -407,6 +422,14 @@ class FakeMatrixClient( return getRecentEmojisLambda() } + override suspend fun getAccountData(eventType: String): Result { + return getAccountDataLambda(eventType) + } + + override suspend fun setAccountData(eventType: String, content: String): Result { + return setAccountDataLambda(eventType, content) + } + override suspend fun markRoomAsFullyRead(roomId: RoomId, eventId: EventId): Result { return markRoomAsFullyReadResult(roomId, eventId) } @@ -419,10 +442,6 @@ class FakeMatrixClient( return performDatabaseVacuumLambda() } - override suspend fun getMapStyleUrl(): Result = simulateLongTask { - getMapStyleUrlResult() - } - override suspend fun canLinkNewDevice(): Result = simulateLongTask { return canLinkNewDeviceResult() } diff --git a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeTemporaryMatrixClient.kt b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeTemporaryMatrixClient.kt new file mode 100644 index 0000000000..3ee7fb5f2f --- /dev/null +++ b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeTemporaryMatrixClient.kt @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.test + +import io.element.android.libraries.matrix.api.TemporaryMatrixClient +import io.element.android.tests.testutils.lambda.lambdaError + +class FakeTemporaryMatrixClient( + override val server: String = A_SERVER_NAME, + override val homeserverUrl: String = A_HOMESERVER_URL, + private val getUrlResult: (String) -> Result = { lambdaError() }, + private val closeLambda: () -> Unit = {}, +) : TemporaryMatrixClient { + override suspend fun getUrl(url: String): Result = getUrlResult(url) + override fun close() = closeLambda() +} diff --git a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeTemporaryMatrixClientFactory.kt b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeTemporaryMatrixClientFactory.kt new file mode 100644 index 0000000000..e906777dcb --- /dev/null +++ b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/FakeTemporaryMatrixClientFactory.kt @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.test + +import io.element.android.libraries.matrix.api.TemporaryMatrixClient +import io.element.android.libraries.matrix.api.TemporaryMatrixClientFactory + +class FakeTemporaryMatrixClientFactory( + private val createResult: (String) -> Result = { Result.success(FakeTemporaryMatrixClient()) }, +) : TemporaryMatrixClientFactory { + override suspend fun create(serverName: String): Result = createResult(serverName) +} diff --git a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/TestData.kt b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/TestData.kt index c41ce0fe3e..c8f49eaf56 100644 --- a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/TestData.kt +++ b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/TestData.kt @@ -72,6 +72,7 @@ const val A_SPACE_NAME = "A space name" const val A_REDACTION_REASON = "A redaction reason" +const val A_SERVER_NAME = "matrix.org" const val A_HOMESERVER_URL = "matrix.org" const val A_HOMESERVER_URL_2 = "matrix-client.org" diff --git a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/auth/FakeMatrixAuthenticationService.kt b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/auth/FakeMatrixAuthenticationService.kt index 3b2fdeafb1..1eac6c0a1d 100644 --- a/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/auth/FakeMatrixAuthenticationService.kt +++ b/libraries/matrix/test/src/main/kotlin/io/element/android/libraries/matrix/test/auth/FakeMatrixAuthenticationService.kt @@ -70,10 +70,15 @@ class FakeMatrixAuthenticationService( return importCreatedSessionLambda(externalSession) } + /** The login hint passed to the most recent [getOAuthUrl] call. */ + var getOAuthUrlLoginHint: String? = null + private set + override suspend fun getOAuthUrl( prompt: OAuthPrompt, loginHint: String?, ): Result = simulateLongTask { + getOAuthUrlLoginHint = loginHint oAuthError?.let { Result.failure(it) } ?: Result.success(AN_OAUTH_DATA) } diff --git a/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/ImageLoaderHolder.kt b/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/ImageLoaderHolder.kt index 62b169744b..228fbd2cff 100644 --- a/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/ImageLoaderHolder.kt +++ b/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/ImageLoaderHolder.kt @@ -11,8 +11,24 @@ import coil3.ImageLoader import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.api.core.SessionId +/** + * Caches one Coil image loader per session, since loading Matrix media requires the session's own client to fetch and decrypt it. + */ interface ImageLoaderHolder { + /** Returns a loader that can only fetch ordinary URLs, for images that do not come from a Matrix room. */ fun get(): ImageLoader + + /** + * Returns the loader of a session, creating it on first use. + * + * @param client the session whose media the loader will fetch. + */ fun get(client: MatrixClient): ImageLoader + + /** + * Drops the cached loader of a session, to be called when that session goes away. + * + * @param sessionId the session whose loader is dropped. + */ fun remove(sessionId: SessionId) } diff --git a/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/InitialsAvatarBitmapGenerator.kt b/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/InitialsAvatarBitmapGenerator.kt index e6ff5d762d..f145383e87 100644 --- a/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/InitialsAvatarBitmapGenerator.kt +++ b/libraries/matrixmedia/api/src/main/kotlin/io/element/android/libraries/matrix/ui/media/InitialsAvatarBitmapGenerator.kt @@ -14,6 +14,15 @@ import io.element.android.libraries.designsystem.components.avatar.AvatarData * Generates a bitmap for an initials avatar based on the provided [io.element.android.libraries.designsystem.components.avatar.AvatarData]. */ interface InitialsAvatarBitmapGenerator { + /** + * Draws the initials avatar, used where a bitmap is required rather than a Composable, such as in notifications and shortcuts. + * + * @param size the width and height of the bitmap in pixels. + * @param avatarData the name and id the initials and the background colour are derived from. + * @param useDarkTheme whether to draw the dark theme variant. + * @param fontSizePercentage the text height as a fraction of [size]. + * @return the bitmap, or `null` when it could not be drawn. + */ fun generateBitmap( size: Int, avatarData: AvatarData, diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnail.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnail.kt index ebc8790a8a..38c5732875 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnail.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnail.kt @@ -132,7 +132,7 @@ data class AttachmentThumbnailInfo( @PreviewsDayNight @Composable -internal fun AttachmentThumbnailPreview(@PreviewParameter(AttachmentThumbnailInfoProvider::class) data: AttachmentThumbnailInfo) = ElementPreview { +internal fun AttachmentThumbnailPreview(@PreviewParameter(AttachmentThumbnailInfoPreviewParam::class) data: AttachmentThumbnailInfo) = ElementPreview { AttachmentThumbnail( info = data, modifier = Modifier diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnailInfoProvider.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnailInfoPreviewParam.kt similarity index 94% rename from libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnailInfoProvider.kt rename to libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnailInfoPreviewParam.kt index ea38a979ae..1509ac2144 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnailInfoProvider.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/AttachmentThumbnailInfoPreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.libraries.matrix.ui.components import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.matrix.api.media.MediaSource -open class AttachmentThumbnailInfoProvider : PreviewParameterProvider { +open class AttachmentThumbnailInfoPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAttachmentThumbnailInfo(type = AttachmentThumbnailType.Image), diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/CreateDmConfirmationBottomSheet.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/CreateDmConfirmationBottomSheet.kt index 598d7f2ca7..45835ed479 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/CreateDmConfirmationBottomSheet.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/CreateDmConfirmationBottomSheet.kt @@ -158,7 +158,7 @@ fun CreateDmConfirmationBottomSheet( @Composable internal fun CreateDmConfirmationBottomSheetPreview( @PreviewParameter( - CreateDmConfirmationBottomSheetStateProvider::class + CreateDmConfirmationBottomSheetStatePreviewParam::class ) state: CreateDmConfirmationBottomSheetState ) = ElementPreview(fillMaxSize = true) { CreateDmConfirmationBottomSheet( @@ -174,7 +174,7 @@ data class CreateDmConfirmationBottomSheetState( val isUserIdentityUnknown: Boolean, ) -class CreateDmConfirmationBottomSheetStateProvider : PreviewParameterProvider { +class CreateDmConfirmationBottomSheetStatePreviewParam : PreviewParameterProvider { override val values = sequenceOf( CreateDmConfirmationBottomSheetState(matrixUser = aMatrixUser(), isUserIdentityUnknown = false), CreateDmConfirmationBottomSheetState(matrixUser = aMatrixUser(), isUserIdentityUnknown = true), diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserHeader.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserHeader.kt index 89b0532580..188a8bc1a4 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserHeader.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserHeader.kt @@ -79,6 +79,6 @@ fun MatrixUserHeader( @PreviewsDayNight @Composable -internal fun MatrixUserHeaderPreview(@PreviewParameter(MatrixUserProvider::class) matrixUser: MatrixUser) = ElementPreview { +internal fun MatrixUserHeaderPreview(@PreviewParameter(MatrixUserPreviewParam::class) matrixUser: MatrixUser) = ElementPreview { MatrixUserHeader(matrixUser) } diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserProvider.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserPreviewParam.kt similarity index 94% rename from libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserProvider.kt rename to libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserPreviewParam.kt index 7bc7d00f09..034570310e 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserProvider.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserPreviewParam.kt @@ -24,7 +24,7 @@ import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.user.DisplayedStatus import io.element.android.libraries.matrix.api.user.MatrixUser -open class MatrixUserProvider : PreviewParameterProvider { +open class MatrixUserPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMatrixUser(), @@ -33,7 +33,7 @@ open class MatrixUserProvider : PreviewParameterProvider { ) } -open class MatrixUserWithAvatarProvider : PreviewParameterProvider { +open class MatrixUserWithAvatarPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMatrixUser(displayName = USER_NAME_JOHN_DOE), diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserRow.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserRow.kt index 9fc7ea7b4a..2a202486a3 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserRow.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/MatrixUserRow.kt @@ -46,6 +46,6 @@ fun MatrixUserRow( @PreviewsDayNight @Composable -internal fun MatrixUserRowPreview(@PreviewParameter(MatrixUserProvider::class) matrixUser: MatrixUser) = ElementPreview { +internal fun MatrixUserRowPreview(@PreviewParameter(MatrixUserPreviewParam::class) matrixUser: MatrixUser) = ElementPreview { MatrixUserRow(matrixUser) } diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectRoomInfoProvider.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectRoomInfoPreviewParam.kt similarity index 92% rename from libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectRoomInfoProvider.kt rename to libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectRoomInfoPreviewParam.kt index 731d499445..e205bac1dd 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectRoomInfoProvider.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectRoomInfoPreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.matrix.ui.model.SelectRoomInfo import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -class SelectRoomInfoProvider : PreviewParameterProvider { +class SelectRoomInfoPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aSelectRoomInfo(roomId = RoomId("!room1:domain")), @@ -31,6 +31,7 @@ fun aSelectRoomInfo( canonicalAlias: RoomAlias? = null, avatarUrl: String? = null, heroes: ImmutableList = persistentListOf(), + isDm: Boolean = false, isTombstoned: Boolean = false, ) = SelectRoomInfo( roomId = roomId, @@ -38,5 +39,6 @@ fun aSelectRoomInfo( canonicalAlias = canonicalAlias, avatarUrl = avatarUrl, heroes = heroes, + isDm = isDm, isTombstoned = isTombstoned, ) diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedRoom.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedRoom.kt index b7484903da..9ebaa5b22c 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedRoom.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedRoom.kt @@ -51,7 +51,7 @@ fun SelectedRoom( @PreviewsDayNight @Composable internal fun SelectedRoomPreview( - @PreviewParameter(SelectRoomInfoProvider::class) roomInfo: SelectRoomInfo + @PreviewParameter(SelectRoomInfoPreviewParam::class) roomInfo: SelectRoomInfo ) = ElementPreview { SelectedRoom( roomInfo = roomInfo, @@ -62,7 +62,7 @@ internal fun SelectedRoomPreview( @PreviewsDayNight @Composable internal fun SelectedRoomRtlPreview( - @PreviewParameter(SelectRoomInfoProvider::class) roomInfo: SelectRoomInfo + @PreviewParameter(SelectRoomInfoPreviewParam::class) roomInfo: SelectRoomInfo ) = CompositionLocalProvider( LocalLayoutDirection provides LayoutDirection.Rtl, ) { diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedUser.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedUser.kt index 17ec7c6ec7..ce8c047cef 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedUser.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SelectedUser.kt @@ -44,7 +44,7 @@ fun SelectedUser( @PreviewsDayNight @Composable -internal fun SelectedUserPreview(@PreviewParameter(MatrixUserWithAvatarProvider::class) user: MatrixUser) = ElementPreview { +internal fun SelectedUserPreview(@PreviewParameter(MatrixUserWithAvatarPreviewParam::class) user: MatrixUser) = ElementPreview { SelectedUser( matrixUser = user, canRemove = true, diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomItemView.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomItemView.kt index d3824f9eec..d10698662f 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomItemView.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomItemView.kt @@ -210,7 +210,7 @@ private fun SpaceRoomItemScaffold( @Composable @PreviewsDayNight -internal fun SpaceRoomItemViewPreview(@PreviewParameter(SpaceRoomProvider::class) spaceRoom: SpaceRoom) = ElementPreview { +internal fun SpaceRoomItemViewPreview(@PreviewParameter(SpaceRoomPreviewParam::class) spaceRoom: SpaceRoom) = ElementPreview { SpaceRoomItemView( spaceRoom = spaceRoom, showUnreadIndicator = spaceRoom.state == CurrentUserMembership.INVITED, diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomProvider.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomPreviewParam.kt similarity index 97% rename from libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomProvider.kt rename to libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomPreviewParam.kt index d6a582d83c..0eddafd9da 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomProvider.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/components/SpaceRoomPreviewParam.kt @@ -17,7 +17,7 @@ import io.element.android.libraries.matrix.api.room.RoomType import io.element.android.libraries.matrix.api.spaces.SpaceRoom import io.element.android.libraries.previewutils.room.aSpaceRoom -class SpaceRoomProvider : PreviewParameterProvider { +class SpaceRoomPreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( aSpaceRoom( roomType = RoomType.Room, diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/media/contentvalidation/ContentErrorView.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/media/contentvalidation/ContentErrorView.kt index 24f4a15200..52d81ae895 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/media/contentvalidation/ContentErrorView.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/media/contentvalidation/ContentErrorView.kt @@ -27,7 +27,7 @@ import io.element.android.compound.tokens.generated.CompoundIcons @Composable internal fun ContentErrorView( title: String, - message: String, + message: String?, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues.Zero, onTextLayout: ((TextLayoutResult) -> Unit)? = null, @@ -51,12 +51,14 @@ internal fun ContentErrorView( color = ElementTheme.colors.textCriticalPrimary, style = ElementTheme.typography.fontBodyMdMedium, ) - Text( - text = message, - color = ElementTheme.colors.textSecondary, - style = ElementTheme.typography.fontBodySmRegular, - onTextLayout = onTextLayout, - ) + if (message != null) { + Text( + text = message, + color = ElementTheme.colors.textSecondary, + style = ElementTheme.typography.fontBodySmRegular, + onTextLayout = onTextLayout, + ) + } } } } diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToDetailsProvider.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToDetailsPreviewParam.kt similarity index 93% rename from libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToDetailsProvider.kt rename to libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToDetailsPreviewParam.kt index b335ef9609..1b48e0eb9b 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToDetailsProvider.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToDetailsPreviewParam.kt @@ -32,10 +32,11 @@ import io.element.android.libraries.matrix.api.timeline.item.event.TextMessageTy import io.element.android.libraries.matrix.api.timeline.item.event.UnableToDecryptContent import io.element.android.libraries.matrix.api.timeline.item.event.VideoMessageType import io.element.android.libraries.matrix.api.timeline.item.event.VoiceMessageType +import io.element.android.libraries.matrix.api.user.DisplayedStatus import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentMapOf -open class InReplyToDetailsProvider : PreviewParameterProvider { +open class InReplyToDetailsPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMessageContent( @@ -99,7 +100,7 @@ open class InReplyToDetailsProvider : PreviewParameterProvider } } -class InReplyToDetailsDisambiguatedProvider : InReplyToDetailsProvider() { +class InReplyToDetailsDisambiguatedPreviewParam : InReplyToDetailsPreviewParam() { override val values: Sequence get() = sequenceOf( aMessageContent( @@ -114,7 +115,7 @@ class InReplyToDetailsDisambiguatedProvider : InReplyToDetailsProvider() { } } -class InReplyToDetailsInformativeProvider : InReplyToDetailsProvider() { +class InReplyToDetailsInformativePreviewParam : InReplyToDetailsPreviewParam() { override val values: Sequence get() = sequenceOf( RedactedContent, @@ -126,7 +127,7 @@ class InReplyToDetailsInformativeProvider : InReplyToDetailsProvider() { } } -class InReplyToDetailsOtherProvider : InReplyToDetailsProvider() { +class InReplyToDetailsOtherPreviewParam : InReplyToDetailsPreviewParam() { override val values: Sequence get() = sequenceOf( InReplyToDetails.Loading(eventId = EventId("\$anEventId")), @@ -163,9 +164,10 @@ fun aProfileDetailsReady( displayName: String? = USER_NAME_SENDER, displayNameAmbiguous: Boolean = false, avatarUrl: String? = null, + displayedStatus: DisplayedStatus? = null ) = ProfileDetails.Ready( displayName = displayName, displayNameAmbiguous = displayNameAmbiguous, avatarUrl = avatarUrl, - displayedStatus = null, + displayedStatus = displayedStatus, ) diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToView.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToView.kt index 3072c81a15..8cdc3ae24c 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToView.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/reply/InReplyToView.kt @@ -19,7 +19,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -45,6 +44,7 @@ import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.timeline.item.event.ProfileDetails import io.element.android.libraries.matrix.api.timeline.item.event.getDisambiguatedDisplayName import io.element.android.libraries.matrix.ui.components.AttachmentThumbnail +import io.element.android.libraries.matrix.ui.media.contentvalidation.ContentErrorView import io.element.android.libraries.matrix.ui.media.contentvalidation.ContentValidationValue import io.element.android.libraries.matrix.ui.media.contentvalidation.InvalidContentView import io.element.android.libraries.matrix.ui.media.contentvalidation.NotFoundContentView @@ -77,7 +77,7 @@ fun InReplyToView( else -> ReplyToLoadingContent(modifier = modifier) } is InReplyToDetails.Error -> - ReplyToErrorContent(data = inReplyTo, maxLines = maxLines, modifier = modifier) + ReplyToErrorContent(modifier = modifier) is InReplyToDetails.Loading -> ReplyToLoadingContent(modifier = modifier) } @@ -150,24 +150,15 @@ private fun ReplyToLoadingContent( @Composable private fun ReplyToErrorContent( - data: InReplyToDetails.Error, - maxLines: Int, modifier: Modifier = Modifier, ) { - val paddings = PaddingValues(horizontal = 12.dp, vertical = 4.dp) - Row( - modifier - .background(ElementTheme.colors.bgCanvasDefault) - .padding(paddings) - ) { - Text( - text = data.message, - style = ElementTheme.typography.fontBodyMdRegular, - color = ElementTheme.colors.textCriticalPrimary, - maxLines = maxLines, - overflow = TextOverflow.Ellipsis, - ) - } + ContentErrorView( + title = stringResource(CommonStrings.error_message_not_found), + message = null, + modifier = modifier, + contentPadding = PaddingValues(vertical = 4.dp, horizontal = 8.dp), + onTextLayout = null, + ) } @Composable @@ -245,7 +236,7 @@ private fun ReplyToNotFoundContent( @PreviewsDayNight @Composable -internal fun InReplyToViewPreview(@PreviewParameter(provider = InReplyToDetailsProvider::class) inReplyTo: InReplyToDetails) = ElementPreview { +internal fun InReplyToViewPreview(@PreviewParameter(provider = InReplyToDetailsPreviewParam::class) inReplyTo: InReplyToDetails) = ElementPreview { InReplyToView( inReplyTo = inReplyTo, hideImage = false, diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderName.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderName.kt index 42432c6950..7cd066d0ce 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderName.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderName.kt @@ -9,12 +9,15 @@ package io.element.android.libraries.matrix.ui.messages.sender import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp @@ -24,7 +27,7 @@ import io.element.android.libraries.designsystem.preview.PreviewsDayNight import io.element.android.libraries.designsystem.theme.components.Text import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.timeline.item.event.ProfileDetails -import io.element.android.libraries.matrix.ui.model.toText +import io.element.android.libraries.matrix.ui.model.toEmojiText // https://www.figma.com/file/Ni6Ii8YKtmXCKYNE90cC67/Timeline-(new)?type=design&node-id=917-80169&mode=design&t=A0CJCBbMqR8NOwUQ-0 @Composable @@ -61,7 +64,7 @@ fun SenderName( modifier = Modifier .clipToBounds() .alignByBaseline(), - text = userStatus.toText(), + text = userStatus.toEmojiText(), style = ElementTheme.typography.fontBodyMdMedium, color = ElementTheme.colors.textSecondary, maxLines = 1, @@ -134,11 +137,29 @@ private fun RowScope.SecondaryText( @PreviewsDayNight @Composable internal fun SenderNamePreview( - @PreviewParameter(SenderNameDataProvider::class) senderNameData: SenderNameData, + @PreviewParameter(SenderNameDataPreviewParam::class) senderNameData: SenderNameData, ) = ElementPreview { - SenderName( - senderId = senderNameData.userId, - senderProfile = senderNameData.profileDetails, - senderNameMode = senderNameData.senderNameMode, - ) + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + sequenceOf( + SenderNameMode.Timeline(mainColor = Color.Red), + SenderNameMode.Reply, + SenderNameMode.ActionList, + ).forEach { mode -> + Column { + Text( + "Rendering in mode ${mode::class.simpleName}:", + style = ElementTheme.typography.fontBodyXsRegular, + color = ElementTheme.colors.textSecondary, + ) + SenderName( + senderId = senderNameData.userId, + senderProfile = senderNameData.profileDetails, + senderNameMode = mode, + ) + } + } + } } diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderNameDataPreviewParam.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderNameDataPreviewParam.kt new file mode 100644 index 0000000000..103cb6a4f0 --- /dev/null +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderNameDataPreviewParam.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Element Creations Ltd. + * Copyright 2024, 2025 New Vector Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.matrix.ui.messages.sender + +import androidx.compose.ui.tooling.preview.PreviewParameterProvider +import io.element.android.libraries.matrix.api.core.UserId +import io.element.android.libraries.matrix.api.timeline.item.event.ProfileDetails +import io.element.android.libraries.matrix.api.user.DisplayedStatus +import io.element.android.libraries.matrix.api.user.UserStatus +import io.element.android.libraries.matrix.ui.messages.reply.aProfileDetailsReady + +data class SenderNameData( + val userId: UserId, + val profileDetails: ProfileDetails, +) + +open class SenderNameDataPreviewParam : PreviewParameterProvider { + override val values: Sequence + get() = sequenceOf( + aSenderNameData(), + aSenderNameData( + displayNameAmbiguous = true, + ), + aSenderNameData( + profileDetails = ProfileDetails.Unavailable, + ), + aSenderNameData( + displayName = null, + ), + aSenderNameData( + displayedStatus = DisplayedStatus.UserSet( + status = UserStatus( + emoji = "😀", + text = "Should not be rendered", + ), + ), + ), + aSenderNameData( + displayedStatus = DisplayedStatus.InCall(0L), + ), + aSenderNameData( + displayNameAmbiguous = true, + displayedStatus = DisplayedStatus.UserSet( + status = UserStatus( + emoji = "😀", + text = "Should not be rendered", + ), + ), + ), + ) +} + +private fun aSenderNameData( + userId: UserId = UserId("@alice:example.com"), + displayName: String? = "Alice", + displayNameAmbiguous: Boolean = false, + displayedStatus: DisplayedStatus? = null, + profileDetails: ProfileDetails = aProfileDetailsReady( + displayName = displayName, + displayNameAmbiguous = displayNameAmbiguous, + displayedStatus = displayedStatus, + ) +) = SenderNameData( + userId = userId, + profileDetails = profileDetails, +) diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderNameDataProvider.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderNameDataProvider.kt deleted file mode 100644 index e4ca73e69c..0000000000 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/messages/sender/SenderNameDataProvider.kt +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2025 Element Creations Ltd. - * Copyright 2024, 2025 New Vector Ltd. - * - * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. - * Please see LICENSE files in the repository root for full details. - */ - -package io.element.android.libraries.matrix.ui.messages.sender - -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import io.element.android.libraries.matrix.api.core.UserId -import io.element.android.libraries.matrix.api.timeline.item.event.ProfileDetails -import io.element.android.libraries.matrix.api.user.DisplayedStatus - -data class SenderNameData( - val userId: UserId, - val profileDetails: ProfileDetails, - val senderNameMode: SenderNameMode, -) - -open class SenderNameDataProvider : PreviewParameterProvider { - override val values: Sequence - get() = sequenceOf( - SenderNameMode.Timeline(mainColor = Color.Red), - SenderNameMode.Reply, - SenderNameMode.ActionList, - ) - .flatMap { senderNameMode -> - sequenceOf( - aSenderNameData( - senderNameMode = senderNameMode, - ), - aSenderNameData( - senderNameMode = senderNameMode, - displayNameAmbiguous = true, - ), - SenderNameData( - senderNameMode = senderNameMode, - userId = UserId("@alice:${senderNameMode.javaClass.simpleName.lowercase()}"), - profileDetails = ProfileDetails.Unavailable, - ), - ) - } -} - -private fun aSenderNameData( - senderNameMode: SenderNameMode, - displayNameAmbiguous: Boolean = false, - displayedStatus: DisplayedStatus? = null, -) = SenderNameData( - userId = UserId("@alice:${senderNameMode.javaClass.simpleName.lowercase()}"), - profileDetails = ProfileDetails.Ready( - displayName = "Alice ${senderNameMode.javaClass.simpleName}", - displayNameAmbiguous = displayNameAmbiguous, - avatarUrl = null, - displayedStatus = displayedStatus, - ), - senderNameMode = senderNameMode, -) diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/model/SelectRoomInfo.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/model/SelectRoomInfo.kt index d6981f62fd..fd13140e54 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/model/SelectRoomInfo.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/model/SelectRoomInfo.kt @@ -23,6 +23,7 @@ data class SelectRoomInfo( val canonicalAlias: RoomAlias?, val avatarUrl: String?, val heroes: ImmutableList, + val isDm: Boolean, val isTombstoned: Boolean, ) { fun getAvatarData(size: AvatarSize) = AvatarData( @@ -41,5 +42,6 @@ fun RoomInfo.toSelectRoomInfo() = SelectRoomInfo( avatarUrl = avatarUrl, heroes = heroes, canonicalAlias = canonicalAlias, + isDm = isDm, isTombstoned = successorRoom != null, ) diff --git a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/room/LoadingRoomState.kt b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/room/LoadingRoomState.kt index cbbe79b480..cdd1475641 100644 --- a/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/room/LoadingRoomState.kt +++ b/libraries/matrixui/src/main/kotlin/io/element/android/libraries/matrix/ui/room/LoadingRoomState.kt @@ -30,7 +30,7 @@ sealed interface LoadingRoomState { data class Loaded(val room: JoinedRoom) : LoadingRoomState } -open class LoadingRoomStateProvider : PreviewParameterProvider { +open class LoadingRoomStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( LoadingRoomState.Loading, diff --git a/libraries/matrixui/src/main/res/values-ar/translations.xml b/libraries/matrixui/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..5417a5e89f --- /dev/null +++ b/libraries/matrixui/src/main/res/values-ar/translations.xml @@ -0,0 +1,9 @@ + + + "إرسال دعوة" + "هل تريد بدء دردشة مع %1$s؟" + "إرسال دعوة؟" + "ليست لديك حاليًا أي دردشات مع هذا الشخص. أكّد دعوته قبل المتابعة." + "هل تريد بدء دردشة مع جهة الاتصال الجديدة هذه؟" + "دعاك %1$s (%2$s)" + diff --git a/libraries/matrixui/src/main/res/values-de/translations.xml b/libraries/matrixui/src/main/res/values-de/translations.xml index d779c15659..816989ed76 100644 --- a/libraries/matrixui/src/main/res/values-de/translations.xml +++ b/libraries/matrixui/src/main/res/values-de/translations.xml @@ -3,5 +3,7 @@ "Einladung senden" "Möchtest du einen Chat mit %1$s starten?" "Einladung senden?" + "Du hast derzeit keine Chats mit dieser Person. Bestätige die Einladung, bevor du fortfährst." + "Mit diesem neuen Kontakt einen Chat starten?" "%1$s (%2$s) hat dich eingeladen" diff --git a/libraries/matrixui/src/main/res/values-es/translations.xml b/libraries/matrixui/src/main/res/values-es/translations.xml index 5d4ac4cf43..26e15d9b2e 100644 --- a/libraries/matrixui/src/main/res/values-es/translations.xml +++ b/libraries/matrixui/src/main/res/values-es/translations.xml @@ -3,5 +3,7 @@ "Enviar invitación" "¿Quieres iniciar un chat con %1$s?" "¿Enviar invitación?" + "De momento no tienes ningún chat con esta persona. Confirma que quieres invitarla antes de continuar." + "¿Iniciar un chat con este nuevo contacto?" "%1$s (%2$s) te invitó" diff --git a/libraries/matrixui/src/main/res/values-fa/translations.xml b/libraries/matrixui/src/main/res/values-fa/translations.xml index 3f5d32f974..9dfece23b2 100644 --- a/libraries/matrixui/src/main/res/values-fa/translations.xml +++ b/libraries/matrixui/src/main/res/values-fa/translations.xml @@ -3,5 +3,7 @@ "فرستادن دعوت" "می‌خواهید گپی را با %1$s بیاغازید؟" "فرستادن دعوت؟" + "شما در حال حاضر هیچ گفت‌وگویی با این شخص ندارید. قبل از ادامه، دعوت از او را تأیید کنید." + "با این مخاطب جدید گفت‌وگو را شروع کنید؟" "%1$s (%2$s) دعوتتان کرد" diff --git a/libraries/mediapickers/api/src/main/kotlin/io/element/android/libraries/mediapickers/api/PickerProvider.kt b/libraries/mediapickers/api/src/main/kotlin/io/element/android/libraries/mediapickers/api/PickerProvider.kt index 1bab693609..185b2f58a0 100644 --- a/libraries/mediapickers/api/src/main/kotlin/io/element/android/libraries/mediapickers/api/PickerProvider.kt +++ b/libraries/mediapickers/api/src/main/kotlin/io/element/android/libraries/mediapickers/api/PickerProvider.kt @@ -12,37 +12,79 @@ import android.net.Uri import androidx.activity.result.PickVisualMediaRequest import androidx.compose.runtime.Composable +/** + * Registers the system media and file pickers from Composable code, returning launchers the UI can trigger later. + * + * Every method must be called during composition, not from a click handler; a cancelled pick reports a `null` uri or an empty list. + */ interface PickerProvider { + /** + * Registers a picker for a single photo or video from the gallery. + * + * @param onResult called with the picked media and its MIME type, both `null` when the user cancelled. + */ @Composable fun registerGalleryPicker( onResult: (uri: Uri?, mimeType: String?) -> Unit ): PickerLauncher + /** + * Registers a picker restricted to a single image, used where a video would not be valid, such as for an avatar. + * + * @param onResult called with the picked image, `null` when the user cancelled. + */ @Composable fun registerGalleryImagePicker( onResult: (Uri?) -> Unit ): PickerLauncher + /** + * Registers a picker for several photos or videos at once. + * + * @param onResult called with the picked media, empty when the user cancelled. + */ @Composable fun registerGalleryMultiPicker( onResult: (uris: List) -> Unit ): PickerLauncher> + /** + * Registers a picker for a single file of any kind. + * + * @param mimeType the MIME type to filter on, `*` / `*` to accept anything. + * @param onResult called with the picked file and its MIME type, both `null` when the user cancelled. + */ @Composable fun registerFilePicker( mimeType: String, onResult: (uri: Uri?, mimeType: String?) -> Unit, ): PickerLauncher + /** + * Registers a picker for several files at once. + * + * @param mimeType the MIME type to filter on. + * @param onResult called with the picked files, empty when the user cancelled. + */ @Composable fun registerFileMultiPicker( mimeType: String, onResult: (uris: List) -> Unit, ): PickerLauncher, List> + /** + * Registers a launcher that opens the camera to take a photo. + * + * @param onResult called with the captured photo, `null` when the user cancelled or the capture failed. + */ @Composable fun registerCameraPhotoPicker(onResult: (Uri?) -> Unit): PickerLauncher + /** + * Registers a launcher that opens the camera to record a video. + * + * @param onResult called with the recorded video, `null` when the user cancelled or the capture failed. + */ @Composable fun registerCameraVideoPicker(onResult: (Uri?) -> Unit): PickerLauncher } diff --git a/libraries/mediaplayer/impl/src/main/kotlin/io/element/android/libraries/mediaplayer/impl/SimplePlayer.kt b/libraries/mediaplayer/impl/src/main/kotlin/io/element/android/libraries/mediaplayer/impl/SimplePlayer.kt index 17bfe682e3..9bec86e72f 100644 --- a/libraries/mediaplayer/impl/src/main/kotlin/io/element/android/libraries/mediaplayer/impl/SimplePlayer.kt +++ b/libraries/mediaplayer/impl/src/main/kotlin/io/element/android/libraries/mediaplayer/impl/SimplePlayer.kt @@ -8,15 +8,8 @@ package io.element.android.libraries.mediaplayer.impl -import android.content.Context import androidx.media3.common.MediaItem import androidx.media3.common.Player -import androidx.media3.exoplayer.ExoPlayer -import dev.zacsweers.metro.BindingContainer -import dev.zacsweers.metro.ContributesTo -import dev.zacsweers.metro.Provides -import io.element.android.libraries.di.RoomScope -import io.element.android.libraries.di.annotations.ApplicationContext /** * A subset of media3 [Player] that only exposes the few methods we need making it easier to mock. @@ -43,15 +36,6 @@ interface SimplePlayer { } } -@ContributesTo(RoomScope::class) -@BindingContainer -object SimplePlayerModule { - @Provides - fun simplePlayerProvider( - @ApplicationContext context: Context, - ): SimplePlayer = DefaultSimplePlayer(ExoPlayer.Builder(context).build()) -} - /** * Default implementation of [SimplePlayer] backed by a media3 [Player]. */ diff --git a/libraries/mediaplayer/impl/src/main/kotlin/io/element/android/libraries/mediaplayer/impl/di/SimplePlayerBindingContainer.kt b/libraries/mediaplayer/impl/src/main/kotlin/io/element/android/libraries/mediaplayer/impl/di/SimplePlayerBindingContainer.kt new file mode 100644 index 0000000000..85518e58fd --- /dev/null +++ b/libraries/mediaplayer/impl/src/main/kotlin/io/element/android/libraries/mediaplayer/impl/di/SimplePlayerBindingContainer.kt @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.mediaplayer.impl.di + +import android.content.Context +import androidx.media3.common.C +import androidx.media3.exoplayer.ExoPlayer +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides +import io.element.android.libraries.di.RoomScope +import io.element.android.libraries.di.annotations.ApplicationContext +import io.element.android.libraries.mediaplayer.impl.DefaultSimplePlayer +import io.element.android.libraries.mediaplayer.impl.SimplePlayer + +@ContributesTo(RoomScope::class) +@BindingContainer +object SimplePlayerBindingContainer { + @Provides + fun providesSimplePlayer( + @ApplicationContext context: Context, + ): SimplePlayer = DefaultSimplePlayer(ExoPlayer.Builder(context).setWakeMode(C.WAKE_MODE_LOCAL).build()) +} diff --git a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MaxUploadSizeProvider.kt b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MaxUploadSizeProvider.kt index a5462a6caf..e6b9c7f026 100644 --- a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MaxUploadSizeProvider.kt +++ b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MaxUploadSizeProvider.kt @@ -12,5 +12,6 @@ package io.element.android.libraries.mediaupload.api * Provides the maximum upload size allowed by the Matrix server. */ fun interface MaxUploadSizeProvider { + /** Returns the maximum size in bytes a single upload may have, as advertised by the homeserver. */ suspend fun getMaxUploadSize(): Result } diff --git a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaOptimizationConfigProvider.kt b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaOptimizationConfigProvider.kt index 976a7057f2..60dbf353eb 100644 --- a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaOptimizationConfigProvider.kt +++ b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaOptimizationConfigProvider.kt @@ -8,6 +8,10 @@ package io.element.android.libraries.mediaupload.api +/** + * Resolves how aggressively media should be compressed, combining the user's own preferences with the app defaults. + */ fun interface MediaOptimizationConfigProvider { + /** Returns the configuration to pass to the pre-processing and sending calls. */ suspend fun get(): MediaOptimizationConfig } diff --git a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaPreProcessor.kt b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaPreProcessor.kt index c2bf1e5f5d..a51ebc17b9 100644 --- a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaPreProcessor.kt +++ b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaPreProcessor.kt @@ -10,10 +10,18 @@ package io.element.android.libraries.mediaupload.api import android.net.Uri +/** + * Prepares a media file for upload: resizing, transcoding and stripping metadata that would leak information about the sender. + */ interface MediaPreProcessor { /** * Given a [uri] and [mimeType], pre-processes the media before it's uploaded, resizing, transcoding, and removing sensitive info from its metadata. * If [deleteOriginal] is `true`, the file reference by the [uri] will be automatically deleted too when this process finishes. + * + * @param uri the media to process. + * @param mimeType the MIME type of that media. + * @param deleteOriginal whether to delete the source file once processing is done. + * @param mediaOptimizationConfig how aggressively the media should be compressed. * @return a [Result] with the [MediaUploadInfo] containing all the info needed to begin the upload. */ suspend fun process( diff --git a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaSender.kt b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaSender.kt index 6cca73935e..808575f9e6 100644 --- a/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaSender.kt +++ b/libraries/mediaupload/api/src/main/kotlin/io/element/android/libraries/mediaupload/api/MediaSender.kt @@ -13,31 +13,62 @@ import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.room.JoinedRoom import io.element.android.libraries.matrix.api.timeline.Timeline +/** + * Creates a [MediaSender] for the room of the current room scope; see [MediaSenderRoomFactory] when the room is not in scope. + */ fun interface MediaSenderFactory { /** * Create a [MediaSender] for the given [Timeline.Mode], in the Room Scope. + * + * @param timelineMode the timeline the media should be sent to, which matters for threads in particular. */ fun create( timelineMode: Timeline.Mode, ): MediaSender } +/** + * Creates a [MediaSender] for an explicitly given room, used outside the room scope, for instance when sharing into a room. + */ fun interface MediaSenderRoomFactory { /** * Create a [MediaSender] for the given [JoinedRoom], with timeline mode Live. + * + * @param room the room the media should be sent to. */ fun create( room: JoinedRoom, ): MediaSender } +/** + * Sends media to a room, taking care of the pre-processing the timeline API does not do: resizing, transcoding and stripping metadata. + * + * Sending is a two-step process, and the steps can be used separately so the UI can show a preview between them. + * The temporary files produced by pre-processing are only released by [cleanUp]. + */ interface MediaSender { + /** + * Resizes, transcodes and strips the metadata of a media file without sending anything yet. + * + * @param uri the media picked by the user. + * @param mimeType the MIME type of that media. + * @param mediaOptimizationConfig how aggressively the media should be compressed. + */ suspend fun preProcessMedia( uri: Uri, mimeType: String, mediaOptimizationConfig: MediaOptimizationConfig, ): Result + /** + * Sends media that has already gone through [preProcessMedia]. + * + * @param mediaUploadInfo the result of the pre-processing step. + * @param caption the text shown along with the media, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendPreProcessedMedia( mediaUploadInfo: MediaUploadInfo, caption: String?, @@ -45,6 +76,16 @@ interface MediaSender { inReplyToEventId: EventId?, ): Result + /** + * Pre-processes and sends a media file in one go, suspending until the upload finishes. + * + * @param uri the media picked by the user. + * @param mimeType the MIME type of that media. + * @param caption the text shown along with the media, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + * @param mediaOptimizationConfig how aggressively the media should be compressed. + */ suspend fun sendMedia( uri: Uri, mimeType: String, @@ -54,6 +95,14 @@ interface MediaSender { mediaOptimizationConfig: MediaOptimizationConfig, ): Result + /** + * Sends a recorded voice message, which is never compressed and carries a waveform instead of a caption. + * + * @param uri the recorded audio file. + * @param mimeType the MIME type of that recording. + * @param waveForm the amplitudes used to draw the waveform. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendVoiceMessage( uri: Uri, mimeType: String, @@ -61,6 +110,14 @@ interface MediaSender { inReplyToEventId: EventId? = null, ): Result + /** + * Sends several already pre-processed media items as a single gallery message. + * + * @param mediaUploadInfos the pre-processed items, in the order they should appear. + * @param caption the text shown along with the gallery, or `null` for none. + * @param formattedCaption the caption as HTML, or `null` to send it unformatted. + * @param inReplyToEventId the event this message replies to, or `null` if it is not a reply. + */ suspend fun sendGallery( mediaUploadInfos: List, caption: String?, @@ -68,5 +125,6 @@ interface MediaSender { inReplyToEventId: EventId?, ): Result + /** Deletes the temporary files produced by pre-processing; must be called even when nothing was ultimately sent. */ fun cleanUp() } diff --git a/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessor.kt b/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessor.kt index b374e530f4..36c5208603 100644 --- a/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessor.kt +++ b/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessor.kt @@ -26,6 +26,7 @@ import io.element.android.libraries.core.data.tryOrNull import io.element.android.libraries.core.extensions.mapFailure import io.element.android.libraries.core.extensions.runCatchingExceptions import io.element.android.libraries.core.mimetype.MimeTypes +import io.element.android.libraries.core.mimetype.MimeTypes.ensureDefaultSubtype import io.element.android.libraries.core.mimetype.MimeTypes.isMimeTypeAudio import io.element.android.libraries.core.mimetype.MimeTypes.isMimeTypeImage import io.element.android.libraries.core.mimetype.MimeTypes.isMimeTypeVideo @@ -62,10 +63,10 @@ class AndroidMediaPreProcessor( /** * Used for calculating `inSampleSize` for bitmaps. * - * *Note*: Ideally, this should result in images of up to (but not included) 1280x1280 being sent. However, images with very different width and height + * *Note*: Ideally, this should result in images of up to (but not included) 2560x2560 being sent. However, images with very different width and height * values may surpass this limit. (i.e.: an image of `480x3000px` would have `inSampleSize=1` and be sent as is). */ - private const val IMAGE_SCALE_REF_SIZE = 640 + private const val IMAGE_SCALE_REF_SIZE = 1280 private val notCompressibleImageTypes = listOf(MimeTypes.Gif, MimeTypes.WebP) } @@ -82,15 +83,17 @@ class AndroidMediaPreProcessor( mediaOptimizationConfig: MediaOptimizationConfig, ): Result = withContext(coroutineDispatchers.computation) { runCatchingExceptions { + val resolvedMimeType = mimeType.ensureDefaultSubtype() val result = when { - mimeType == MimeTypes.Svg -> processSvgImage(uri, mimeType) - mimeType.isMimeTypeImage() -> { - val shouldBeCompressed = mediaOptimizationConfig.compressImages && mimeType !in notCompressibleImageTypes - processImage(uri, mimeType, shouldBeCompressed) + resolvedMimeType == MimeTypes.Svg -> processSvgImage(uri, resolvedMimeType) + resolvedMimeType.isMimeTypeImage() -> { + val imageMimeType = resolveImageMimeType(uri, mimeType).ensureDefaultSubtype() + val shouldBeCompressed = mediaOptimizationConfig.compressImages && imageMimeType !in notCompressibleImageTypes + processImage(uri, imageMimeType, shouldBeCompressed) } - mimeType.isMimeTypeVideo() -> processVideo(uri, mimeType, mediaOptimizationConfig.videoCompressionPreset) - mimeType.isMimeTypeAudio() -> processAudio(uri, mimeType) - else -> processFile(uri, mimeType) + resolvedMimeType.isMimeTypeVideo() -> processVideo(uri, resolvedMimeType, mediaOptimizationConfig.videoCompressionPreset) + resolvedMimeType.isMimeTypeAudio() -> processAudio(uri, resolvedMimeType) + else -> processFile(uri, resolvedMimeType) } if (deleteOriginal) { tryOrNull { @@ -155,6 +158,19 @@ class AndroidMediaPreProcessor( } } + /** + * The declared mime type can be broader than the image actually is - a wildcard from a share intent, or a mislabelled file - and the encoder is picked + * from it. Re-encoding a transparent image as JPEG flattens its alpha channel to black, so resolve the real format from the image header first. + */ + private fun resolveImageMimeType(uri: Uri, declaredMimeType: String): String { + if (declaredMimeType == MimeTypes.Png || declaredMimeType == MimeTypes.Jpeg) return declaredMimeType + val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } + tryOrNull { + contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, options) } + } + return options.outMimeType ?: declaredMimeType + } + private suspend fun processImage(uri: Uri, mimeType: String, shouldBeCompressed: Boolean): MediaUploadInfo { Timber.d("Processing image ${uri.path.orEmpty().hash()}") diff --git a/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfig.kt b/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfig.kt index 152678261c..40611741c9 100644 --- a/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfig.kt +++ b/libraries/mediaupload/impl/src/main/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfig.kt @@ -34,11 +34,14 @@ internal object VideoCompressorConfigFactory { val newFrameRate = min(originalFrameRate, DEFAULT_FRAME_RATE) // If we need to resize the video, we also want to recalculate the bitrate - val newBitrate = resizer.calculateOptimalBitrate(Size(width, height), newFrameRate) + val optimalBitrate = resizer.calculateOptimalBitrate(Size(width, height), newFrameRate).toInt() + + val sourceBitrate = metadata?.bitrate?.takeIf { it > 0 } + val newBitrate = sourceBitrate?.let { min(optimalBitrate.toLong(), it).toInt() } ?: optimalBitrate return VideoCompressorConfig( videoCompressorHelper = resizer, - newBitRate = newBitrate.toInt(), + newBitRate = newBitrate, newFrameRate = newFrameRate, ) } diff --git a/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessorTest.kt b/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessorTest.kt index 3fb639aa9b..090cf11674 100644 --- a/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessorTest.kt +++ b/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/AndroidMediaPreProcessorTest.kt @@ -65,11 +65,26 @@ class AndroidMediaPreProcessorTest : RobolectricTest() { assertThat(height).isEqualTo(2268) } + @Test + fun `test processing an image shared with a wildcard mime type`() = runTest { + val mediaUploadInfo = process( + asset = assetImageJpeg, + mimeType = MimeTypes.Images, + mediaOptimizationConfig = MediaOptimizationConfig( + compressImages = true, + videoCompressionPreset = VideoCompressionPreset.STANDARD, + ), + ) + val info = mediaUploadInfo as MediaUploadInfo.Image + assertThat(info.imageInfo.mimetype).isEqualTo(MimeTypes.Jpeg) + } + private suspend fun TestScope.process( asset: Asset, mediaOptimizationConfig: MediaOptimizationConfig, sdkIntVersion: Int = Build.VERSION_CODES.P, deleteOriginal: Boolean = false, + mimeType: String = asset.mimeType, ): MediaUploadInfo { val context = InstrumentationRegistry.getInstrumentation().context val deleteCallback = lambdaRecorder {} @@ -81,7 +96,7 @@ class AndroidMediaPreProcessorTest : RobolectricTest() { val file = getFileFromAssets(context, asset.filename) val result = sut.process( uri = file.toUri(), - mimeType = asset.mimeType, + mimeType = mimeType, deleteOriginal = deleteOriginal, mediaOptimizationConfig = mediaOptimizationConfig, ) @@ -91,6 +106,52 @@ class AndroidMediaPreProcessorTest : RobolectricTest() { return data } + @Test + fun `a png shared with a wildcard mime type is still encoded as a png`() = runTest { + val mediaUploadInfo = process( + asset = assetImagePng, + mimeType = MimeTypes.Images, + mediaOptimizationConfig = MediaOptimizationConfig( + compressImages = true, + videoCompressionPreset = VideoCompressionPreset.STANDARD, + ), + sdkIntVersion = Build.VERSION_CODES.Q, + ) + val info = mediaUploadInfo as MediaUploadInfo.Image + assertThat(info.imageInfo.mimetype).isEqualTo(MimeTypes.Png) + } + + @Test + fun `a gif shared with a wildcard mime type is recognised and left uncompressed`() = runTest { + val mediaUploadInfo = process( + asset = assetAnimatedGif, + mimeType = MimeTypes.Images, + mediaOptimizationConfig = MediaOptimizationConfig( + compressImages = true, + videoCompressionPreset = VideoCompressionPreset.STANDARD, + ), + sdkIntVersion = Build.VERSION_CODES.Q, + ) + val info = mediaUploadInfo as MediaUploadInfo.Image + assertThat(info.imageInfo.mimetype).isEqualTo(MimeTypes.Gif) + assertThat(info.imageInfo.size).isEqualTo(assetAnimatedGif.size) + } + + @Test + fun `a file that is not an image falls back to the default subtype of the wildcard it was shared with`() = runTest { + val mediaUploadInfo = process( + asset = assetText, + mimeType = MimeTypes.Images, + mediaOptimizationConfig = MediaOptimizationConfig( + compressImages = false, + videoCompressionPreset = VideoCompressionPreset.STANDARD, + ), + sdkIntVersion = Build.VERSION_CODES.Q, + ) + val info = mediaUploadInfo as MediaUploadInfo.Image + assertThat(info.imageInfo.mimetype).isEqualTo(MimeTypes.Jpeg) + } + @Test @Ignore("Ignore now that min API for enterprise is 33") fun `test processing png`() = runTest { @@ -208,10 +269,10 @@ class AndroidMediaPreProcessorTest : RobolectricTest() { assertThat(info.thumbnailFile).isNotNull() assertThat(info.imageInfo).isEqualTo( ImageInfo( - height = 979, - width = 3006, + height = 1958, + width = 6012, mimetype = MimeTypes.Jpeg, - size = 84_845, + size = 682_492, ThumbnailInfo(height = 244, width = 751, mimetype = MimeTypes.Jpeg, size = 7_178), thumbnailSource = null, blurhash = "K07gBzX=j_D4xZjoaSe,s:" @@ -233,10 +294,10 @@ class AndroidMediaPreProcessorTest : RobolectricTest() { assertThat(info.thumbnailFile).isNull() assertThat(info.imageInfo).isEqualTo( ImageInfo( - height = 979, - width = 3_006, + height = 1_958, + width = 6_012, mimetype = MimeTypes.Jpeg, - size = 84_845, + size = 682_492, thumbnailInfo = null, thumbnailSource = null, blurhash = null, diff --git a/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfigFactoryTest.kt b/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfigFactoryTest.kt index 6af0956541..4309d59209 100644 --- a/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfigFactoryTest.kt +++ b/libraries/mediaupload/impl/src/test/kotlin/io/element/android/libraries/mediaupload/impl/VideoCompressorConfigFactoryTest.kt @@ -33,6 +33,46 @@ class VideoCompressorConfigFactoryTest : RobolectricTest() { assertThat(videoCompressorConfig.newBitRate).isNotEqualTo(VideoEncoderSettings.NO_VALUE) } + @Test + fun `the bitrate is clamped to the source bitrate when the source is already low`() { + val metadata = VideoFileMetadata(width = 720, height = 720, bitrate = 615_000, frameRate = 25, rotation = 0) + + val videoCompressorConfig = VideoCompressorConfigFactory.create( + metadata = metadata, + preset = VideoCompressionPreset.STANDARD, + ) + + assertThat(videoCompressorConfig.newBitRate).isEqualTo(615_000) + } + + @Test + fun `the bitrate is not raised for a high bitrate source`() { + val metadata = VideoFileMetadata(width = 1920, height = 1080, bitrate = 20_000_000, frameRate = 30, rotation = 0) + + val videoCompressorConfig = VideoCompressorConfigFactory.create( + metadata = metadata, + preset = VideoCompressionPreset.STANDARD, + ) + + assertThat(videoCompressorConfig.newBitRate).isLessThan(20_000_000) + assertThat(videoCompressorConfig.newBitRate).isGreaterThan(0) + } + + @Test + fun `an unknown bitrate falls back to the calculated optimal`() { + val unknown = VideoCompressorConfigFactory.create( + metadata = VideoFileMetadata(width = 1280, height = 720, bitrate = -1, frameRate = 30, rotation = 0), + preset = VideoCompressionPreset.STANDARD, + ) + val zero = VideoCompressorConfigFactory.create( + metadata = VideoFileMetadata(width = 1280, height = 720, bitrate = 0, frameRate = 30, rotation = 0), + preset = VideoCompressionPreset.STANDARD, + ) + + assertThat(unknown.newBitRate).isGreaterThan(0) + assertThat(zero.newBitRate).isEqualTo(unknown.newBitRate) + } + @Test fun `if the video should be compressed and is larger than 720p it will be resized`() { // Given diff --git a/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaFactory.kt b/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaFactory.kt index 383f985c4f..5a218f9e1e 100644 --- a/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaFactory.kt +++ b/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaFactory.kt @@ -12,9 +12,15 @@ import android.net.Uri import io.element.android.libraries.matrix.api.media.MediaFile import io.element.android.libraries.mediaviewer.api.MediaInfo +/** + * Builds the [LocalMedia] the media viewer renders, from either a downloaded Matrix media file or an arbitrary content uri. + */ interface LocalMediaFactory { /** * This method will create a [LocalMedia] with the given [MediaFile] and [MediaInfo]. + * + * @param mediaFile the file already downloaded from the homeserver. + * @param mediaInfo what is known about the media from the event that carried it. */ fun createFromMediaFile( mediaFile: MediaFile, @@ -24,6 +30,11 @@ interface LocalMediaFactory { /** * This method will create a [LocalMedia] with the given mimeType, name and formattedFileSize * If any of those params are null, it'll try to read them from the content. + * + * @param uri the content to display, for instance one just picked by the user. + * @param mimeType the MIME type, or `null` to read it from the content. + * @param name the file name, or `null` to read it from the content. + * @param formattedFileSize the size to display, or `null` to read it from the content. */ fun createFromUri( uri: Uri, diff --git a/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaRenderer.kt b/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaRenderer.kt index fb7f26101e..5bc84919be 100644 --- a/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaRenderer.kt +++ b/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/local/LocalMediaRenderer.kt @@ -10,7 +10,15 @@ package io.element.android.libraries.mediaviewer.api.local import androidx.compose.runtime.Composable +/** + * Renders a media file held on the device, picking the right player or viewer for its type. + */ interface LocalMediaRenderer { + /** + * Draws the media, filling the space it is given. + * + * @param localMedia the file to display, along with what is known about its type. + */ @Composable fun Render(localMedia: LocalMedia) } diff --git a/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/util/FileExtensionExtractor.kt b/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/util/FileExtensionExtractor.kt index 094b4513d8..e29188e984 100644 --- a/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/util/FileExtensionExtractor.kt +++ b/libraries/mediaviewer/api/src/main/kotlin/io/element/android/libraries/mediaviewer/api/util/FileExtensionExtractor.kt @@ -8,6 +8,13 @@ package io.element.android.libraries.mediaviewer.api.util +/** + * Extracts the extension of a file name, so it can be shown to the user and used to pick an icon. + */ interface FileExtensionExtractor { + /** + * @param name the file name to inspect. + * @return the extension without its dot, or an empty string when the name has none. + */ fun extractFromName(name: String): String } diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/MediaGalleryDataSource.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/MediaGalleryDataSource.kt index 7bdd4872a3..a123fd2f97 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/MediaGalleryDataSource.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/MediaGalleryDataSource.kt @@ -83,7 +83,9 @@ class TimelineMediaGalleryDataSource( }, { Timber.e(it, "Failed to get media timeline for room ${room.roomId}") - groupedMediaItemsFlow.emit(AsyncData.Failure(it)) + if (cache == null) { + groupedMediaItemsFlow.emit(AsyncData.Failure(it)) + } }, ) }.flatMapLatest { timeline -> diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDeleteConfirmationProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDeleteConfirmationPreviewParam.kt similarity index 90% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDeleteConfirmationProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDeleteConfirmationPreviewParam.kt index 72b16c4e1d..449ab1c5c3 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDeleteConfirmationProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDeleteConfirmationPreviewParam.kt @@ -15,7 +15,7 @@ import io.element.android.libraries.matrix.api.media.MediaSource import io.element.android.libraries.mediaviewer.api.MediaInfo import io.element.android.libraries.mediaviewer.api.anImageMediaInfo -open class MediaBottomSheetStateDeleteConfirmationProvider : PreviewParameterProvider { +open class MediaBottomSheetStateDeleteConfirmationPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaBottomSheetStateDeleteConfirmation(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDetailsProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDetailsPreviewParam.kt similarity index 93% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDetailsProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDetailsPreviewParam.kt index 7540d49b8a..a38c5c2ac9 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDetailsProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaBottomSheetStateDetailsPreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.mediaviewer.api.MediaInfo import io.element.android.libraries.mediaviewer.api.anApkMediaInfo import io.element.android.libraries.mediaviewer.api.anImageMediaInfo -open class MediaBottomSheetStateDetailsProvider : PreviewParameterProvider { +open class MediaBottomSheetStateDetailsPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaBottomSheetStateDetails(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDeleteConfirmationBottomSheet.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDeleteConfirmationBottomSheet.kt index 38bbb4dcf0..6aff6cf136 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDeleteConfirmationBottomSheet.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDeleteConfirmationBottomSheet.kt @@ -168,7 +168,7 @@ private fun MediaRow( @PreviewsDayNight @Composable internal fun MediaDeleteConfirmationBottomSheetPreview( - @PreviewParameter(provider = MediaBottomSheetStateDeleteConfirmationProvider::class) state: MediaBottomSheetState.DeleteConfirmation, + @PreviewParameter(provider = MediaBottomSheetStateDeleteConfirmationPreviewParam::class) state: MediaBottomSheetState.DeleteConfirmation, ) = ElementPreview(fillMaxSize = true) { MediaDeleteConfirmationBottomSheet( state = state, diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDetailsBottomSheet.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDetailsBottomSheet.kt index 35d056dc39..f4b35a78ff 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDetailsBottomSheet.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/details/MediaDetailsBottomSheet.kt @@ -266,7 +266,7 @@ private fun SectionText( @PreviewsDayNight @Composable internal fun MediaDetailsBottomSheetPreview( - @PreviewParameter(MediaBottomSheetStateDetailsProvider::class) state: MediaBottomSheetState.Details, + @PreviewParameter(MediaBottomSheetStateDetailsPreviewParam::class) state: MediaBottomSheetState.Details, ) = ElementPreview(fillMaxSize = true) { MediaDetailsBottomSheet( state = state, diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryStateProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryStatePreviewParam.kt similarity index 98% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryStateProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryStatePreviewParam.kt index 43a361ac29..6d90fff26a 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryStateProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryStatePreviewParam.kt @@ -28,7 +28,7 @@ import io.element.android.libraries.mediaviewer.impl.model.aMediaItemVideo import io.element.android.libraries.mediaviewer.impl.model.aMediaItemVoice import kotlinx.collections.immutable.toImmutableList -open class MediaGalleryStateProvider : PreviewParameterProvider { +open class MediaGalleryStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaGalleryState( diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryView.kt index 441b6082dd..132fb4af91 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/MediaGalleryView.kt @@ -597,7 +597,7 @@ private fun LoadingContent( @PreviewsDayNight @Composable internal fun MediaGalleryViewPreview( - @PreviewParameter(MediaGalleryStateProvider::class) state: MediaGalleryState + @PreviewParameter(MediaGalleryStatePreviewParam::class) state: MediaGalleryState ) = ElementPreview { CompositionLocalProvider( LocalMediaItemPresenterFactories provides aFakeMediaItemPresenterFactories(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/di/MediaItemPresenterFactories.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/di/MediaItemPresenterFactories.kt index b74debc177..94c5485130 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/di/MediaItemPresenterFactories.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/di/MediaItemPresenterFactories.kt @@ -10,28 +10,13 @@ package io.element.android.libraries.mediaviewer.impl.gallery.di import androidx.compose.runtime.Composable import androidx.compose.runtime.remember -import dev.zacsweers.metro.BindingContainer -import dev.zacsweers.metro.ContributesTo import dev.zacsweers.metro.Inject -import dev.zacsweers.metro.Multibinds import dev.zacsweers.metro.SingleIn import io.element.android.libraries.architecture.Presenter import io.element.android.libraries.di.RoomScope import io.element.android.libraries.mediaviewer.impl.model.MediaItem import kotlin.reflect.KClass -/** - * Container that declares the [MediaItemPresenterFactory] map multi binding. - * - * Its sole purpose is to support the case of an empty map multibinding. - */ -@BindingContainer -@ContributesTo(RoomScope::class) -interface MediaItemPresenterFactoriesModule { - @Multibinds - fun multiBindMediaItemPresenterFactories(): @JvmSuppressWildcards Map, MediaItemPresenterFactory<*, *>> -} - /** * Room level caching layer for the [MediaItemPresenterFactory] instances. * diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/di/MediaItemPresenterFactoriesBindingContainer.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/di/MediaItemPresenterFactoriesBindingContainer.kt new file mode 100644 index 0000000000..2ab533aeca --- /dev/null +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/di/MediaItemPresenterFactoriesBindingContainer.kt @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.mediaviewer.impl.gallery.di + +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Multibinds +import io.element.android.libraries.di.RoomScope +import io.element.android.libraries.mediaviewer.impl.model.MediaItem +import kotlin.reflect.KClass + +/** + * Container that declares the [MediaItemPresenterFactory] map multi binding. + * + * Its sole purpose is to support the case of an empty map multibinding. + */ +@BindingContainer +@ContributesTo(RoomScope::class) +interface MediaItemPresenterFactoriesBindingContainer { + @Multibinds + fun multiBindMediaItemPresenterFactories(): @JvmSuppressWildcards Map, MediaItemPresenterFactory<*, *>> +} diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/AudioItemView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/AudioItemView.kt index cda8422e33..36d1c2de35 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/AudioItemView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/AudioItemView.kt @@ -46,7 +46,7 @@ fun AudioItemView( @PreviewsDayNight @Composable internal fun AudioItemViewPreview( - @PreviewParameter(MediaItemAudioProvider::class) audio: MediaItem.Audio, + @PreviewParameter(MediaItemAudioPreviewParam::class) audio: MediaItem.Audio, ) = ElementPreview { val states = remember { listOf( diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/DateItemView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/DateItemView.kt index b04b25a53e..8f86c86523 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/DateItemView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/DateItemView.kt @@ -45,7 +45,7 @@ fun DateItemView( @PreviewsDayNight @Composable internal fun DateItemViewPreview( - @PreviewParameter(MediaItemDateSeparatorProvider::class) date: MediaItem.DateSeparator, + @PreviewParameter(MediaItemDateSeparatorPreviewParam::class) date: MediaItem.DateSeparator, ) = ElementPreview { DateItemView(date) } diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/FileItemView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/FileItemView.kt index b552c374b9..1919eea459 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/FileItemView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/FileItemView.kt @@ -46,7 +46,7 @@ fun FileItemView( @PreviewsDayNight @Composable internal fun FileItemViewPreview( - @PreviewParameter(MediaItemFileProvider::class) file: MediaItem.File, + @PreviewParameter(MediaItemFilePreviewParam::class) file: MediaItem.File, ) = ElementPreview { val states = remember { listOf( diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemAudioProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemAudioPreviewParam.kt similarity index 92% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemAudioProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemAudioPreviewParam.kt index 4dfd1c18c8..7d5d39c9bd 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemAudioProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemAudioPreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.core.preview.loremIpsum import io.element.android.libraries.mediaviewer.impl.model.MediaItem import io.element.android.libraries.mediaviewer.impl.model.aMediaItemAudio -class MediaItemAudioProvider : PreviewParameterProvider { +class MediaItemAudioPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaItemAudio(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemDateSeparatorProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemDateSeparatorPreviewParam.kt similarity index 88% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemDateSeparatorProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemDateSeparatorPreviewParam.kt index 05705a9251..914df563cf 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemDateSeparatorProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemDateSeparatorPreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.mediaviewer.impl.model.MediaItem import io.element.android.libraries.mediaviewer.impl.model.aMediaItemDateSeparator -class MediaItemDateSeparatorProvider : PreviewParameterProvider { +class MediaItemDateSeparatorPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaItemDateSeparator(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemFileProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemFilePreviewParam.kt similarity index 92% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemFileProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemFilePreviewParam.kt index e64b10adb4..f0bd4c4383 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemFileProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemFilePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.core.preview.loremIpsum import io.element.android.libraries.mediaviewer.impl.model.MediaItem import io.element.android.libraries.mediaviewer.impl.model.aMediaItemFile -class MediaItemFileProvider : PreviewParameterProvider { +class MediaItemFilePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaItemFile(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVideoProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVideoPreviewParam.kt similarity index 90% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVideoProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVideoPreviewParam.kt index c9c4666904..e3e4017e8d 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVideoProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVideoPreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.mediaviewer.impl.model.MediaItem import io.element.android.libraries.mediaviewer.impl.model.aMediaItemVideo -class MediaItemVideoProvider : PreviewParameterProvider { +class MediaItemVideoPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaItemVideo(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVoiceProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVoicePreviewParam.kt similarity index 92% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVoiceProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVoicePreviewParam.kt index 56c1c4bb32..4f0ec2f3fa 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVoiceProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/MediaItemVoicePreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.core.preview.loremIpsum import io.element.android.libraries.mediaviewer.impl.model.MediaItem import io.element.android.libraries.mediaviewer.impl.model.aMediaItemVoice -class MediaItemVoiceProvider : PreviewParameterProvider { +class MediaItemVoicePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaItemVoice(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VideoItemView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VideoItemView.kt index 3aad3f1061..01d1e29f08 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VideoItemView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VideoItemView.kt @@ -117,7 +117,7 @@ private fun VideoInfoRow( @PreviewsDayNight @Composable internal fun VideoItemViewPreview( - @PreviewParameter(MediaItemVideoProvider::class) video: MediaItem.Video, + @PreviewParameter(MediaItemVideoPreviewParam::class) video: MediaItem.Video, ) = ElementPreview { VideoItemView( video = video, diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VoiceItemView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VoiceItemView.kt index 6c9df5fc48..2ffaed7af0 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VoiceItemView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/ui/VoiceItemView.kt @@ -54,7 +54,7 @@ import io.element.android.libraries.mediaviewer.impl.model.aMediaItemVoice import io.element.android.libraries.ui.strings.CommonStrings import io.element.android.libraries.voiceplayer.api.VoiceMessageEvent import io.element.android.libraries.voiceplayer.api.VoiceMessageState -import io.element.android.libraries.voiceplayer.api.VoiceMessageStateProvider +import io.element.android.libraries.voiceplayer.api.VoiceMessageStatePreviewParam import io.element.android.libraries.voiceplayer.api.aVoiceMessageState import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.delay @@ -279,7 +279,7 @@ private fun CustomIconButton( @PreviewsDayNight @Composable internal fun VoiceItemViewPreview( - @PreviewParameter(MediaItemVoiceProvider::class) voice: MediaItem.Voice, + @PreviewParameter(MediaItemVoicePreviewParam::class) voice: MediaItem.Voice, ) = ElementPreview { val states = remember { listOf( @@ -304,7 +304,7 @@ internal fun VoiceItemViewPreview( @PreviewsDayNight @Composable internal fun VoiceItemViewPlayPreview( - @PreviewParameter(VoiceMessageStateProvider::class) state: VoiceMessageState, + @PreviewParameter(VoiceMessageStatePreviewParam::class) state: VoiceMessageState, ) = ElementPreview { val validationState = remember { listOf( diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/voice/VoiceMessagePresenter.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/voice/VoiceMessagePresenter.kt index 32a9b0f74c..2910d28936 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/voice/VoiceMessagePresenter.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/voice/VoiceMessagePresenter.kt @@ -12,28 +12,13 @@ import androidx.compose.runtime.Composable import dev.zacsweers.metro.Assisted import dev.zacsweers.metro.AssistedFactory import dev.zacsweers.metro.AssistedInject -import dev.zacsweers.metro.BindingContainer -import dev.zacsweers.metro.Binds -import dev.zacsweers.metro.ContributesTo -import dev.zacsweers.metro.IntoMap import io.element.android.libraries.architecture.Presenter -import io.element.android.libraries.di.RoomScope -import io.element.android.libraries.mediaviewer.impl.gallery.di.MediaItemEventContentKey import io.element.android.libraries.mediaviewer.impl.gallery.di.MediaItemPresenterFactory import io.element.android.libraries.mediaviewer.impl.model.MediaItem import io.element.android.libraries.voiceplayer.api.VoiceMessagePresenterFactory import io.element.android.libraries.voiceplayer.api.VoiceMessageState import kotlin.time.Duration -@BindingContainer -@ContributesTo(RoomScope::class) -interface VoiceMessagePresenterModule { - @Binds - @IntoMap - @MediaItemEventContentKey(MediaItem.Voice::class) - fun bindVoiceMessagePresenterFactory(factory: VoiceMessagePresenter.Factory): MediaItemPresenterFactory<*, *> -} - @AssistedInject class VoiceMessagePresenter( voiceMessagePresenterFactory: VoiceMessagePresenterFactory, diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/voice/di/VoiceMessagePresenterBindingContainer.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/voice/di/VoiceMessagePresenterBindingContainer.kt new file mode 100644 index 0000000000..384f48367a --- /dev/null +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/gallery/voice/di/VoiceMessagePresenterBindingContainer.kt @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +package io.element.android.libraries.mediaviewer.impl.gallery.voice.di + +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.Binds +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.IntoMap +import io.element.android.libraries.di.RoomScope +import io.element.android.libraries.mediaviewer.impl.gallery.di.MediaItemEventContentKey +import io.element.android.libraries.mediaviewer.impl.gallery.di.MediaItemPresenterFactory +import io.element.android.libraries.mediaviewer.impl.gallery.voice.VoiceMessagePresenter +import io.element.android.libraries.mediaviewer.impl.model.MediaItem + +@BindingContainer +@ContributesTo(RoomScope::class) +interface VoiceMessagePresenterBindingContainer { + @Binds + @IntoMap + @MediaItemEventContentKey(MediaItem.Voice::class) + fun bindVoiceMessagePresenterFactory(factory: VoiceMessagePresenter.Factory): MediaItemPresenterFactory<*, *> +} diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaAudioView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaAudioView.kt index 3ac578196d..4ef746cb89 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaAudioView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaAudioView.kt @@ -393,7 +393,7 @@ private fun AudioInfoView( @PreviewsDayNight @Composable internal fun MediaAudioViewPreview( - @PreviewParameter(MediaInfoAudioProvider::class) info: MediaInfo + @PreviewParameter(MediaInfoAudioPreviewParam::class) info: MediaInfo ) = ElementPreview { MediaAudioView( modifier = Modifier.fillMaxSize(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaInfoAudioProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaInfoAudioPreviewParam.kt similarity index 91% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaInfoAudioProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaInfoAudioPreviewParam.kt index 02607e3e0e..900321a909 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaInfoAudioProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/audio/MediaInfoAudioPreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.designsystem.components.media.WaveFormSample import io.element.android.libraries.mediaviewer.api.MediaInfo import io.element.android.libraries.mediaviewer.api.anAudioMediaInfo -open class MediaInfoAudioProvider : PreviewParameterProvider { +open class MediaInfoAudioPreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( anAudioMediaInfo(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaFileView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaFileView.kt index a1c57ef272..89e02b616a 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaFileView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaFileView.kt @@ -114,7 +114,7 @@ fun MediaFileView( @PreviewsDayNight @Composable internal fun MediaFileViewPreview( - @PreviewParameter(MediaInfoFileProvider::class) info: MediaInfo + @PreviewParameter(MediaInfoFilePreviewParam::class) info: MediaInfo ) = ElementPreview { MediaFileView( modifier = Modifier.fillMaxSize(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaInfoFileProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaInfoFilePreviewParam.kt similarity index 91% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaInfoFileProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaInfoFilePreviewParam.kt index 3214236253..b647eb8fd2 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaInfoFileProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/file/MediaInfoFilePreviewParam.kt @@ -14,7 +14,7 @@ import io.element.android.libraries.mediaviewer.api.aZipMediaInfo import io.element.android.libraries.mediaviewer.api.anApkMediaInfo import io.element.android.libraries.mediaviewer.api.anAudioMediaInfo -open class MediaInfoFileProvider : PreviewParameterProvider { +open class MediaInfoFilePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aZipMediaInfo(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/ExoPlayerForPreview.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/ExoPlayerForPreview.kt index 4da8433cd1..e23cb790db 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/ExoPlayerForPreview.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/ExoPlayerForPreview.kt @@ -266,4 +266,5 @@ class ExoPlayerForPreview( override fun setVideoCodecParameters(codecParameters: CodecParameters) {} override fun addVideoCodecParametersChangeListener(listener: CodecParametersChangeListener, keys: List) {} override fun removeVideoCodecParametersChangeListener(listener: CodecParametersChangeListener) {} + override fun setEnforceAdPlaybackOnTimelineRefresh(enforceAdPlaybackOnTimelineRefresh: Boolean) = throw NotImplementedError() } diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerStateProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerStatePreviewParam.kt similarity index 92% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerStateProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerStatePreviewParam.kt index 55432fb817..b229d11283 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerStateProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.libraries.mediaviewer.impl.local.player import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class MediaPlayerControllerStateProvider : PreviewParameterProvider { +open class MediaPlayerControllerStatePreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( aMediaPlayerControllerState(), aMediaPlayerControllerState( diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerView.kt index 1f2b0b93d2..0a68a2d75d 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/player/MediaPlayerControllerView.kt @@ -213,7 +213,7 @@ fun MediaPlayerControllerView( @PreviewsDayNight @Composable internal fun MediaPlayerControllerViewPreview( - @PreviewParameter(MediaPlayerControllerStateProvider::class) state: MediaPlayerControllerState + @PreviewParameter(MediaPlayerControllerStatePreviewParam::class) state: MediaPlayerControllerState ) = ElementPreview { MediaPlayerControllerView( state = state, diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileContentProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileContentPreviewParam.kt similarity index 89% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileContentProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileContentPreviewParam.kt index d92e400495..108f8dd066 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileContentProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileContentPreviewParam.kt @@ -13,7 +13,7 @@ import io.element.android.libraries.architecture.AsyncData import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -open class TextFileContentProvider : PreviewParameterProvider>> { +open class TextFileContentPreviewParam : PreviewParameterProvider>> { override val values: Sequence>> get() = sequenceOf( AsyncData.Uninitialized, diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileView.kt index f4984470dd..2f397103e8 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/local/txt/TextFileView.kt @@ -98,7 +98,7 @@ private fun TextFileContentView( @PreviewsDayNight @Composable internal fun TextFileContentViewPreview( - @PreviewParameter(TextFileContentProvider::class) text: AsyncData>, + @PreviewParameter(TextFileContentPreviewParam::class) text: AsyncData>, ) = ElementPreview { TextFileContentView( data = text, diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerNode.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerNode.kt index e53153ce19..77222d97ff 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerNode.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerNode.kt @@ -92,7 +92,7 @@ class MediaViewerNode( is MediaViewerEntryPoint.Params.RoomMedia -> { val eventId = inputs.eventId if (eventId == null) { - // Should not happen + // Local echo, the viewer will not be focused on the item timelineMediaGalleryDataSource } else { // Can we use a specific timeline? diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerStateProvider.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerStatePreviewParam.kt similarity index 99% rename from libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerStateProvider.kt rename to libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerStatePreviewParam.kt index 440d366c30..ea422e41f1 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerStateProvider.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerStatePreviewParam.kt @@ -41,7 +41,7 @@ private const val LONG_CAPTION = "This is a very long caption that should be scr "Line 4: Duis aute irure dolor in reprehenderit in voluptate velit esse cillum. " + "Line 5: Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia." -open class MediaViewerStateProvider : PreviewParameterProvider { +open class MediaViewerStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aMediaViewerState(), diff --git a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerView.kt b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerView.kt index 6eca5e9dbc..343bf99ec9 100644 --- a/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerView.kt +++ b/libraries/mediaviewer/impl/src/main/kotlin/io/element/android/libraries/mediaviewer/impl/viewer/MediaViewerView.kt @@ -82,7 +82,6 @@ import io.element.android.libraries.audio.api.AudioFocus import io.element.android.libraries.core.mimetype.MimeTypes.isMimeTypeVideo import io.element.android.libraries.designsystem.atomic.molecules.IconTitleSubtitleMolecule import io.element.android.libraries.designsystem.components.BigIcon -import io.element.android.libraries.designsystem.components.async.AsyncFailure import io.element.android.libraries.designsystem.components.async.AsyncIndicator import io.element.android.libraries.designsystem.components.async.AsyncLoading import io.element.android.libraries.designsystem.components.button.BackButton @@ -209,7 +208,6 @@ fun MediaViewerView( when (val dataForPage = state.listData[page]) { is MediaViewerPageData.Failure -> { MediaViewerErrorPage( - throwable = dataForPage.throwable, onDismiss = onBackClick, ) } @@ -414,6 +412,7 @@ private fun MediaViewerPage( if (showProgress) { LinearProgressIndicator( modifier = Modifier + .padding(WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top).asPaddingValues()) .fillMaxWidth() .height(2.dp) ) @@ -506,7 +505,6 @@ private fun MediaViewerLoadingPage( @Composable private fun MediaViewerErrorPage( - throwable: Throwable, onDismiss: () -> Unit, modifier: Modifier = Modifier, ) { @@ -520,9 +518,10 @@ private fun MediaViewerErrorPage( .navigationBarsPadding(), contentAlignment = Alignment.Center ) { - AsyncFailure( - throwable = throwable, - onRetry = null + IconTitleSubtitleMolecule( + iconStyle = BigIcon.Style.AlertSolid, + title = stringResource(CommonStrings.common_something_went_wrong), + subTitle = stringResource(CommonStrings.common_something_went_wrong_message), ) } } @@ -750,7 +749,7 @@ private fun ErrorView( // Only preview in dark, dark theme is forced on the Node. @Preview @Composable -internal fun MediaViewerViewPreview(@PreviewParameter(MediaViewerStateProvider::class) state: MediaViewerState) = ElementPreviewDark { +internal fun MediaViewerViewPreview(@PreviewParameter(MediaViewerStatePreviewParam::class) state: MediaViewerState) = ElementPreviewDark { MediaViewerView( state = state, audioFocus = null, @@ -761,7 +760,7 @@ internal fun MediaViewerViewPreview(@PreviewParameter(MediaViewerStateProvider:: @Preview(device = "${Devices.PHONE}, orientation=landscape") @Composable -internal fun MediaViewerViewLandscapePreview(@PreviewParameter(MediaViewerStateProvider::class) state: MediaViewerState) = ElementPreviewDark { +internal fun MediaViewerViewLandscapePreview(@PreviewParameter(MediaViewerStatePreviewParam::class) state: MediaViewerState) = ElementPreviewDark { MediaViewerView( state = state, audioFocus = null, diff --git a/libraries/mediaviewer/impl/src/main/res/values-ar/translations.xml b/libraries/mediaviewer/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..0e18b01b6b --- /dev/null +++ b/libraries/mediaviewer/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,22 @@ + + + "ستتم إزالة هذا الملف من الغرفة ولن يتمكن الأعضاء من الوصول إليه." + "إزالة الملف؟" + "تحقّق من اتصالك بالإنترنت وحاول مرة أخرى." + "ستظهر هنا المستندات والملفات الصوتية والرسائل الصوتية التي يتم رفعها إلى هذه الغرفة." + "لم يتم رفع أي ملفات بعد" + "جارٍ تحميل الملفات…" + "جارٍ تحميل الوسائط…" + "الملفات" + "الوسائط" + "ستظهر هنا الصور ومقاطع الفيديو التي يتم رفعها إلى هذه الغرفة." + "لم يتم رفع أي وسائط بعد" + "الوسائط والملفات" + "التنسيق" + "الاسم" + "لا توجد ملفات أخرى لعرضها" + "لا توجد وسائط أخرى لعرضها" + "معلومات الملف" + "تم الرفع بواسطة" + "تم الرفع في" + diff --git a/libraries/mediaviewer/impl/src/main/res/values-es/translations.xml b/libraries/mediaviewer/impl/src/main/res/values-es/translations.xml index 686dc60658..2a98d41e81 100644 --- a/libraries/mediaviewer/impl/src/main/res/values-es/translations.xml +++ b/libraries/mediaviewer/impl/src/main/res/values-es/translations.xml @@ -6,16 +6,17 @@ "Los documentos, archivos de audio y mensajes de voz subidos a esta sala se mostrarán aquí." "Aún no se ha subido ningún archivo" "Cargando archivos…" - "Cargando medios…" + "Cargando multimedia…" "Archivos" - "Medios" + "Multimedia" "Las imágenes y vídeos subidos a esta sala se mostrarán aquí." "Aún no se ha subido ningún medio" - "Medios y archivos" + "Multimedia y archivos" "Formato de archivo" "Nombre del archivo" "No hay más archivos que mostrar" "No hay más medios que mostrar" + "Información del archivo" "Subido por" "Subido el" diff --git a/libraries/mediaviewer/impl/src/main/res/values-fa/translations.xml b/libraries/mediaviewer/impl/src/main/res/values-fa/translations.xml index 81f8f4db2d..30a9add8f3 100644 --- a/libraries/mediaviewer/impl/src/main/res/values-fa/translations.xml +++ b/libraries/mediaviewer/impl/src/main/res/values-fa/translations.xml @@ -1,5 +1,6 @@ + "این فایل از اتاق حذف خواهد شد و اعضا به آن دسترسی نخواهند داشت." "حذف پرونده؟" "بررسی اتّصال اینترنتیتان و تلاش دوباره." "سندها، پرونده‌ها و پیام‌های صوتی بار گذاشته در این اتاق این‌جا نشان داده خواهند شد." @@ -13,6 +14,9 @@ "رسانه‌ها و پرونده‌ها" "قالب پرونده" "نام پرونده" + "فایل بیشتری برای نمایش وجود ندارد" + "رسانه دیگری برای نمایش وجود ندارد" + "اطلاعات فایل" "بارگذاشته به دست" "بارگذاشته در" diff --git a/libraries/mediaviewer/impl/src/main/res/values-zh-rTW/translations.xml b/libraries/mediaviewer/impl/src/main/res/values-zh-rTW/translations.xml index 4cbe579e00..0bebdea024 100644 --- a/libraries/mediaviewer/impl/src/main/res/values-zh-rTW/translations.xml +++ b/libraries/mediaviewer/impl/src/main/res/values-zh-rTW/translations.xml @@ -16,6 +16,7 @@ "檔案名稱" "無可顯示的檔案" "無可顯示的媒體" + "檔案資訊" "上傳者:" "上傳於" diff --git a/libraries/mediaviewer/impl/src/test/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/TimelineMediaGalleryDataSourceTest.kt b/libraries/mediaviewer/impl/src/test/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/TimelineMediaGalleryDataSourceTest.kt index 81bb23d73c..a18bce58c4 100644 --- a/libraries/mediaviewer/impl/src/test/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/TimelineMediaGalleryDataSourceTest.kt +++ b/libraries/mediaviewer/impl/src/test/kotlin/io/element/android/libraries/mediaviewer/impl/datasource/TimelineMediaGalleryDataSourceTest.kt @@ -39,6 +39,7 @@ import io.element.android.libraries.matrix.ui.media.contentvalidation.NoopEventC import io.element.android.libraries.mediaviewer.api.MediaInfo import io.element.android.libraries.mediaviewer.impl.model.GroupedMediaItems import io.element.android.libraries.mediaviewer.impl.model.MediaItem +import io.element.android.libraries.mediaviewer.impl.model.aMediaItemImage import io.element.android.libraries.mediaviewer.test.util.FileExtensionExtractorWithoutValidation import io.element.android.tests.testutils.WarmUpRule import io.element.android.tests.testutils.lambda.lambdaRecorder @@ -171,6 +172,32 @@ class TimelineMediaGalleryDataSourceTest { } } + @Test + fun `test - failing to load a focused timeline keeps the item that was opened`() = runTest { + val room = FakeJoinedRoom( + createTimelineResult = { Result.failure(AN_EXCEPTION) }, + roomCoroutineScope = backgroundScope, + ) + val initialMediaItem = aMediaItemImage() + val sut = createTimelineMediaGalleryDataSource( + room = room, + mediaTimeline = FocusedMediaTimeline( + room = room, + eventId = AN_EVENT_ID, + onlyPinnedEvents = false, + initialMediaItem = initialMediaItem, + ), + ) + sut.start(backgroundScope) + sut.groupedMediaItemsFlow().test { + val item = awaitItem() + assertThat(item.isSuccess()).isTrue() + assertThat(item.dataOrNull()?.imageAndVideoItems).contains(initialMediaItem) + expectNoEvents() + } + assertThat(sut.getLastData().isFailure()).isFalse() + } + @Test fun `test - when timeline emits new data, the flow emits the data`() = runTest { val timelineItems = MutableStateFlow>(emptyList()) @@ -269,10 +296,11 @@ internal fun TestScope.createTimelineMediaGalleryDataSource( room: JoinedRoom = FakeJoinedRoom( liveTimeline = FakeTimeline(), ), + mediaTimeline: MediaTimeline? = null, ): TimelineMediaGalleryDataSource { return TimelineMediaGalleryDataSource( room = room, - mediaTimeline = LiveMediaTimeline(room), + mediaTimeline = mediaTimeline ?: LiveMediaTimeline(room), timelineMediaItemsFactory = createTimelineMediaItemsFactory(), mediaItemsPostProcessor = MediaItemsPostProcessor(), ) diff --git a/libraries/network/src/main/kotlin/io/element/android/libraries/network/NetworkModule.kt b/libraries/network/src/main/kotlin/io/element/android/libraries/network/di/NetworkBindingContainer.kt similarity index 95% rename from libraries/network/src/main/kotlin/io/element/android/libraries/network/NetworkModule.kt rename to libraries/network/src/main/kotlin/io/element/android/libraries/network/di/NetworkBindingContainer.kt index 90e78d860e..46f00a6b9b 100644 --- a/libraries/network/src/main/kotlin/io/element/android/libraries/network/NetworkModule.kt +++ b/libraries/network/src/main/kotlin/io/element/android/libraries/network/di/NetworkBindingContainer.kt @@ -6,7 +6,7 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.libraries.network +package io.element.android.libraries.network.di import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.BindingContainer @@ -23,7 +23,7 @@ import java.util.concurrent.TimeUnit @BindingContainer @ContributesTo(AppScope::class) -object NetworkModule { +object NetworkBindingContainer { @Provides @SingleIn(AppScope::class) fun providesOkHttpClient( diff --git a/libraries/network/src/main/kotlin/io/element/android/libraries/network/useragent/DefaultUserAgentProvider.kt b/libraries/network/src/main/kotlin/io/element/android/libraries/network/useragent/DefaultUserAgentProvider.kt index 3ecd091e0d..2a32c6d273 100644 --- a/libraries/network/src/main/kotlin/io/element/android/libraries/network/useragent/DefaultUserAgentProvider.kt +++ b/libraries/network/src/main/kotlin/io/element/android/libraries/network/useragent/DefaultUserAgentProvider.kt @@ -12,6 +12,7 @@ import android.os.Build import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding import dev.zacsweers.metro.SingleIn +import io.element.android.libraries.core.extensions.normalized import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.matrix.api.SdkMetadata @@ -26,11 +27,11 @@ class DefaultUserAgentProvider( override fun provide(): String = userAgent /** - * Create an user agent with the application version. + * Create a user agent with the application version. * Ex: Element X/1.5.0 (Xiaomi Mi 9T; Android 11; RKQ1.200826.002; Sdk c344b155c) */ private fun buildUserAgent(): String { - val appName = buildMeta.applicationName + val appName = buildMeta.applicationName.normalized() val appVersion = buildMeta.versionName val deviceManufacturer = Build.MANUFACTURER val deviceModel = Build.MODEL diff --git a/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthActionFlow.kt b/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthActionFlow.kt index c6791e3197..7cb35de176 100644 --- a/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthActionFlow.kt +++ b/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthActionFlow.kt @@ -10,8 +10,26 @@ package io.element.android.libraries.oauth.api import kotlinx.coroutines.flow.FlowCollector +/** + * Carries the OAuth redirect from the activity that receives it to the login screen waiting for it. + * + * The two are not in the same navigation subtree, so the result cannot simply be returned. + */ interface OAuthActionFlow { + /** + * Publishes the action just received, to be picked up by whoever is collecting. + * + * @param oAuthAction the action resolved from the redirect intent. + */ fun post(oAuthAction: OAuthAction) + + /** + * Observes the published actions; `null` is emitted when there is nothing pending. + * + * @param collector the collector to feed. + */ suspend fun collect(collector: FlowCollector) + + /** Clears the pending action, so it is not handled twice. */ fun reset() } diff --git a/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthIntentResolver.kt b/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthIntentResolver.kt index 2091a86db4..5187649298 100644 --- a/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthIntentResolver.kt +++ b/libraries/oauth/api/src/main/kotlin/io/element/android/libraries/oauth/api/OAuthIntentResolver.kt @@ -10,6 +10,13 @@ package io.element.android.libraries.oauth.api import android.content.Intent +/** + * Recognises the redirect the authentication server sends the user back with once they have signed in or cancelled. + */ interface OAuthIntentResolver { + /** + * @param intent the intent the app was resumed with. + * @return the action to carry out, or `null` when the intent is not an OAuth redirect. + */ fun resolve(intent: Intent): OAuthAction? } diff --git a/libraries/oauth/test/src/main/kotlin/io/element/android/libraries/oauth/test/customtab/FakeOAuthActionFlow.kt b/libraries/oauth/test/src/main/kotlin/io/element/android/libraries/oauth/test/FakeOAuthActionFlow.kt similarity index 94% rename from libraries/oauth/test/src/main/kotlin/io/element/android/libraries/oauth/test/customtab/FakeOAuthActionFlow.kt rename to libraries/oauth/test/src/main/kotlin/io/element/android/libraries/oauth/test/FakeOAuthActionFlow.kt index 5a5ca4369e..49abe58622 100644 --- a/libraries/oauth/test/src/main/kotlin/io/element/android/libraries/oauth/test/customtab/FakeOAuthActionFlow.kt +++ b/libraries/oauth/test/src/main/kotlin/io/element/android/libraries/oauth/test/FakeOAuthActionFlow.kt @@ -6,7 +6,7 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.libraries.oauth.test.customtab +package io.element.android.libraries.oauth.test import io.element.android.libraries.oauth.api.OAuthAction import io.element.android.libraries.oauth.api.OAuthActionFlow diff --git a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionStateProvider.kt b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionStateProvider.kt index beeef0b234..98fb3edbe0 100644 --- a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionStateProvider.kt +++ b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionStateProvider.kt @@ -10,11 +10,40 @@ package io.element.android.libraries.permissions.api import kotlinx.coroutines.flow.Flow +/** + * Answers permission questions by combining the live system state with what [PermissionsStore] remembers about past requests. + */ interface PermissionStateProvider { + /** + * Whether the permission is granted right now, read from the system rather than from the store. + * + * @param permission the Android permission name. + */ fun isPermissionGranted(permission: String): Boolean + + /** + * @param permission the Android permission name. + * @param value true once the user has refused this permission. + */ suspend fun setPermissionDenied(permission: String, value: Boolean) + + /** + * Whether the user has refused this permission before. + * + * @param permission the Android permission name. + */ fun isPermissionDenied(permission: String): Flow + /** + * @param permission the Android permission name. + * @param value true once the system dialog for this permission has been shown. + */ suspend fun setPermissionAsked(permission: String, value: Boolean) + + /** + * Whether the system dialog for this permission has already been shown. + * + * @param permission the Android permission name. + */ fun isPermissionAsked(permission: String): Flow } diff --git a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsPresenter.kt b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsPresenter.kt index f2ccb2bfc3..07918d0c86 100644 --- a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsPresenter.kt +++ b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsPresenter.kt @@ -11,7 +11,13 @@ package io.element.android.libraries.permissions.api import io.element.android.libraries.architecture.Presenter interface PermissionsPresenter : Presenter { + /** + * Creates a presenter dedicated to one permission. + */ interface Factory { + /** + * @param permission the Android permission name this presenter will request. + */ fun create(permission: String): PermissionsPresenter } } diff --git a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStateProvider.kt b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStatePreviewParam.kt similarity index 93% rename from libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStateProvider.kt rename to libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStatePreviewParam.kt index a330333d17..9052667578 100644 --- a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStateProvider.kt +++ b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStatePreviewParam.kt @@ -11,7 +11,7 @@ package io.element.android.libraries.permissions.api import android.Manifest import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class PermissionsStateProvider : PreviewParameterProvider { +open class PermissionsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aPermissionsState(showDialog = true, permission = Manifest.permission.POST_NOTIFICATIONS), diff --git a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStore.kt b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStore.kt index 3bb7d2c679..2d37f016f9 100644 --- a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStore.kt +++ b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsStore.kt @@ -10,15 +10,44 @@ package io.element.android.libraries.permissions.api import kotlinx.coroutines.flow.Flow +/** + * Remembers what the app has already asked the user about, since Android itself does not let an app tell + * "never asked" apart from "asked and denied". + */ interface PermissionsStore { + /** + * @param permission the Android permission name. + * @param value true once the user has refused this permission. + */ suspend fun setPermissionDenied(permission: String, value: Boolean) + + /** + * Whether the user has refused this permission before. + * + * @param permission the Android permission name. + */ fun isPermissionDenied(permission: String): Flow + /** + * @param permission the Android permission name. + * @param value true once the system dialog for this permission has been shown. + */ suspend fun setPermissionAsked(permission: String, value: Boolean) + + /** + * Whether the system dialog for this permission has already been shown, which decides whether the app may show a rationale instead. + * + * @param permission the Android permission name. + */ fun isPermissionAsked(permission: String): Flow + /** + * Forgets what was recorded about one permission, so the app behaves as if it had never been requested. + * + * @param permission the Android permission name. + */ suspend fun resetPermission(permission: String) - // To debug + /** Forgets every recorded permission; exposed for debugging from the developer options. */ suspend fun resetStore() } diff --git a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsView.kt b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsView.kt index af0f3dd5e8..7a641b1cfd 100644 --- a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsView.kt +++ b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/PermissionsView.kt @@ -55,7 +55,7 @@ private fun String.toDialogContent(): String { @PreviewsDayNight @Composable -internal fun PermissionsViewPreview(@PreviewParameter(PermissionsStateProvider::class) state: PermissionsState) = ElementPreview { +internal fun PermissionsViewPreview(@PreviewParameter(PermissionsStatePreviewParam::class) state: PermissionsState) = ElementPreview { PermissionsView( state = state, ) diff --git a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/localnetwork/LocalNetworkPermissionAdvisor.kt b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/localnetwork/LocalNetworkPermissionAdvisor.kt index 9863dbb751..8d801cfe67 100644 --- a/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/localnetwork/LocalNetworkPermissionAdvisor.kt +++ b/libraries/permissions/api/src/main/kotlin/io/element/android/libraries/permissions/api/localnetwork/LocalNetworkPermissionAdvisor.kt @@ -7,10 +7,15 @@ package io.element.android.libraries.permissions.api.localnetwork +/** + * Decides whether the local network permission is needed to reach a homeserver, which is the case for a server on the user's own network. + */ interface LocalNetworkPermissionAdvisor { /** * Returns true when the app should request the ACCESS_LOCAL_NETWORK permission before making * network requests to [homeserverUrl]. + * + * @param homeserverUrl the server the app is about to contact. */ suspend fun shouldRequestPermissionFor(homeserverUrl: String): Boolean } diff --git a/libraries/permissions/api/src/main/res/values-ar/translations.xml b/libraries/permissions/api/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..4131b6d27c --- /dev/null +++ b/libraries/permissions/api/src/main/res/values-ar/translations.xml @@ -0,0 +1,7 @@ + + + "من أجل جعل التطبيق يستخدم الكاميرا عليك بمنح الإذن لذلك في إعدادات النظام." + "يرجى منح الإذن في إعدادات النظام." + "من أجل جعل التطبيق يستخدم المايكروفون عليك بمنح الإذن لذلك في إعدادت النظام." + "من أجل جعل التطبيق يظهر الإشعارات عليك أن تمنح الإذن في إعدادات النظام." + diff --git a/libraries/permissions/impl/src/main/res/values-ar/translations.xml b/libraries/permissions/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..5d9fb3e1e6 --- /dev/null +++ b/libraries/permissions/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,5 @@ + + + "يتحقق من قدرة التطبيق على عرض الإشعارات." + "التحقق من الأذونات" + diff --git a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/AppPreferencesStore.kt b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/AppPreferencesStore.kt index b1877b3ae5..6285c46389 100644 --- a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/AppPreferencesStore.kt +++ b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/AppPreferencesStore.kt @@ -13,48 +13,125 @@ import io.element.android.libraries.matrix.api.tracing.LogLevel import io.element.android.libraries.matrix.api.tracing.TraceLogPack import kotlinx.coroutines.flow.Flow +/** + * Local, app-wide user preferences that are not tied to a session, stored on the device only. + * + * Each getter returns a flow that emits the current value straight away and then again on every change. + * The default each preference falls back to when it has never been set is given on the getter. + */ interface AppPreferencesStore { + /** + * @param enabled true to expose the developer options in the settings. + */ suspend fun setDeveloperModeEnabled(enabled: Boolean) + + /** Whether developer mode is on; defaults to `true` on debug builds and `false` otherwise. */ fun isDeveloperModeEnabledFlow(): Flow + /** + * @param string the Element Call deployment to use, or `null` to go back to the one from the homeserver. + */ suspend fun setCustomElementCallBaseUrl(string: String?) + + /** The Element Call URL the user has overridden, or `null` when the homeserver's own value should be used. */ fun getCustomElementCallBaseUrlFlow(): Flow + /** + * @param theme the name of the theme to apply: light, dark, or follow the system. + */ suspend fun setTheme(theme: String) + + /** The name of the chosen theme, or `null` when the user has not picked one and the system setting should be followed. */ fun getThemeFlow(): Flow + /** + * @param value the distance in metres the user must move before a new live location is published. + */ suspend fun setLiveLocationMinimumDistanceInMetersUpdate(value: Int) + + /** The minimum distance in metres between two live location updates; defaults to 10. */ fun getLiveLocationMinimumDistanceInMetersUpdateFlow(): Flow + /** + * Only used to clear the local value once it has been migrated to the server. + * + * @param hide the local setting, or `null` to erase it. + */ @Deprecated("Use MediaPreviewService instead. Kept only for migration.") suspend fun setHideInviteAvatars(hide: Boolean?) + + /** The local setting to migrate to the server, or `null` once there is nothing left to migrate. */ @Deprecated("Use MediaPreviewService instead. Kept only for migration.") fun getHideInviteAvatarsFlow(): Flow + + /** + * Only used to clear the local value once it has been migrated to the server. + * + * @param mediaPreviewValue the local setting, or `null` to erase it. + */ @Deprecated("Use MediaPreviewService instead. Kept only for migration.") suspend fun setTimelineMediaPreviewValue(mediaPreviewValue: MediaPreviewValue?) + + /** The local setting to migrate to the server, or `null` once there is nothing left to migrate. */ @Deprecated("Use MediaPreviewService instead. Kept only for migration.") fun getTimelineMediaPreviewValueFlow(): Flow + /** + * @param logLevel how verbose the SDK and app logs should be. + */ suspend fun setTracingLogLevel(logLevel: LogLevel) + + /** The configured log level; defaults to the one the build was compiled with. */ fun getTracingLogLevelFlow(): Flow + /** + * The list of account providers (homeserver URLs) the user has previously authenticated + * against, most recent first. Used to default the account provider and to power autocomplete + * suggestions during sign-in. Stored locally only; never synced across devices. + */ + fun getHomeserverHistoryFlow(): Flow> + + /** + * Add [url] to the front of the account provider history (see [getHomeserverHistoryFlow]). + * The value is normalised (trimmed + lowercased); existing case-insensitive duplicates are + * moved to the front rather than duplicated, and the list is capped in size. No-op for blanks. + */ + suspend fun addHomeserverToHistory(url: String) + + /** + * @param targets the extra log packs to enable on top of the default targets. + */ suspend fun setTracingLogPacks(targets: Set) + + /** The extra log packs enabled by the user; defaults to an empty set. */ fun getTracingLogPacksFlow(): Flow> + /** The sound played for message notifications. */ fun getMessageSoundFlow(): Flow /** * Atomically persists [sound] (with copy-time [title] for Custom; cleared otherwise) and * bumps the channel version. Single transaction so process death can't desync URI and version. + * + * @param sound the sound to persist. + * @param title the display name captured when the sound was copied, or `null` for the built-in choices. + * @return the new channel version, to be passed to the channel recreation. */ suspend fun setMessageSoundAndIncrementVersion(sound: NotificationSound, title: String?): Int /** Title captured at copy time. Null for SystemDefault / Silent or pre-title persisted data. */ fun getMessageSoundDisplayNameFlow(): Flow + /** The sound played for incoming call notifications. */ fun getCallRingtoneFlow(): Flow - /** See [setMessageSoundAndIncrementVersion]. */ + /** + * See [setMessageSoundAndIncrementVersion]. + * + * @param sound the ringtone to persist. + * @param title the display name captured when the sound was copied, or `null` for the built-in choices. + * @return the new channel version, to be passed to the channel recreation. + */ suspend fun setCallRingtoneAndIncrementVersion(sound: NotificationSound, title: String?): Int /** See [getMessageSoundDisplayNameFlow]. */ @@ -63,5 +140,6 @@ interface AppPreferencesStore { /** Single-snapshot read of all sound prefs; used at boot to seed channels without N reads. */ suspend fun getNotificationSoundChannelConfig(): NotificationSoundChannelConfig + /** Erases every app preference, so they all fall back to their defaults. */ suspend fun reset() } diff --git a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/PreferenceDataStoreFactory.kt b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/PreferenceDataStoreFactory.kt index 50f6eb2431..a3d609e205 100644 --- a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/PreferenceDataStoreFactory.kt +++ b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/PreferenceDataStoreFactory.kt @@ -17,5 +17,10 @@ import androidx.datastore.preferences.core.Preferences * It's a wrapper around AndroidX's `PreferenceDataStoreFactory` to make testing easier. */ interface PreferenceDataStoreFactory { + /** + * Creates or opens the preference store with the given name. + * + * @param name the store name, which also determines the file it is persisted to. + */ fun create(name: String): DataStore } diff --git a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStore.kt b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStore.kt index d3f3fb4e28..b554fff460 100644 --- a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStore.kt +++ b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStore.kt @@ -10,30 +10,77 @@ package io.element.android.libraries.preferences.api.store import kotlinx.coroutines.flow.Flow +/** + * Local, per-session user preferences, stored on the device only and never synced to the homeserver. + * + * Each getter returns a flow that emits the current value straight away and then again on every change. + * The default each preference falls back to when it has never been set is given on the getter. + */ interface SessionPreferencesStore { + /** + * @param enabled true to let the homeserver share this user's presence with others. + */ suspend fun setSharePresence(enabled: Boolean) + + /** Whether presence is shared; defaults to `true`. */ fun isSharePresenceEnabled(): Flow + /** + * @param enabled true to send read receipts that other members can see. + */ suspend fun setSendPublicReadReceipts(enabled: Boolean) + + /** Whether read receipts are sent publicly rather than privately; defaults to `true`. */ fun isSendPublicReadReceiptsEnabled(): Flow + /** + * @param enabled true to display the read receipts of other members in the timeline. + */ suspend fun setRenderReadReceipts(enabled: Boolean) + + /** Whether other members' read receipts are displayed; defaults to `true`. */ fun isRenderReadReceiptsEnabled(): Flow + /** + * @param enabled true to tell other members when this user is typing. + */ suspend fun setSendTypingNotifications(enabled: Boolean) + + /** Whether typing notifications are sent; defaults to `true`. */ fun isSendTypingNotificationsEnabled(): Flow + /** + * @param enabled true to display which other members are typing. + */ suspend fun setRenderTypingNotifications(enabled: Boolean) + + /** Whether other members' typing notifications are displayed; defaults to `true`. */ fun isRenderTypingNotificationsEnabled(): Flow + /** + * @param skip true to remember that the user dismissed the session verification prompt. + */ suspend fun setSkipSessionVerification(skip: Boolean) + + /** Whether the user chose to skip verifying this session, so they are not asked again; defaults to `false`. */ fun isSessionVerificationSkipped(): Flow + /** + * @param compress true to downscale images before uploading them. + */ suspend fun setOptimizeImages(compress: Boolean) + + /** Whether images are downscaled before upload; defaults to `true`. */ fun doesOptimizeImages(): Flow + /** + * @param preset the quality and size trade-off to apply when compressing videos. + */ suspend fun setVideoCompressionPreset(preset: VideoCompressionPreset) + + /** The video compression preset; defaults to [VideoCompressionPreset.STANDARD], including when the stored value is unreadable. */ fun getVideoCompressionPreset(): Flow + /** Erases every preference of this session, so they all fall back to their defaults. */ suspend fun clear() } diff --git a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStoreFactory.kt b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStoreFactory.kt index 2c0038d06e..05b4845026 100644 --- a/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStoreFactory.kt +++ b/libraries/preferences/api/src/main/kotlin/io/element/android/libraries/preferences/api/store/SessionPreferencesStoreFactory.kt @@ -11,7 +11,22 @@ package io.element.android.libraries.preferences.api.store import io.element.android.libraries.matrix.api.core.SessionId import kotlinx.coroutines.CoroutineScope +/** + * Caches one [SessionPreferencesStore] per session, so that every caller of a given session shares the same instance. + */ interface SessionPreferencesStoreFactory { + /** + * Returns the store of a session, creating it on first use. + * + * @param sessionId the session whose store is requested. + * @param sessionCoroutineScope the scope the store uses for its own work, only honoured when the store is actually created. + */ fun get(sessionId: SessionId, sessionCoroutineScope: CoroutineScope): SessionPreferencesStore + + /** + * Drops the cached store of a session, to be called when that session goes away. + * + * @param sessionId the session whose store is dropped. + */ fun remove(sessionId: SessionId) } diff --git a/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStore.kt b/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStore.kt index af35ac3c44..1a14a0ea8f 100644 --- a/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStore.kt +++ b/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStore.kt @@ -8,6 +8,7 @@ package io.element.android.libraries.preferences.impl.store +import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey @@ -36,6 +37,7 @@ private val timelineMediaPreviewValueKey = stringPreferencesKey("timelineMediaPr private val liveLocationMinimumDistanceUpdateKey = intPreferencesKey("liveLocationMinimumDistanceUpdate") private val logLevelKey = stringPreferencesKey("logLevel") private val traceLogPacksKey = stringPreferencesKey("traceLogPacks") +private val homeserverHistoryKey = stringPreferencesKey("homeserverHistory") private val messageSoundUriKey = stringPreferencesKey("notificationMessageSoundUri") private val messageSoundChannelVersionKey = intPreferencesKey("notificationMessageSoundChannelVersion") private val messageSoundDisplayNameKey = stringPreferencesKey("notificationMessageSoundDisplayName") @@ -43,6 +45,10 @@ private val callRingtoneUriKey = stringPreferencesKey("notificationCallRingtoneU private val callRingtoneChannelVersionKey = intPreferencesKey("notificationCallRingtoneChannelVersion") private val callRingtoneDisplayNameKey = stringPreferencesKey("notificationCallRingtoneDisplayName") +// URLs never contain a newline, so it is a safe delimiter to persist an ordered list in a single String. +private const val HOMESERVER_HISTORY_DELIMITER = "\n" +private const val MAX_HOMESERVER_HISTORY_SIZE = 20 + @ContributesBinding(AppScope::class) class DefaultAppPreferencesStore( private val buildMeta: BuildMeta, @@ -168,6 +174,20 @@ class DefaultAppPreferencesStore( } } + override fun getHomeserverHistoryFlow(): Flow> { + return store.data.map { prefs -> prefs.readHomeserverHistory() } + } + + override suspend fun addHomeserverToHistory(url: String) { + val normalized = url.trim().lowercase() + if (normalized.isEmpty()) return + store.edit { prefs -> + val updated = (listOf(normalized) + prefs.readHomeserverHistory().filter { it != normalized }) + .take(MAX_HOMESERVER_HISTORY_SIZE) + prefs[homeserverHistoryKey] = updated.joinToString(HOMESERVER_HISTORY_DELIMITER) + } + } + override fun getMessageSoundFlow(): Flow { return store.data.map { prefs -> NotificationSound.fromStored(prefs[messageSoundUriKey]) } } @@ -242,6 +262,13 @@ class DefaultAppPreferencesStore( } } +private fun Preferences.readHomeserverHistory(): List { + return this[homeserverHistoryKey] + ?.split(HOMESERVER_HISTORY_DELIMITER) + ?.filter { it.isNotEmpty() } + ?: emptyList() +} + private fun BuildMeta.defaultLogLevel(): LogLevel { return when (buildType) { BuildType.DEBUG -> LogLevel.TRACE diff --git a/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/SessionPreferencesModule.kt b/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/di/SessionPreferencesBindingContainer.kt similarity index 84% rename from libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/SessionPreferencesModule.kt rename to libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/di/SessionPreferencesBindingContainer.kt index 43de0b5a62..396c3c7bc0 100644 --- a/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/SessionPreferencesModule.kt +++ b/libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/di/SessionPreferencesBindingContainer.kt @@ -6,7 +6,7 @@ * Please see LICENSE files in the repository root for full details. */ -package io.element.android.libraries.preferences.impl.store +package io.element.android.libraries.preferences.impl.store.di import dev.zacsweers.metro.BindingContainer import dev.zacsweers.metro.ContributesTo @@ -15,11 +15,12 @@ import io.element.android.libraries.di.SessionScope import io.element.android.libraries.di.annotations.SessionCoroutineScope import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.preferences.api.store.SessionPreferencesStore +import io.element.android.libraries.preferences.impl.store.DefaultSessionPreferencesStoreFactory import kotlinx.coroutines.CoroutineScope @BindingContainer @ContributesTo(SessionScope::class) -object SessionPreferencesModule { +object SessionPreferencesBindingContainer { @Provides fun providesSessionPreferencesStore( defaultSessionPreferencesStoreFactory: DefaultSessionPreferencesStoreFactory, diff --git a/libraries/preferences/impl/src/test/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStoreTest.kt b/libraries/preferences/impl/src/test/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStoreTest.kt index c52d1648ac..4cf018371a 100644 --- a/libraries/preferences/impl/src/test/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStoreTest.kt +++ b/libraries/preferences/impl/src/test/kotlin/io/element/android/libraries/preferences/impl/store/DefaultAppPreferencesStoreTest.kt @@ -54,4 +54,74 @@ class DefaultAppPreferencesStoreTest { assertThat(store.getLiveLocationMinimumDistanceInMetersUpdateFlow().first()).isEqualTo(25) } + + @Test + fun `homeserver history is empty by default`() = runTest { + val store = createStore() + assertThat(store.getHomeserverHistoryFlow().first()).isEmpty() + } + + @Test + fun `adding homeservers keeps the most recent first`() = runTest { + val store = createStore() + + store.addHomeserverToHistory("https://matrix.org") + store.addHomeserverToHistory("https://example.com") + + assertThat(store.getHomeserverHistoryFlow().first()) + .containsExactly("https://example.com", "https://matrix.org") + .inOrder() + } + + @Test + fun `adding an existing homeserver moves it to the front without duplicating`() = runTest { + val store = createStore() + + store.addHomeserverToHistory("https://matrix.org") + store.addHomeserverToHistory("https://example.com") + store.addHomeserverToHistory("https://matrix.org") + + assertThat(store.getHomeserverHistoryFlow().first()) + .containsExactly("https://matrix.org", "https://example.com") + .inOrder() + } + + @Test + fun `homeservers are normalised and deduplicated case-insensitively`() = runTest { + val store = createStore() + + store.addHomeserverToHistory(" HTTPS://Matrix.ORG ") + store.addHomeserverToHistory("https://matrix.org") + + assertThat(store.getHomeserverHistoryFlow().first()) + .containsExactly("https://matrix.org") + } + + @Test + fun `blank homeservers are ignored`() = runTest { + val store = createStore() + + store.addHomeserverToHistory(" ") + + assertThat(store.getHomeserverHistoryFlow().first()).isEmpty() + } + + @Test + fun `homeserver history is capped to the most recent entries`() = runTest { + val store = createStore() + + repeat(25) { index -> + store.addHomeserverToHistory("https://server$index.org") + } + + val history = store.getHomeserverHistoryFlow().first() + assertThat(history).hasSize(20) + assertThat(history.first()).isEqualTo("https://server24.org") + assertThat(history.last()).isEqualTo("https://server5.org") + } + + private fun createStore() = DefaultAppPreferencesStore( + buildMeta = buildMeta, + preferenceDataStoreFactory = FakePreferenceDataStoreFactory(), + ) } diff --git a/libraries/preferences/test/src/main/kotlin/io/element/android/libraries/preferences/test/InMemoryAppPreferencesStore.kt b/libraries/preferences/test/src/main/kotlin/io/element/android/libraries/preferences/test/InMemoryAppPreferencesStore.kt index 6499e70223..e8d0b0bb8e 100644 --- a/libraries/preferences/test/src/main/kotlin/io/element/android/libraries/preferences/test/InMemoryAppPreferencesStore.kt +++ b/libraries/preferences/test/src/main/kotlin/io/element/android/libraries/preferences/test/InMemoryAppPreferencesStore.kt @@ -16,6 +16,7 @@ import io.element.android.libraries.preferences.api.store.NotificationSound import io.element.android.libraries.preferences.api.store.NotificationSoundChannelConfig import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.updateAndGet class InMemoryAppPreferencesStore( @@ -27,6 +28,7 @@ class InMemoryAppPreferencesStore( liveLocationMinimumDistanceUpdate: Int = 10, logLevel: LogLevel = LogLevel.INFO, traceLogPacks: Set = emptySet(), + homeserverHistory: List = emptyList(), messageSound: NotificationSound = NotificationSound.SystemDefault, messageSoundChannelVersion: Int = 0, messageSoundDisplayName: String? = null, @@ -40,6 +42,7 @@ class InMemoryAppPreferencesStore( private val liveLocationMinimumDistanceUpdate = MutableStateFlow(liveLocationMinimumDistanceUpdate) private val logLevel = MutableStateFlow(logLevel) private val tracingLogPacks = MutableStateFlow(traceLogPacks) + private val homeserverHistory = MutableStateFlow(homeserverHistory) private val hideInviteAvatars = MutableStateFlow(hideInviteAvatars) private val timelineMediaPreviewValue = MutableStateFlow(timelineMediaPreviewValue) private val messageSound = MutableStateFlow(messageSound) @@ -117,6 +120,18 @@ class InMemoryAppPreferencesStore( return tracingLogPacks } + override fun getHomeserverHistoryFlow(): Flow> { + return homeserverHistory + } + + override suspend fun addHomeserverToHistory(url: String) { + val normalized = url.trim().lowercase() + if (normalized.isEmpty()) return + homeserverHistory.update { current -> + (listOf(normalized) + current.filter { it != normalized }).take(10) + } + } + override fun getMessageSoundFlow(): Flow { return messageSound } diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/GetCurrentPushProvider.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/GetCurrentPushProvider.kt index a6fbb47173..eb2ce09545 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/GetCurrentPushProvider.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/GetCurrentPushProvider.kt @@ -10,6 +10,16 @@ package io.element.android.libraries.push.api import io.element.android.libraries.matrix.api.core.SessionId +/** + * Reads the name of the push provider a session is currently registered with. + * + * This is the low-level accessor used where depending on the whole push feature would be too much; prefer [PushService.getCurrentPushProvider] otherwise. + */ interface GetCurrentPushProvider { + /** + * Returns the stored provider name, or `null` when the session has no push provider selected yet. + * + * @param sessionId the session to read the provider of. + */ suspend fun getCurrentPushProvider(sessionId: SessionId): String? } diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/PushService.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/PushService.kt index a43ee36403..4a5037d17f 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/PushService.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/PushService.kt @@ -16,9 +16,14 @@ import io.element.android.libraries.pushproviders.api.Distributor import io.element.android.libraries.pushproviders.api.PushProvider import kotlinx.coroutines.flow.Flow +/** + * Entry point for push notification setup: choosing a push provider, registering a pusher with the homeserver, and inspecting the push history. + */ interface PushService { /** * Return the current push provider, or null if none. + * + * @param sessionId the session to read the provider of. */ suspend fun getCurrentPushProvider(sessionId: SessionId): PushProvider? @@ -31,6 +36,10 @@ interface PushService { * Will unregister any previous pusher and register a new one with the provided [PushProvider]. * * The method has effect only if the [PushProvider] is different than the current one. + * + * @param matrixClient the session to register the pusher for. + * @param pushProvider the provider to switch to. + * @param distributor the distributor of that provider to use, which matters for providers such as UnifiedPush. */ suspend fun registerWith( matrixClient: MatrixClient, @@ -42,6 +51,8 @@ interface PushService { * Ensure that the pusher with the current push provider and distributor is registered. * If there is no current config, the default push provider with the default distributor will be used. * Error can be [PusherRegistrationFailure]. + * + * @param matrixClient the session to ensure the pusher of. */ suspend fun ensurePusherIsRegistered( matrixClient: MatrixClient, @@ -50,17 +61,35 @@ interface PushService { /** * Store the given push provider as the current one, but do not register. * To be used when there is no distributor available. + * + * @param sessionId the session to store the provider for. + * @param pushProvider the provider to remember. */ suspend fun selectPushProvider( sessionId: SessionId, pushProvider: PushProvider, ) + /** + * Whether the user has asked not to be warned about pusher registration failures for this session. + * + * @param sessionId the session to read the preference of. + */ fun ignoreRegistrationError(sessionId: SessionId): Flow + + /** + * Remembers whether pusher registration failures should be reported to the user for this session. + * + * @param sessionId the session to store the preference for. + * @param ignore true to stop warning the user about registration failures. + */ suspend fun setIgnoreRegistrationError(sessionId: SessionId, ignore: Boolean) /** + * Asks the homeserver to send a test push, so the user can check that the whole chain works. * Return false in case of early error. + * + * @param sessionId the session to test the push setup of. */ suspend fun testPush(sessionId: SessionId): Boolean @@ -86,6 +115,8 @@ interface PushService { /** * Notify the user that the service is un-registered. + * + * @param userId the user whose push service is no longer registered. */ suspend fun onServiceUnregistered(userId: UserId) } diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/gateway/PushGatewayFailure.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/gateway/PushGatewayFailure.kt index 975e10e134..3bf065550d 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/gateway/PushGatewayFailure.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/gateway/PushGatewayFailure.kt @@ -10,4 +10,9 @@ package io.element.android.libraries.push.api.gateway sealed class PushGatewayFailure : Exception() { class PusherRejected : PushGatewayFailure() + + /** + * The gateway refused the notification because too many were sent to it. + */ + class RateLimited : PushGatewayFailure() } diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationBitmapLoader.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationBitmapLoader.kt index bded69991b..9dd53ade09 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationBitmapLoader.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationBitmapLoader.kt @@ -14,6 +14,9 @@ import coil3.ImageLoader import io.element.android.libraries.designsystem.components.avatar.AvatarData import io.element.android.libraries.matrix.ui.media.AVATAR_THUMBNAIL_SIZE_IN_PIXEL +/** + * Loads the avatars used to decorate notifications, since the notification APIs need bitmaps rather than Compose images. + */ interface NotificationBitmapLoader { /** * Get icon of a room. diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationCleaner.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationCleaner.kt index 0a4e35c697..95966f8eb1 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationCleaner.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationCleaner.kt @@ -13,12 +13,56 @@ import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.matrix.api.core.ThreadId +/** + * Dismisses notifications that are already displayed, typically because the user has now seen the events elsewhere. + * + * Every method also removes the grouping summary notification when it is left without children. + */ interface NotificationCleaner { + /** + * Dismisses every message notification of a session. + * + * @param sessionId the session whose notifications are dismissed. + */ fun clearAllMessagesEvents(sessionId: SessionId) + + /** + * Dismisses the message notifications of one room. + * + * @param sessionId the session the room belongs to. + * @param roomId the room whose notifications are dismissed. + */ fun clearMessagesForRoom(sessionId: SessionId, roomId: RoomId) + + /** + * Dismisses the message notifications of one thread, leaving the rest of the room's notifications in place. + * + * @param sessionId the session the room belongs to. + * @param roomId the room the thread belongs to. + * @param threadId the thread whose notifications are dismissed. + */ fun clearMessagesForThread(sessionId: SessionId, roomId: RoomId, threadId: ThreadId) + + /** + * Dismisses the notification of a single event. + * + * @param sessionId the session the event belongs to. + * @param eventId the event whose notification is dismissed. + */ fun clearEvent(sessionId: SessionId, eventId: EventId) + /** + * Dismisses every membership notification of a session, i.e. the invitations and the join requests. + * + * @param sessionId the session whose notifications are dismissed. + */ fun clearMembershipNotificationForSession(sessionId: SessionId) + + /** + * Dismisses the membership notifications of one room. + * + * @param sessionId the session the room belongs to. + * @param roomId the room whose notifications are dismissed. + */ fun clearMembershipNotificationForRoom(sessionId: SessionId, roomId: RoomId) } diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationSoundUpdater.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationSoundUpdater.kt index b23c4122ad..91f50abc07 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationSoundUpdater.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/NotificationSoundUpdater.kt @@ -14,8 +14,20 @@ import io.element.android.libraries.preferences.api.store.NotificationSound * versioned channel because Android forbids mutating sound after creation. */ interface NotificationSoundUpdater { + /** + * Recreates the message notification channel so it uses [sound]. + * + * @param sound the sound the new channel should play. + * @param version bumped on every change, since a new channel id is the only way to change a channel's sound. + */ fun recreateNoisyChannel(sound: NotificationSound, version: Int) + /** + * Recreates the ringing call notification channel so it uses [sound]; see [recreateNoisyChannel] for why a version is needed. + * + * @param sound the sound the new channel should play. + * @param version bumped on every change to force a new channel id. + */ fun recreateRingingCallChannel(sound: NotificationSound, version: Int) /** Current channel sound classified into [NotificationSound]. Null when the channel doesn't exist. */ diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/OnMissedCallNotificationHandler.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/OnMissedCallNotificationHandler.kt index 2ba61925c5..d4e051ebf2 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/OnMissedCallNotificationHandler.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/OnMissedCallNotificationHandler.kt @@ -18,6 +18,10 @@ import io.element.android.libraries.matrix.api.core.SessionId interface OnMissedCallNotificationHandler { /** * Adds a missed call notification. + * + * @param sessionId the session the call was received on. + * @param roomId the room the call took place in. + * @param eventId the call notification event that went unanswered. */ suspend fun addMissedCallNotification( sessionId: SessionId, diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/conversations/NotificationConversationService.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/conversations/NotificationConversationService.kt index 4ea80e4ce8..b3bffc0147 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/conversations/NotificationConversationService.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/conversations/NotificationConversationService.kt @@ -18,6 +18,12 @@ interface NotificationConversationService { /** * Called when a new message is received in a room. * It should create a new conversation shortcut for this room. + * + * @param sessionId the session the message belongs to. + * @param roomId the room the message was received in. + * @param roomName the name to show on the shortcut, or `null` when the room has none. + * @param roomIsDirect whether the room is a direct message, which changes how the shortcut is presented. + * @param roomAvatarUrl the avatar to show on the shortcut, or `null` when the room has none. */ suspend fun onSendMessage( sessionId: SessionId, @@ -30,12 +36,18 @@ interface NotificationConversationService { /** * Called when a room is left. * It should remove the conversation shortcut for this room. + * + * @param sessionId the session the room belongs to. + * @param roomId the room that was left. */ suspend fun onLeftRoom(sessionId: SessionId, roomId: RoomId) /** * Called when the list of available rooms changes. * It should update the conversation shortcuts accordingly, removing shortcuts for no longer joined rooms. + * + * @param sessionId the session the rooms belong to. + * @param roomIds the rooms the user is currently joined to. */ suspend fun onAvailableRoomsChanged(sessionId: SessionId, roomIds: Set) } diff --git a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/sound/NotificationSoundCopier.kt b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/sound/NotificationSoundCopier.kt index 2268198353..ad3d73656f 100644 --- a/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/sound/NotificationSoundCopier.kt +++ b/libraries/push/api/src/main/kotlin/io/element/android/libraries/push/api/notifications/sound/NotificationSoundCopier.kt @@ -12,6 +12,12 @@ package io.element.android.libraries.push.api.notifications.sound * FileProvider, so the persisted reference outlives the original source. */ interface NotificationSoundCopier { + /** + * Copies the picked sound into app-private storage, replacing any file previously stored for [slot]. + * + * @param sourceUriString the uri of the sound the user picked. + * @param slot which of the two sounds is being set, since each keeps its own copy. + */ suspend fun copyToAppFiles(sourceUriString: String, slot: SoundSlot): CopyResult /** diff --git a/libraries/push/impl/build.gradle.kts b/libraries/push/impl/build.gradle.kts index b9082c50f6..8615485bba 100644 --- a/libraries/push/impl/build.gradle.kts +++ b/libraries/push/impl/build.gradle.kts @@ -1,3 +1,5 @@ +import config.BuildTimeConfig +import extension.buildConfigFieldStr import extension.setupDependencyInjection import extension.testCommonDependencies @@ -17,6 +19,33 @@ plugins { android { namespace = "io.element.android.libraries.push.impl" + buildFeatures { + buildConfig = true + } + + buildTypes { + val defaultPusherAppId = "im.vector.app.android" + getByName("release") { + buildConfigFieldStr( + name = "PUSHER_APP_ID", + value = BuildTimeConfig.PUSHER_APP_ID_RELEASE ?: defaultPusherAppId, + ) + } + getByName("debug") { + buildConfigFieldStr( + name = "PUSHER_APP_ID", + value = BuildTimeConfig.PUSHER_APP_ID_DEBUG ?: defaultPusherAppId, + ) + } + register("nightly") { + matchingFallbacks += listOf("release") + buildConfigFieldStr( + name = "PUSHER_APP_ID", + value = BuildTimeConfig.PUSHER_APP_ID_NIGHTLY ?: defaultPusherAppId, + ) + } + } + testOptions { unitTests { isIncludeAndroidResources = true diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriber.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriber.kt index 35482aa164..7aa519a791 100644 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriber.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriber.kt @@ -10,7 +10,6 @@ package io.element.android.libraries.push.impl import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding -import io.element.android.appconfig.PushConfig import io.element.android.libraries.core.extensions.mapFailure import io.element.android.libraries.core.log.logger.LoggerTag import io.element.android.libraries.core.meta.BuildMeta @@ -74,7 +73,7 @@ class DefaultPusherSubscriber( ): SetHttpPusherData = SetHttpPusherData( pushKey = pushKey, - appId = PushConfig.PUSHER_APP_ID, + appId = BuildConfig.PUSHER_APP_ID, // TODO + abs(activeSessionHolder.getActiveSession().myUserId.hashCode()) profileTag = DEFAULT_PUSHER_FILE_TAG + "_", // TODO localeProvider.current().language @@ -104,7 +103,7 @@ class DefaultPusherSubscriber( .unsetHttpPusher( unsetHttpPusherData = UnsetHttpPusherData( pushKey = pushKey, - appId = PushConfig.PUSHER_APP_ID + appId = BuildConfig.PUSHER_APP_ID ) ) .onSuccess { diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/di/PushModule.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/di/PushBindingContainer.kt similarity index 88% rename from libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/di/PushModule.kt rename to libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/di/PushBindingContainer.kt index b7e807523c..2274232406 100644 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/di/PushModule.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/di/PushBindingContainer.kt @@ -22,10 +22,10 @@ import io.element.android.libraries.push.impl.battery.BatteryOptimizationPresent @BindingContainer @ContributesTo(AppScope::class) -interface PushModule { +interface PushBindingContainer { companion object { @Provides - fun provideNotificationCompatManager(@ApplicationContext context: Context): NotificationManagerCompat { + fun providesNotificationManagerCompat(@ApplicationContext context: Context): NotificationManagerCompat { return NotificationManagerCompat.from(context) } } diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/history/di/PushHistoryModule.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/history/di/PushHistoryBindingContainer.kt similarity index 96% rename from libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/history/di/PushHistoryModule.kt rename to libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/history/di/PushHistoryBindingContainer.kt index 93194b2738..f50b221c58 100644 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/history/di/PushHistoryModule.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/history/di/PushHistoryBindingContainer.kt @@ -23,10 +23,10 @@ import timber.log.Timber @BindingContainer @ContributesTo(AppScope::class) -object PushHistoryModule { +object PushHistoryBindingContainer { @Provides @SingleIn(AppScope::class) - fun providePushDatabase( + fun providesPushDatabase( @ApplicationContext context: Context, ): PushDatabase { val name = "push_database" diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolver.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolver.kt index abbda10a3c..fdffad3049 100644 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolver.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolver.kt @@ -36,6 +36,7 @@ import io.element.android.libraries.matrix.api.media.isPreviewEnabled import io.element.android.libraries.matrix.api.notification.NotificationContent import io.element.android.libraries.matrix.api.notification.NotificationData import io.element.android.libraries.matrix.api.permalink.PermalinkParser +import io.element.android.libraries.matrix.api.room.RoomMembershipState import io.element.android.libraries.matrix.api.room.join.JoinRule import io.element.android.libraries.matrix.api.timeline.item.event.AudioMessageType import io.element.android.libraries.matrix.api.timeline.item.event.EmoteMessageType @@ -56,6 +57,7 @@ import io.element.android.libraries.push.impl.db.PushRequest import io.element.android.libraries.push.impl.notifications.model.InviteNotifiableEvent import io.element.android.libraries.push.impl.notifications.model.NotifiableMessageEvent import io.element.android.libraries.push.impl.notifications.model.ResolvedPushEvent +import io.element.android.libraries.sessionstorage.api.SessionStore import io.element.android.libraries.ui.strings.CommonStrings import io.element.android.services.toolbox.api.strings.StringProvider import timber.log.Timber @@ -94,6 +96,7 @@ class DefaultNotifiableEventResolver( private val callNotificationEventResolver: CallNotificationEventResolver, private val fallbackNotificationFactory: FallbackNotificationFactory, private val featureFlagService: FeatureFlagService, + private val sessionStore: SessionStore, ) : NotifiableEventResolver { override suspend fun resolveEvents( sessionId: SessionId, @@ -117,10 +120,15 @@ class DefaultNotifiableEventResolver( return Result.failure(exception ?: NotificationResolverException.UnknownError("Unknown error while fetching notifications")) } + val otherSessionUserIds = sessionStore.getAllSessions() + .map { UserId(it.userId) } + .minus(sessionId) + .toSet() + // The null check is done above val notificationDataMap = notificationsResult.getOrNull()!!.mapValues { (_, notificationData) -> notificationData.flatMap { data -> - data.asNotifiableEvent(client, sessionId) + data.asNotifiableEvent(client, sessionId, otherSessionUserIds) } } @@ -136,10 +144,23 @@ class DefaultNotifiableEventResolver( ) } + private fun NotificationContent.senderIdOrNull(): UserId? = when (this) { + is NotificationContent.MessageLike.RoomMessage -> senderId + is NotificationContent.MessageLike.Poll -> senderId + is NotificationContent.MessageLike.CallInvite -> senderId + is NotificationContent.MessageLike.RtcNotification -> senderId + is NotificationContent.Invite -> senderId + else -> null + } + private suspend fun NotificationData.asNotifiableEvent( client: MatrixClient, userId: SessionId, + otherSessionUserIds: Set, ): Result = runCatchingExceptions { + if (content.senderIdOrNull() in otherSessionUserIds) { + throw NotificationResolverException.EventFilteredOut + } when (val content = this.content) { is NotificationContent.MessageLike.RoomMessage -> { val showMediaPreview = client.mediaPreviewService.getMediaPreviewValue().isPreviewEnabled(roomJoinRule) @@ -284,8 +305,8 @@ class DefaultNotifiableEventResolver( // Note: this case will be handled below val redactedEventId = content.redactedEventId if (redactedEventId == null) { - Timber.tag(loggerTag.value).d("redactedEventId is null.") - throw NotificationResolverException.UnknownError("redactedEventId is null") + Timber.tag(loggerTag.value).w("Ignoring redaction notification with no redactedEventId.") + throw NotificationResolverException.EventFilteredOut } else { ResolvedPushEvent.Redaction( sessionId = userId, @@ -299,6 +320,29 @@ class DefaultNotifiableEventResolver( Timber.tag(loggerTag.value).d("Ignoring notification for sticker") throw NotificationResolverException.EventFilteredOut } + is NotificationContent.StateEvent.RoomMemberContent -> { + // MSC4506: the homeserver pushes knocks to users who can act on them. + if (content.membershipState == RoomMembershipState.KNOCK) { + val notifiableMessageEvent = buildNotifiableMessageEvent( + sessionId = userId, + senderId = content.userId, + roomId = roomId, + eventId = eventId, + noisy = isNoisy, + timestamp = this.timestamp, + senderDisambiguatedDisplayName = getDisambiguatedDisplayName(content.userId), + body = stringProvider.getString(R.string.notification_knock_request_body), + roomName = roomDisplayName, + roomIsDm = isDm, + roomAvatarPath = roomAvatarUrl, + senderAvatarPath = senderAvatarUrl, + ) + ResolvedPushEvent.Event(notifiableMessageEvent) + } else { + Timber.tag(loggerTag.value).d("Ignoring notification for membership ${content.membershipState}") + throw NotificationResolverException.EventFilteredOut + } + } NotificationContent.MessageLike.Beacon -> { Timber.tag(loggerTag.value).d("Ignoring notification for beacon") throw NotificationResolverException.EventFilteredOut @@ -321,7 +365,6 @@ class DefaultNotifiableEventResolver( ) ResolvedPushEvent.Event(notifiableEventMessage) } - is NotificationContent.StateEvent.RoomMemberContent, NotificationContent.StateEvent.PolicyRuleRoom, NotificationContent.StateEvent.PolicyRuleServer, NotificationContent.StateEvent.PolicyRuleUser, diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/factories/NotificationCreator.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/factories/NotificationCreator.kt index 44a9b5ca30..afbbe4af4f 100755 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/factories/NotificationCreator.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/notifications/factories/NotificationCreator.kt @@ -196,11 +196,12 @@ class DefaultNotificationCreator( isThread = threadId != null, roomIsGroup = !roomInfo.isDm, ) - messagingStyle.addMessagesFromEvents(events, imageLoader) + val newEvents = messagingStyle.filterOutAlreadyDisplayedEvents(events) + messagingStyle.addMessagesFromEvents(newEvents, imageLoader) return builder .setCategory(category) .setNumber(events.size) - .setOnlyAlertOnce(roomInfo.isUpdated) + .setOnlyAlertOnce(roomInfo.isUpdated || newEvents.isEmpty()) .setWhen(lastMessageTimestamp) // MESSAGING_STYLE sets title and content for API 16 and above devices. .setStyle(messagingStyle) @@ -416,6 +417,15 @@ class DefaultNotificationCreator( .build() } + private fun MessagingStyle.filterOutAlreadyDisplayedEvents( + events: List, + ): List { + val displayedEventIds = messages.mapNotNullTo(mutableSetOf()) { it.extras.getString(MESSAGE_EVENT_ID) } + return events.filter { event -> + event.isSmartReplyError() || displayedEventIds.add(event.eventId.value) + } + } + private suspend fun MessagingStyle.addMessagesFromEvents( events: List, imageLoader: ImageLoader, diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/pushgateway/PushGatewayNotifyRequest.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/pushgateway/PushGatewayNotifyRequest.kt index 6315285559..e3a7968909 100644 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/pushgateway/PushGatewayNotifyRequest.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/pushgateway/PushGatewayNotifyRequest.kt @@ -12,6 +12,7 @@ import dev.zacsweers.metro.ContributesBinding import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomId import io.element.android.libraries.push.api.gateway.PushGatewayFailure +import retrofit2.HttpException interface PushGatewayNotifyRequest { data class Params( @@ -33,26 +34,38 @@ class DefaultPushGatewayNotifyRequest( val pushGatewayApi = pushGatewayApiFactory.create( params.url.substringBefore(PushGatewayConfig.URI_PUSH_GATEWAY_PREFIX_PATH) ) - val response = pushGatewayApi.notify( - PushGatewayNotifyBody( - PushGatewayNotification( - eventId = params.eventId.value, - roomId = params.roomId.value, - devices = listOf( - PushGatewayDevice( - params.appId, - params.pushKey, - PusherData(mapOf( - "cs" to "A_FAKE_SECRET", - )) - ) - ), + val response = try { + pushGatewayApi.notify( + PushGatewayNotifyBody( + PushGatewayNotification( + eventId = params.eventId.value, + roomId = params.roomId.value, + devices = listOf( + PushGatewayDevice( + params.appId, + params.pushKey, + PusherData(mapOf( + "cs" to "A_FAKE_SECRET", + )) + ) + ), + ) ) ) - ) + } catch (httpException: HttpException) { + if (httpException.code() in RATE_LIMITED_STATUS_CODES) { + throw PushGatewayFailure.RateLimited() + } + throw httpException + } if (response.rejectedPushKeys.contains(params.pushKey)) { throw PushGatewayFailure.PusherRejected() } } } + +/** + * 429 is the standard answer, ntfy answers 507 when a device is over its message quota. + */ +private val RATE_LIMITED_STATUS_CODES = setOf(429, 507) diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/test/TestPush.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/test/TestPush.kt index 4ed8ca8338..6921c050db 100644 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/test/TestPush.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/test/TestPush.kt @@ -10,9 +10,9 @@ package io.element.android.libraries.push.impl.test import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding -import io.element.android.appconfig.PushConfig import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.core.RoomId +import io.element.android.libraries.push.impl.BuildConfig import io.element.android.libraries.push.impl.pushgateway.PushGatewayNotifyRequest import io.element.android.libraries.pushproviders.api.Config @@ -28,7 +28,7 @@ class DefaultTestPush( pushGatewayNotifyRequest.execute( PushGatewayNotifyRequest.Params( url = config.url, - appId = PushConfig.PUSHER_APP_ID, + appId = BuildConfig.PUSHER_APP_ID, pushKey = config.pushKey, eventId = TEST_EVENT_ID, roomId = TEST_ROOM_ID, diff --git a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTest.kt b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTest.kt index bc89d031a8..0277d7d2c8 100644 --- a/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTest.kt +++ b/libraries/push/impl/src/main/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTest.kt @@ -62,6 +62,13 @@ class PushLoopbackTest( ) job.cancel() return + } catch (_: PushGatewayFailure.RateLimited) { + delegate.updateState( + description = stringProvider.getString(R.string.troubleshoot_notifications_test_push_loop_back_failure_rate_limit), + status = NotificationTroubleshootTestState.Status.Failure() + ) + job.cancel() + return } catch (e: Exception) { Timber.e(e, "Failed to test push") delegate.updateState( diff --git a/libraries/push/impl/src/main/res/values-ar/translations.xml b/libraries/push/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..7b8e847c72 --- /dev/null +++ b/libraries/push/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,140 @@ + + + "إتصال" + "الاستماع إلى الأحداث" + "إشعارات الصاخبة" + "رنين المكالمات" + "إشعارات صامتة" + + "%1$s: %2$d رسائل" + "%1$s: %2$d رسالة" + "%1$s: %2$d رسالتان" + "%1$s: %2$d رسائل" + "%1$s: %2$d رسالة" + "%1$s: %2$d رسالة" + + + "%d إشعارات" + "%d إشعار" + "%d إشعاران" + "%d إشعارات" + "%d إشعار" + "%d إشعار" + + "تعذّر تسجيل موزّع إشعارات UnifiedPush، لذلك لن تتلقى إشعارات بعد الآن. يرجى التحقق من إعدادات إشعارات التطبيق وحالة موزّع الإشعارات الفورية." + "أتتك رسائل جديدة." + + "لديك %d رسائل جديدة." + "لديك %d رسالة جديدة." + "لديك %d رسالتان جديدتان." + "لديك %d رسائل جديدة." + "لديك %d رسالة جديدة." + "لديك %d رسالة جديدة." + + "📞 مكالمة واردة" + "📹 مكالمة واردة" + "** فشل الإرسال - يرجى فتح الغرفة" + "إنضمام" + "رفض" + + "%d دعوة" + "%d دعوة" + "%d دعوات" + "%d دعوات" + "%d دعوات" + "%d دعوات" + + "دعاك للتحدث" + "دعاك %1$s إلى الدردشة" + "طلبت الإنضمام" + "ذكرك: %1$s" + "رسائل جديدة" + + "%d رسالة جديدة" + "%d رسالة جديدة" + "%d من الرسائل الجديدة" + "%d من الرسائل الجديدة" + "%d من الرسائل الجديدة" + "%d من الرسائل الجديدة" + + "تفاعلت بـ %1$s" + "وضع علامة كمقروء" + "رد سريع " + "دعاك للانضمام للغرفة" + "دعاك %1$s للانضمام إلى الغرفة" + "أنا" + "إشارة أو رد من %1$s" + "دعاك للانضمام إلى المساحة" + "دعاك %1$s للانضمام إلى المساحة" + "إنك ترى الإشعارات! اضغط عليّ!" + "سلسلة في %1$s" + "%1$s:%2$s" + "%1$s:%2$s:%3$s" + + "%d رسالة مُعلَمة لم تُقرأ" + "%d رسالة مُعلَمة لم تُقرأ" + "%d من الرسائل المُعلَمة لم تُقرأ" + "%d من الرسائل المُعلَمة لم تُقرأ" + "%d من الرسائل المُعلَمة لم تُقرأ" + "%d من الرسائل المُعلَمة لم تُقرأ" + + "%1$s و %2$s" + "%1$s في %2$s" + "%1$s في %2$s و %3$s" + + "%d غرفة" + "%d غرفة" + "%d من الغرف" + "%d من الغرف" + "%d من الغرف" + "%d من الغرف" + + "المزامنة في الخلفية" + "خدمات Google" + "لم يتم العثور على خدمات Google صالحة. الإشعارات قد لا تعمل كما يجب." + "التحقق من المستخدمين المحظورين" + "عرض المستخدمين المحظورين" + "لا يوجد مستخدمون محظورون." + + "لقد حظرت %1$d مستخدمين. لن تتلقى إشعارات لهؤلاء المستخدمين." + "لقد حظرت %1$d مستخدم. لن تتلقى إشعارات لهذا المستخدم." + "لقد حظرت %1$d مستخدمين. لن تتلقى إشعارات لهذين المستخدمين." + "لقد حظرت %1$d مستخدمين. لن تتلقى إشعارات لهؤلاء المستخدمين." + "لقد حظرت %1$d مستخدمًا. لن تتلقى إشعارات لهؤلاء المستخدمين." + "لقد حظرت %1$d مستخدم. لن تتلقى إشعارات لهؤلاء المستخدمين." + + "المستخدمون المحظورون" + "يحصل على اسم الموفّر الحالي." + "لم يتم تحديد أي موفّر إشعارات فورية." + "موفّر الإشعارات الفورية الحالي: %1$s والموزّع الحالي: %2$s. لكن لم يتم العثور على الموزّع %3$s. ربما تم إلغاء تثبيت التطبيق؟" + "موفّر الإشعارات الفورية الحالي: %1$s، لكن لم يتم إعداد أي موزّعين." + "موفّر الإشعارات الفورية الحالي: %1$s." + "موفّر الإشعارات الفورية الحالي: %1$s (%2$s)" + "موفّر الإشعارات الفورية الحالي" + "يتحقق من أن التطبيق يدعم موفّر إشعارات فورية واحدًا على الأقل." + "لم يتم العثور على دعم لأي موفّر إشعارات فورية." + + "تم العثور على %1$d من موفّري الإشعارات الفورية: %2$s" + "تم العثور على %1$d موفّر إشعارات فورية: %2$s" + "تم العثور على %1$d من موفّري الإشعارات الفورية: %2$s" + "تم العثور على %1$d من موفّري الإشعارات الفورية: %2$s" + "تم العثور على %1$d من موفّري الإشعارات الفورية: %2$s" + "تم العثور على %1$d من موفّري الإشعارات الفورية: %2$s" + + "تم إنشاء التطبيق بدعم لـ: %1$s" + "دعم موفّر الإشعارات الفورية" + "يتحقق من قدرة التطبيق على عرض إشعار." + "لم يتم النقر على الإشعار." + "تعذّر عرض الإشعار." + "تم النقر على الإشعار!" + "عرض إشعار" + "يرجى النقر على الإشعار لمتابعة الاختبار." + "يتحقق من أن التطبيق يستقبل الإشعارات الفورية." + "خطأ: رفض موفّر الإشعارات الفورية الطلب." + "خطأ: %1$s." + "خطأ، تعذّر اختبار الإشعارات الفورية." + "خطأ، انتهت مهلة انتظار الإشعار الفوري." + "خطأ: بوابة الإشعارات الفورية تفرض قيودًا على معدّل استخدام هذا الجهاز، لذا لن تكون الإشعارات موثوقة. يُرجى إعداد بوابة إشعارات فورية أخرى." + "استغرق اختبار إرسال واستقبال الإشعارات الفورية %1$d مللي ثانية." + "اختبار إرسال واستقبال الإشعارات الفورية" + diff --git a/libraries/push/impl/src/main/res/values-es/translations.xml b/libraries/push/impl/src/main/res/values-es/translations.xml index 412d32bfb6..b66e05be05 100644 --- a/libraries/push/impl/src/main/res/values-es/translations.xml +++ b/libraries/push/impl/src/main/res/values-es/translations.xml @@ -13,7 +13,17 @@ "%d notificación" "%d notificaciones" + "No se pudo registrar el distribuidor de notificaciones de UnifiedPush, así que no recibirás más notificaciones. Comprueba los ajustes de notificaciones de la aplicación y el estado del distribuidor de push." "Tienes nuevos mensajes." + + "Tienes %d mensaje nuevo." + "Tienes %d mensajes nuevos." + + + "Se ha compartido %1$d archivo adjunto" + "Se han compartido %1$d archivos adjuntos" + + "📞 Llamada entrante" "📹 Llamada entrante" "** No se ha podido enviar - por favor, abre la sala" "Unirse" @@ -24,6 +34,7 @@ "Te invitó a chatear" "%1$s te invitó a chatear" + "Comenzó a compartir su ubicación en tiempo real" "Te mencionó: %1$s" "Mensajes nuevos" @@ -37,7 +48,10 @@ "%1$s te invitó a unirte a la sala" "Yo" "%1$s mencionó o respondió" + "Te invitó a unirte al espacio" + "%1$s te invitó a unirte al espacio" "¡Estás viendo la notificación! ¡Haz clic en mí!" + "Hilo en %1$s" "%1$s: %2$s" "%1$s: %2$s %3$s" @@ -54,10 +68,20 @@ "Sincronización en segundo plano" "Servicios de Google" "No se han encontrado Servicios de Google Play válidos. Es posible que las notificaciones no funcionen correctamente." + "Comprobando usuarios bloqueados" + "Ver usuarios bloqueados" + "No hay usuarios bloqueados." + + "Has bloqueado %1$d usuario. No recibirás notificaciones de este usuario." + "Has bloqueado %1$d usuarios. No recibirás notificaciones de estos usuarios." + "Usuarios bloqueados" "Obtener el nombre del proveedor actual." "No se ha seleccionado ningún proveedor de push." + "Proveedor de push actual: %1$s y distribuidor actual: %2$s. Pero no se encuentra el distribuidor %3$s. ¿Quizás se ha desinstalado la aplicación?" + "Proveedor de push actual: %1$s, pero no se ha configurado ningún distribuidor." "Proveedor de push actual: %1$s." + "Proveedor de push actual: %1$s (%2$s)" "Proveedor de push actual" "Asegurarse de que la aplicación tiene al menos un proveedor de push." "No se encontró ningún proveedor de push." diff --git a/libraries/push/impl/src/main/res/values-et/translations.xml b/libraries/push/impl/src/main/res/values-et/translations.xml index 49010359cd..6b3d3f01d0 100644 --- a/libraries/push/impl/src/main/res/values-et/translations.xml +++ b/libraries/push/impl/src/main/res/values-et/translations.xml @@ -30,6 +30,7 @@ "Kutse osalema vestluses" "%1$s saatus sulle vestluskutse" + "Hakkas jagama oma asukohta reaalajas" "Mainis sind: %1$s" "Uued sõnumid" diff --git a/libraries/push/impl/src/main/res/values-fa/translations.xml b/libraries/push/impl/src/main/res/values-fa/translations.xml index 4afd68e17b..f1c70c7f08 100644 --- a/libraries/push/impl/src/main/res/values-fa/translations.xml +++ b/libraries/push/impl/src/main/res/values-fa/translations.xml @@ -13,7 +13,17 @@ "%dاعلان" "%dاعلان‌" + "توزیع‌کننده اعلان UnifiedPush قابل ثبت نیست، بنابراین دیگر اعلانی دریافت نخواهید کرد. لطفاً تنظیمات اعلان‌های برنامه و وضعیت توزیع‌کننده اعلان را بررسی کنید." "پیام‌های جدیدی دارید." + + "شما یک پیام جدید %d دارید." + "شما پیام‌های جدید %d دارید." + + + "پیوست %1$d مشترک" + "پیوست‌های %1$d مشترک" + + "📞 تماس ورودی" "📹 تماس ورودی" "**‌شکست در فرستادن - لطفاً اتاق را بگشایید" "پیوستن" @@ -24,6 +34,7 @@ "به گپ دعوتتان کرد" "%1$s به گپ دعوتتان کرد" + "شروع به اشتراک گذاری موقعیت مکانی زنده خود کردند" "به شما اشاره کرد: %1$s" "پیام جدید" @@ -37,7 +48,10 @@ "%1$s دعوت کرد به اتاق بپیوندید" "خودم" "%1$s اشاره کرد یا پاسخ داد" + "از شما دعوت شد تا به این فضا بپیوندید" + "%1$s از شما دعوت کرد تا به این فضا بپیوندید" "دارید آگاهی را مشاهده می‌کنید! کلیک کنید!" + "رزوه در %1$s" "%1$s: %2$s" "%1$s: %2$s %3$s" @@ -54,13 +68,28 @@ "همگام سازی پس‌زمینه" "خدمات گوگل" "خدمت پلی گوگل معتبری پیدا نشد. ممکن است آگاهی‌ها به درستی کار نکنند." + "بررسی کاربران مسدود شده" + "مشاهده کاربران مسدود شده" + "هیچ کاربری مسدود نشده است." + + "شما کاربر %1$d را مسدود کرده‌اید. شما اعلان‌هایی برای این کاربر دریافت نخواهید کرد." + "شما کاربران %1$d را مسدود کرده‌اید. برای این کاربران اعلان دریافت نخواهید کرد." + "کاربران مسدود" "گرفتن نام فراهم کنندهٔ کنونی." "هیچ فراهم کنندهٔ ارسالی گزیده نشده." + "ارائه دهنده فعلی پوش: %1$s و توزیع کننده فعلی: %2$s. اما توزیع کننده %3$s پیدا نشد. شاید برنامه حذف نصب شده باشد؟" + "ارائه دهنده فشار فعلی: %1$s، اما هیچ توزیع کننده ای پیکربندی نشده است." "فراهم کنندهٔ ارسال کنونی: %1$s." + "ارائه دهنده خدمات فشار فعلی: %1$s (%2$s)" "فراهم کنندهٔ ارسال کنونی" "ازمینان از پشتیبانی برنامه از لااقل یک فراهم کنندهٔ ارسال." "پشتیبانی از هیچ فراهم کنندهٔ ارسالی پیدا نشد." + + "ارائه دهنده فشار %1$d یافت شد: %2$s" + "ارائه دهندگان فشار %1$d یافت شد: %2$s" + + "این برنامه با پشتیبانی از موارد زیر ساخته شده است: %1$s" "پشتیبانی از فراهم‌کنندهٔ ارسال" "بررسی توانایی برنامه در نمایش آگاهی." "روی آگاهی زده نشد." diff --git a/libraries/push/impl/src/main/res/values-fi/translations.xml b/libraries/push/impl/src/main/res/values-fi/translations.xml index 24c10e8e69..0d8f486663 100644 --- a/libraries/push/impl/src/main/res/values-fi/translations.xml +++ b/libraries/push/impl/src/main/res/values-fi/translations.xml @@ -19,6 +19,10 @@ "Sinulla on %d uusi viesti." "Sinulla on %d uutta viestiä." + + "Jakoi %1$d liitteen" + "Jakoi %1$d liitettä" + "📞 Saapuva puhelu" "📹 Saapuva puhelu" "** Lähetys epäonnistui - avaa huone" @@ -30,6 +34,7 @@ "Kutsui sinut keskustelemaan" "%1$s kutsui sinut keskustelemaan" + "Aloitti reaaliaikaisen sijainnin jakamisen" "Mainitsi sinut: %1$s" "Uusia viestejä" diff --git a/libraries/push/impl/src/main/res/values-fr/translations.xml b/libraries/push/impl/src/main/res/values-fr/translations.xml index 1b0c44d90e..6c129cd3ed 100644 --- a/libraries/push/impl/src/main/res/values-fr/translations.xml +++ b/libraries/push/impl/src/main/res/values-fr/translations.xml @@ -19,6 +19,10 @@ "Vous avez %d nouveau message." "Vous avez %d nouveaux messages." + + "%1$d attachement partagé" + "%1$d attachements partagés" + "📞 Appel entrant" "📹 Appel entrant" "** Échec de l’envoi - veuillez ouvrir le salon" @@ -30,6 +34,7 @@ "Vous a invité(e) à discuter" "%1$s vous a invité à discuter" + "A commencé à partager sa position en direct" "Mentionné(e) : %1$s" "Nouveaux messages" diff --git a/libraries/push/impl/src/main/res/values-hr/translations.xml b/libraries/push/impl/src/main/res/values-hr/translations.xml index eead0db104..6c364c6a9f 100644 --- a/libraries/push/impl/src/main/res/values-hr/translations.xml +++ b/libraries/push/impl/src/main/res/values-hr/translations.xml @@ -21,6 +21,10 @@ "Imate%d novu poruku." "Imate %d novi poruka." + + "Dijeljeni privitak %1$d" + "Dijeljeni prilozi %1$d" + "📞 Dolazni poziv" "📹 Dolazni poziv" "** Slanje nije uspjelo – otvorite sobu" @@ -33,6 +37,7 @@ "Pozvao/la te na razgovor" "%1$s pozvao/la te na razgovor" + "Počeli su dijeliti svoju lokaciju uživo" "Korisnik vas je spomenuo: %1$s" "Nove poruke" diff --git a/libraries/push/impl/src/main/res/values-hu/translations.xml b/libraries/push/impl/src/main/res/values-hu/translations.xml index ea500512ad..4ee957bc23 100644 --- a/libraries/push/impl/src/main/res/values-hu/translations.xml +++ b/libraries/push/impl/src/main/res/values-hu/translations.xml @@ -30,6 +30,7 @@ "Meghívta, hogy csevegjen" "%1$s meghívta egy csevegésre" + "Elkezdték megosztani az élő helyzetüket" "Megemlítette Önt: %1$s" "Új üzenetek" diff --git a/libraries/push/impl/src/main/res/values-pl/translations.xml b/libraries/push/impl/src/main/res/values-pl/translations.xml index d8a4077d05..6c04215dd4 100644 --- a/libraries/push/impl/src/main/res/values-pl/translations.xml +++ b/libraries/push/impl/src/main/res/values-pl/translations.xml @@ -22,6 +22,11 @@ "Masz %d nowe wiadomości." "Masz %d nowych wiadomości." + + "Udostępnił %1$d załącznik" + "Udostępnił %1$d załączniki" + "Udostępnił %1$d załączników" + "📞 Połączenie przychodzące" "📹 Połączenie przychodzące" "** Nie udało się wysłać - proszę otworzyć pokój" @@ -34,6 +39,7 @@ "Zaprosił Cię do czatu" "%1$s zaprosił Cię do czatu" + "Rozpoczął udostępnianie swojej lokalizacji" "Wspomniano o Tobie: %1$s" "Nowe wiadomości" diff --git a/libraries/push/impl/src/main/res/values-ro/translations.xml b/libraries/push/impl/src/main/res/values-ro/translations.xml index 2f677568ea..109a50f7aa 100644 --- a/libraries/push/impl/src/main/res/values-ro/translations.xml +++ b/libraries/push/impl/src/main/res/values-ro/translations.xml @@ -20,6 +20,11 @@ "Aveți %d mesaje noi." "Aveți %d mesaje noi." + + "%1$d atașament partajat" + "%1$d atașamente partajate" + "%1$d atașamente partajate" + "📞 Apel primit" "Apel primit" "** Trimiterea eșuată - vă rugăm să deschideți camera" @@ -31,6 +36,7 @@ "V-a invitat la o discuție" "%1$s v-a invitat să discutați" + "A început să își partajeze locația live" "%1$s v-a menționat" "Mesaje noi" diff --git a/libraries/push/impl/src/main/res/values-uk/translations.xml b/libraries/push/impl/src/main/res/values-uk/translations.xml index 253bebda78..755654dc62 100644 --- a/libraries/push/impl/src/main/res/values-uk/translations.xml +++ b/libraries/push/impl/src/main/res/values-uk/translations.xml @@ -22,6 +22,11 @@ "У вас %d нових повідомлення." "У вас %d нових повідомлень." + + "Поширено %1$d вкладення" + "Поширено %1$d вкладення" + "Поширено %1$d вкладень" + "📞 Вхідний виклик" "📹 Вхідний виклик" "** Не вдалося надіслати - відкрийте кімнату" diff --git a/libraries/push/impl/src/main/res/values-zh-rTW/translations.xml b/libraries/push/impl/src/main/res/values-zh-rTW/translations.xml index 207f962b90..af3b58c980 100644 --- a/libraries/push/impl/src/main/res/values-zh-rTW/translations.xml +++ b/libraries/push/impl/src/main/res/values-zh-rTW/translations.xml @@ -16,6 +16,9 @@ "您有 %d 則新訊息。" + + "已分享 %1$d 個附件" + "📞 來電" "📹 來電" "** 無法傳送,請開啟聊天室" @@ -26,6 +29,7 @@ "邀請您聊天" "%1$s 邀請您加入聊天" + "已開始分享他們的即時位置" "提及您:%1$s" "新訊息" diff --git a/libraries/push/impl/src/main/res/values-zh/translations.xml b/libraries/push/impl/src/main/res/values-zh/translations.xml index 155c9d8ce6..bbdbabd350 100644 --- a/libraries/push/impl/src/main/res/values-zh/translations.xml +++ b/libraries/push/impl/src/main/res/values-zh/translations.xml @@ -16,6 +16,9 @@ "你有 %d 个新消息。" + + "已共享 %1$d 个附件" + "📞 来电" "📹 来电" "** 无法发送——请打开房间" @@ -26,6 +29,7 @@ "已邀请你聊天" "%1$s 已邀请你聊天" + "已申请加入" "已开始共享其实时位置" "提到了你:%1$s" "新消息" @@ -89,6 +93,7 @@ "错误:%1$s。" "错误,无法测试推送。" "错误,等待推送超时。" + "错误:推送网关已对此设备限流,因此通知可能不稳定。请更换其它推送网关。" "推送回路耗时 %1$d 毫秒。" "测试推送回路" diff --git a/libraries/push/impl/src/main/res/values/localazy.xml b/libraries/push/impl/src/main/res/values/localazy.xml index 1620408c15..bbe6f958b9 100644 --- a/libraries/push/impl/src/main/res/values/localazy.xml +++ b/libraries/push/impl/src/main/res/values/localazy.xml @@ -19,6 +19,10 @@ "You have %d new message." "You have %d new messages." + + "Shared %1$d attachment" + "Shared %1$d attachments" + "📞 Incoming call" "📹 Incoming call" "** Failed to send - please open room" @@ -30,6 +34,7 @@ "Invited you to chat" "%1$s invited you to chat" + "Requested to join" "Started sharing their live location" "Mentioned you: %1$s" "New Messages" @@ -98,6 +103,7 @@ "Error: %1$s." "Error, cannot test push." "Error, timeout waiting for push." + "Error: the push gateway is rate limiting this device, so notifications won\'t be reliable. Please set up a different push gateway." "Push loop back took %1$d ms." "Test Push loop back" diff --git a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriberTest.kt b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriberTest.kt index 8cb1e2a7f6..76479720be 100644 --- a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriberTest.kt +++ b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/DefaultPusherSubscriberTest.kt @@ -9,7 +9,6 @@ package io.element.android.libraries.push.impl import com.google.common.truth.Truth.assertThat -import io.element.android.appconfig.PushConfig import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.matrix.api.pusher.SetHttpPusherData import io.element.android.libraries.matrix.api.pusher.UnsetHttpPusherData @@ -96,7 +95,7 @@ class DefaultPusherSubscriberTest { value( SetHttpPusherData( pushKey = "aPushKey", - appId = PushConfig.PUSHER_APP_ID, + appId = BuildConfig.PUSHER_APP_ID, url = "aGateway", appDisplayName = "MyApp", deviceDisplayName = "MyDevice", @@ -163,7 +162,7 @@ class DefaultPusherSubscriberTest { value( UnsetHttpPusherData( pushKey = "aPushKey", - appId = PushConfig.PUSHER_APP_ID, + appId = BuildConfig.PUSHER_APP_ID, ), ) ) diff --git a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolverTest.kt b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolverTest.kt index eedc107c67..24e88e72d2 100644 --- a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolverTest.kt +++ b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/DefaultNotifiableEventResolverTest.kt @@ -39,6 +39,7 @@ import io.element.android.libraries.matrix.test.A_REDACTION_REASON import io.element.android.libraries.matrix.test.A_ROOM_ID import io.element.android.libraries.matrix.test.A_ROOM_NAME import io.element.android.libraries.matrix.test.A_SESSION_ID +import io.element.android.libraries.matrix.test.A_SESSION_ID_2 import io.element.android.libraries.matrix.test.A_SPACE_NAME import io.element.android.libraries.matrix.test.A_TIMESTAMP import io.element.android.libraries.matrix.test.A_USER_ID_2 @@ -56,6 +57,9 @@ import io.element.android.libraries.push.impl.notifications.model.FallbackNotifi import io.element.android.libraries.push.impl.notifications.model.InviteNotifiableEvent import io.element.android.libraries.push.impl.notifications.model.NotifiableMessageEvent import io.element.android.libraries.push.impl.notifications.model.ResolvedPushEvent +import io.element.android.libraries.sessionstorage.api.SessionStore +import io.element.android.libraries.sessionstorage.test.InMemorySessionStore +import io.element.android.libraries.sessionstorage.test.aSessionData import io.element.android.services.toolbox.impl.strings.AndroidStringProvider import io.element.android.services.toolbox.test.systemclock.A_FAKE_TIMESTAMP import io.element.android.services.toolbox.test.systemclock.FakeSystemClock @@ -648,6 +652,28 @@ class DefaultNotifiableEventResolverTest : RobolectricTest() { assertThat(result.getEvent(request)).isEqualTo(Result.success(expectedResult)) } + @Test + fun `resolve RoomMemberContent knock`() = runTest { + val sut = createDefaultNotifiableEventResolver( + notificationResult = Result.success( + mapOf( + AN_EVENT_ID to Result.success(aNotificationData( + content = NotificationContent.StateEvent.RoomMemberContent( + userId = A_USER_ID_2, + membershipState = RoomMembershipState.KNOCK + ) + )) + ) + ) + ) + val request = aPushRequest(A_SESSION_ID, A_ROOM_ID, AN_EVENT_ID, "firebase") + val result = sut.resolveEvents(A_SESSION_ID, listOf(request)) + val expectedResult = ResolvedPushEvent.Event( + aNotifiableMessageEvent(body = "Requested to join") + ) + assertThat(result.getEvent(request)).isEqualTo(Result.success(expectedResult)) + } + @Test fun `resolve RoomMemberContent other`() = runTest { val sut = createDefaultNotifiableEventResolver( @@ -818,7 +844,7 @@ class DefaultNotifiableEventResolverTest : RobolectricTest() { } @Test - fun `resolve RoomRedaction with null redactedEventId should return null`() = runTest { + fun `resolve RoomRedaction with null redactedEventId is filtered out`() = runTest { val sut = createDefaultNotifiableEventResolver( notificationResult = Result.success( mapOf( @@ -834,6 +860,112 @@ class DefaultNotifiableEventResolverTest : RobolectricTest() { val request = aPushRequest(A_SESSION_ID, A_ROOM_ID, AN_EVENT_ID, "firebase") val result = sut.resolveEvents(A_SESSION_ID, listOf(request)) assertThat(result.getEvent(request)?.getOrNull()).isNull() + assertThat(result.getEvent(request)?.exceptionOrNull()).isEqualTo(NotificationResolverException.EventFilteredOut) + } + + @Test + fun `resolve RoomMessage sent by another session on the same device is filtered out`() = runTest { + val sut = createDefaultNotifiableEventResolver( + notificationResult = Result.success( + mapOf( + AN_EVENT_ID to Result.success( + aNotificationData( + content = NotificationContent.MessageLike.RoomMessage( + senderId = A_SESSION_ID_2, + messageType = TextMessageType("Hello world", null), + ) + ) + ) + ) + ), + sessionStore = InMemorySessionStore( + listOf( + aSessionData(sessionId = A_SESSION_ID.value), + aSessionData(sessionId = A_SESSION_ID_2.value), + ) + ), + ) + val request = aPushRequest(A_SESSION_ID, A_ROOM_ID, AN_EVENT_ID, "firebase") + val result = sut.resolveEvents(A_SESSION_ID, listOf(request)) + assertThat(result.getEvent(request)?.exceptionOrNull()).isEqualTo(NotificationResolverException.EventFilteredOut) + } + + @Test + fun `resolve RtcNotification sent by another session on the same device is filtered out`() = runTest { + val sut = createDefaultNotifiableEventResolver( + notificationResult = Result.success( + mapOf( + AN_EVENT_ID to Result.success( + aNotificationData( + content = NotificationContent.MessageLike.RtcNotification( + senderId = A_SESSION_ID_2, + type = RtcNotificationType.RING, + callIntent = CallIntent.AUDIO, + expirationTimestampMillis = 0, + ) + ) + ) + ) + ), + sessionStore = InMemorySessionStore( + listOf( + aSessionData(sessionId = A_SESSION_ID.value), + aSessionData(sessionId = A_SESSION_ID_2.value), + ) + ), + ) + val request = aPushRequest(A_SESSION_ID, A_ROOM_ID, AN_EVENT_ID, "firebase") + val result = sut.resolveEvents(A_SESSION_ID, listOf(request)) + assertThat(result.getEvent(request)?.exceptionOrNull()).isEqualTo(NotificationResolverException.EventFilteredOut) + } + + @Test + fun `resolve RoomMessage sent by a user who is not logged in is not filtered out`() = runTest { + val sut = createDefaultNotifiableEventResolver( + notificationResult = Result.success( + mapOf( + AN_EVENT_ID to Result.success( + aNotificationData( + content = NotificationContent.MessageLike.RoomMessage( + senderId = A_SESSION_ID_2, + messageType = TextMessageType("Hello world", null), + ) + ) + ) + ) + ), + sessionStore = InMemorySessionStore(listOf(aSessionData(sessionId = A_SESSION_ID.value))), + ) + val request = aPushRequest(A_SESSION_ID, A_ROOM_ID, AN_EVENT_ID, "firebase") + val result = sut.resolveEvents(A_SESSION_ID, listOf(request)) + assertThat(result.getEvent(request)?.isSuccess).isTrue() + } + + @Test + fun `resolve RoomMessage sent by the receiving session itself is not filtered out`() = runTest { + val sut = createDefaultNotifiableEventResolver( + notificationResult = Result.success( + mapOf( + AN_EVENT_ID to Result.success( + aNotificationData( + content = NotificationContent.MessageLike.RoomMessage( + senderId = A_SESSION_ID, + messageType = TextMessageType("Hello world", null), + ) + ) + ) + ) + ), + sessionStore = InMemorySessionStore( + listOf( + aSessionData(sessionId = A_SESSION_ID.value), + aSessionData(sessionId = A_SESSION_ID_2.value), + ) + ), + ) + val request = aPushRequest(A_SESSION_ID, A_ROOM_ID, AN_EVENT_ID, "firebase") + val result = sut.resolveEvents(A_SESSION_ID, listOf(request)) + assertThat(result.getEvent(request)?.isSuccess).isTrue() } @Test @@ -893,6 +1025,7 @@ class DefaultNotifiableEventResolverTest : RobolectricTest() { notificationService: FakeNotificationService? = FakeNotificationService(), notificationResult: Result>> = Result.success(emptyMap()), callNotificationEventResolver: FakeCallNotificationEventResolver = FakeCallNotificationEventResolver(), + sessionStore: SessionStore = InMemorySessionStore(), ): DefaultNotifiableEventResolver { val context = RuntimeEnvironment.getApplication() as Context notificationService?.givenGetNotificationsResult(notificationResult) @@ -917,6 +1050,7 @@ class DefaultNotifiableEventResolverTest : RobolectricTest() { clock = FakeSystemClock(), ), featureFlagService = FakeFeatureFlagService(), + sessionStore = sessionStore, ) } } diff --git a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/factories/DefaultNotificationCreatorTest.kt b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/factories/DefaultNotificationCreatorTest.kt index 38b387a180..299c5ad213 100644 --- a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/factories/DefaultNotificationCreatorTest.kt +++ b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/notifications/factories/DefaultNotificationCreatorTest.kt @@ -19,6 +19,7 @@ import io.element.android.features.enterprise.api.EnterpriseService import io.element.android.features.enterprise.test.FakeEnterpriseService import io.element.android.libraries.core.meta.BuildMeta import io.element.android.libraries.matrix.test.AN_EVENT_ID +import io.element.android.libraries.matrix.test.AN_EVENT_ID_2 import io.element.android.libraries.matrix.test.A_COLOR_INT import io.element.android.libraries.matrix.test.A_ROOM_ID import io.element.android.libraries.matrix.test.A_SESSION_ID @@ -40,6 +41,7 @@ import io.element.android.libraries.push.impl.notifications.factories.action.Rej import io.element.android.libraries.push.impl.notifications.fixtures.aFallbackNotifiableEvent import io.element.android.libraries.push.impl.notifications.fixtures.aNotifiableMessageEvent import io.element.android.libraries.push.impl.notifications.model.InviteNotifiableEvent +import io.element.android.libraries.push.impl.notifications.model.NotifiableMessageEvent import io.element.android.libraries.push.impl.notifications.model.SimpleNotifiableEvent import io.element.android.services.toolbox.test.sdk.FakeBuildVersionSdkIntProvider import io.element.android.services.toolbox.test.strings.FakeStringProvider @@ -302,6 +304,81 @@ class DefaultNotificationCreatorTest : RobolectricTest() { result.commonAssertions() } + @Test + fun `test createMessagesListNotification does not add an event which is already displayed`() = runTest { + val sut = createNotificationCreator() + val event = aNotifiableMessageEvent(body = "A message") + val existingNotification = sut.createRoomNotification(events = listOf(event)) + assertThat(existingNotification.flags and Notification.FLAG_ONLY_ALERT_ONCE).isEqualTo(0) + val result = sut.createRoomNotification(events = listOf(event), existingNotification = existingNotification) + assertThat(result.messageTexts()).containsExactly("A message") + assertThat(result.flags and Notification.FLAG_ONLY_ALERT_ONCE).isNotEqualTo(0) + } + + @Test + fun `test createMessagesListNotification adds a new event to the already displayed ones`() = runTest { + val sut = createNotificationCreator() + val existingNotification = sut.createRoomNotification(events = listOf(aNotifiableMessageEvent(body = "A message"))) + val result = sut.createRoomNotification( + events = listOf(aNotifiableMessageEvent(eventId = AN_EVENT_ID_2, body = "Another message")), + existingNotification = existingNotification, + ) + assertThat(result.messageTexts()).containsExactly("A message", "Another message").inOrder() + } + + @Test + fun `test createMessagesListNotification adds the smart reply error of an already displayed event`() = runTest { + val sut = createNotificationCreator() + val event = aNotifiableMessageEvent(body = "A message").copy(outGoingMessage = true) + val existingNotification = sut.createRoomNotification(events = listOf(event)) + val result = sut.createRoomNotification( + events = listOf(event.copy(outGoingMessageFailed = true)), + existingNotification = existingNotification, + ) + assertThat(result.messageTexts()).containsExactly("A message", "test").inOrder() + } + + @Test + fun `test createMessagesListNotification does not add an image and its caption twice`() = runTest { + val sut = createNotificationCreator() + val event = aNotifiableMessageEvent(body = "A caption").copy( + imageUriString = "aUri", + imageMimeType = "image/jpeg", + ) + val existingNotification = sut.createRoomNotification(events = listOf(event)) + assertThat(existingNotification.messageTexts()).containsExactly("test", "A caption").inOrder() + val result = sut.createRoomNotification(events = listOf(event), existingNotification = existingNotification) + assertThat(result.messageTexts()).containsExactly("test", "A caption").inOrder() + } + + private suspend fun NotificationCreator.createRoomNotification( + events: List, + existingNotification: Notification? = null, + ) = createMessagesListNotification( + notificationAccountParams = aNotificationAccountParams(), + roomInfo = RoomEventGroupInfo( + sessionId = A_SESSION_ID, + roomId = A_ROOM_ID, + roomDisplayName = "roomDisplayName", + hasSmartReplyError = false, + shouldBing = false, + customSound = null, + isUpdated = false, + ), + threadId = null, + largeIcon = null, + lastMessageTimestamp = 123_456L, + tickerText = "tickerText", + existingNotification = existingNotification, + imageLoader = FakeImageLoader(), + events = events, + ) + + private fun Notification.messageTexts(): List { + val messagingStyle = checkNotNull(NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(this)) + return messagingStyle.messages.map { it.text?.toString() } + } + private fun Notification.commonAssertions( expectedGroup: String? = aMatrixUser().userId.value, expectedCategory: String? = NotificationCompat.CATEGORY_MESSAGE, diff --git a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/pushgateway/DefaultPushGatewayNotifyRequestTest.kt b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/pushgateway/DefaultPushGatewayNotifyRequestTest.kt index 47dc027b43..97f3bdc540 100644 --- a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/pushgateway/DefaultPushGatewayNotifyRequestTest.kt +++ b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/pushgateway/DefaultPushGatewayNotifyRequestTest.kt @@ -12,8 +12,11 @@ import com.google.common.truth.Truth.assertThat import io.element.android.libraries.push.api.gateway.PushGatewayFailure import io.element.android.libraries.push.impl.test.DefaultTestPush import kotlinx.coroutines.test.runTest +import okhttp3.ResponseBody.Companion.toResponseBody import org.junit.Assert.assertThrows import org.junit.Test +import retrofit2.HttpException +import retrofit2.Response class DefaultPushGatewayNotifyRequestTest { @Test @@ -64,6 +67,58 @@ class DefaultPushGatewayNotifyRequestTest { assertThat(factory.baseUrlParameter).isEqualTo("aUrl") } + @Test + fun `notify with a rate limiting status should throw expected Exception`() { + listOf(429, 507).forEach { statusCode -> + val factory = FakePushGatewayApiFactory( + notifyResponse = { + throw HttpException(Response.error(statusCode, "".toResponseBody())) + } + ) + val pushGatewayNotifyRequest = DefaultPushGatewayNotifyRequest( + pushGatewayApiFactory = factory, + ) + assertThrows(PushGatewayFailure.RateLimited::class.java) { + runTest { + pushGatewayNotifyRequest.execute( + PushGatewayNotifyRequest.Params( + url = "aUrl", + appId = "anAppId", + pushKey = "aPushKey", + eventId = DefaultTestPush.TEST_EVENT_ID, + roomId = DefaultTestPush.TEST_ROOM_ID, + ) + ) + } + } + } + } + + @Test + fun `notify with another http error should not be mapped to a rate limit`() { + val factory = FakePushGatewayApiFactory( + notifyResponse = { + throw HttpException(Response.error(500, "".toResponseBody())) + } + ) + val pushGatewayNotifyRequest = DefaultPushGatewayNotifyRequest( + pushGatewayApiFactory = factory, + ) + assertThrows(HttpException::class.java) { + runTest { + pushGatewayNotifyRequest.execute( + PushGatewayNotifyRequest.Params( + url = "aUrl", + appId = "anAppId", + pushKey = "aPushKey", + eventId = DefaultTestPush.TEST_EVENT_ID, + roomId = DefaultTestPush.TEST_ROOM_ID, + ) + ) + } + } + } + @Test fun `notify with rejected push key should throw expected Exception`() { val factory = FakePushGatewayApiFactory( diff --git a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/test/DefaultTestPushTest.kt b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/test/DefaultTestPushTest.kt index 9ab0f16b62..3722c09d99 100644 --- a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/test/DefaultTestPushTest.kt +++ b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/test/DefaultTestPushTest.kt @@ -8,7 +8,7 @@ package io.element.android.libraries.push.impl.test -import io.element.android.appconfig.PushConfig +import io.element.android.libraries.push.impl.BuildConfig import io.element.android.libraries.push.impl.pushgateway.PushGatewayNotifyRequest import io.element.android.libraries.pushproviders.test.aSessionPushConfig import io.element.android.tests.testutils.lambda.lambdaRecorder @@ -33,7 +33,7 @@ class DefaultTestPushTest { value( PushGatewayNotifyRequest.Params( url = aConfig.url, - appId = PushConfig.PUSHER_APP_ID, + appId = BuildConfig.PUSHER_APP_ID, pushKey = aConfig.pushKey, eventId = DefaultTestPush.TEST_EVENT_ID, roomId = DefaultTestPush.TEST_ROOM_ID, diff --git a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTestTest.kt b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTestTest.kt index f83fb660ce..447fdd7eb5 100644 --- a/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTestTest.kt +++ b/libraries/push/impl/src/test/kotlin/io/element/android/libraries/push/impl/troubleshoot/PushLoopbackTestTest.kt @@ -59,6 +59,25 @@ class PushLoopbackTestTest { } } + @Test + fun `test PushLoopbackTest RateLimited error`() = runTest { + val sut = createPushLoopbackTest( + pushService = FakePushService( + testPushBlock = { + throw PushGatewayFailure.RateLimited() + } + ), + stringProvider = FakeStringProvider(A_FAILURE_REASON), + ) + sut.runAndTestState { + assertThat(awaitItem().status).isEqualTo(NotificationTroubleshootTestState.Status.Idle(true)) + assertThat(awaitItem().status).isEqualTo(NotificationTroubleshootTestState.Status.InProgress) + val lastItem = awaitItem() + assertThat(lastItem.status).isEqualTo(NotificationTroubleshootTestState.Status.Failure()) + assertThat(lastItem.description).isEqualTo(A_FAILURE_REASON) + } + } + @Test fun `test PushLoopbackTest PusherRejected error with quick fix`() = runTest { val rotateTokenLambda = lambdaRecorder> { Result.success(Unit) } diff --git a/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushHandler.kt b/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushHandler.kt index 49b578070b..1e53575717 100644 --- a/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushHandler.kt +++ b/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushHandler.kt @@ -8,6 +8,9 @@ package io.element.android.libraries.pushproviders.api +/** + * Entry point for the pushes coming from any provider, which resolves them into notifications. + */ interface PushHandler { /** * Handle a push received from the provider. @@ -22,7 +25,10 @@ interface PushHandler { ): Boolean /** - * Handle an invalid push received from the provider. + * Handle an invalid push received from the provider, which is recorded in the push history so it can be diagnosed. + * + * @param providerInfo an identifier of the provider that sent the push, for logging and debugging purposes. + * @param data the raw payload that could not be understood. */ suspend fun handleInvalid( providerInfo: String, diff --git a/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushProvider.kt b/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushProvider.kt index 405a83b9b8..ed13d0ab37 100644 --- a/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushProvider.kt +++ b/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PushProvider.kt @@ -37,33 +37,54 @@ interface PushProvider { /** * Register the pusher to the homeserver. + * + * @param matrixClient the session to register the pusher for. + * @param distributor the distributor to route the notifications through. */ suspend fun registerWith(matrixClient: MatrixClient, distributor: Distributor): Result /** - * Return the current distributor, or null if none. + * Return the current distributor as its raw stored value, or null if none. + * + * @param sessionId the session to read the distributor of. */ suspend fun getCurrentDistributorValue(sessionId: SessionId): String? /** - * Return the current distributor, or null if none. + * Return the current distributor, or null if none, which also happens when the stored one is no longer installed. + * + * @param sessionId the session to read the distributor of. */ suspend fun getCurrentDistributor(sessionId: SessionId): Distributor? /** * Unregister the pusher. + * + * @param matrixClient the session to unregister the pusher of. */ suspend fun unregister(matrixClient: MatrixClient): Result /** * To invoke when the session is deleted. + * + * @param sessionId the session that has been removed, whose provider-side data should be cleaned up. */ suspend fun onSessionDeleted(sessionId: SessionId) + /** + * The gateway and push key currently in use, for display in the troubleshooting screens; `null` when not registered. + * + * @param sessionId the session to read the configuration of. + */ suspend fun getPushConfig(sessionId: SessionId): Config? + /** Whether this provider can renew its push token on demand, which not every provider supports. */ fun canRotateToken(): Boolean + /** + * Renews the push token, which is one of the recovery steps offered when notifications stop arriving. + * Throws when [canRotateToken] is `false`. + */ suspend fun rotateToken(): Result { error("rotateToken() not implemented, you need to override this method in your implementation") } diff --git a/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PusherSubscriber.kt b/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PusherSubscriber.kt index 989170c975..e1d885fca2 100644 --- a/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PusherSubscriber.kt +++ b/libraries/pushproviders/api/src/main/kotlin/io/element/android/libraries/pushproviders/api/PusherSubscriber.kt @@ -11,14 +11,25 @@ package io.element.android.libraries.pushproviders.api import io.element.android.libraries.matrix.api.MatrixClient import io.element.android.libraries.matrix.api.exception.ClientException +/** + * Registers and removes a pusher on the homeserver on behalf of a push provider, so every provider agrees on the parameters sent. + */ interface PusherSubscriber { /** * Register a pusher. Note that failure will be a [RegistrationFailure]. + * + * @param matrixClient the session to register the pusher for. + * @param pushKey the token identifying this device with the gateway. + * @param gateway the URL the homeserver should send the notifications to. */ suspend fun registerPusher(matrixClient: MatrixClient, pushKey: String, gateway: String): Result /** * Unregister a pusher. + * + * @param matrixClient the session to unregister the pusher of. + * @param pushKey the token of the registration to remove. + * @param gateway the gateway of the registration to remove. */ suspend fun unregisterPusher(matrixClient: MatrixClient, pushKey: String, gateway: String): Result } diff --git a/libraries/pushproviders/firebase/README.md b/libraries/pushproviders/firebase/README.md index a2a7ad97ed..d9732af0d0 100644 --- a/libraries/pushproviders/firebase/README.md +++ b/libraries/pushproviders/firebase/README.md @@ -2,6 +2,6 @@ ## Configuration -In order to make this module only know about Firebase, the plugin `com.google.gms.google-services` has been disabled from the `app` module. +In order to make only this module know about Firebase, the plugin `com.google.gms.google-services` has been disabled from the `app` module. -To be able to change the values set to `google_app_id` in the file `build.gradle.kts` of this module, you should enable the plugin `com.google.gms.google-services` again, copy the file `google-services.json` to the folder `/app/src/main`, build the project, and check the generated file `app/build/generated/res/google-services//values/values.xml` to import the generated values into the `build.gradle.kts` files. +To be able to change the values set to `google_app_id` in the file `build.gradle.kts` of this module, you should enable the plugin `com.google.gms.google-services` again, copy the file `google-services.json` to the folder `/app`, build the project, and check the generated file `app/build/generated/res/google-services//values/values.xml` to import the generated values into the `firebase.xml` files. diff --git a/libraries/pushproviders/firebase/build.gradle.kts b/libraries/pushproviders/firebase/build.gradle.kts index 1a8e73a4da..33e88dd94c 100644 --- a/libraries/pushproviders/firebase/build.gradle.kts +++ b/libraries/pushproviders/firebase/build.gradle.kts @@ -8,7 +8,6 @@ @file:Suppress("UnstableApiUsage") -import config.BuildTimeConfig import extension.setupDependencyInjection import extension.testCommonDependencies import org.gradle.kotlin.dsl.withType @@ -28,27 +27,10 @@ android { buildTypes { getByName("release") { consumerProguardFiles("consumer-proguard-rules.pro") - resValue( - type = "string", - name = "google_app_id", - value = BuildTimeConfig.GOOGLE_APP_ID_RELEASE, - ) - } - getByName("debug") { - resValue( - type = "string", - name = "google_app_id", - value = BuildTimeConfig.GOOGLE_APP_ID_DEBUG, - ) } register("nightly") { consumerProguardFiles("consumer-proguard-rules.pro") matchingFallbacks += listOf("release") - resValue( - type = "string", - name = "google_app_id", - value = BuildTimeConfig.GOOGLE_APP_ID_NIGHTLY, - ) } } } diff --git a/libraries/pushproviders/firebase/src/debug/res/values/firebase.xml b/libraries/pushproviders/firebase/src/debug/res/values/firebase.xml new file mode 100644 index 0000000000..e96f163603 --- /dev/null +++ b/libraries/pushproviders/firebase/src/debug/res/values/firebase.xml @@ -0,0 +1,4 @@ + + + 1:912726360885:android:def0a4e454042e9b00427c + diff --git a/libraries/pushproviders/firebase/src/main/res/values-ar/translations.xml b/libraries/pushproviders/firebase/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..e5229be2f3 --- /dev/null +++ b/libraries/pushproviders/firebase/src/main/res/values-ar/translations.xml @@ -0,0 +1,11 @@ + + + "يتحقق من توفر Firebase." + "Firebase غير متاح." + "Firebase متاح." + "التحقق من Firebase" + "يتحقق من توفر رمز Firebase المميز." + "رمز Firebase المميز غير معروف." + "رمز Firebase المميز: %1$s." + "التحقق من رمز Firebase المميز" + diff --git a/libraries/pushproviders/firebase/src/nightly/res/values/firebase.xml b/libraries/pushproviders/firebase/src/nightly/res/values/firebase.xml new file mode 100644 index 0000000000..7275ff2ddd --- /dev/null +++ b/libraries/pushproviders/firebase/src/nightly/res/values/firebase.xml @@ -0,0 +1,4 @@ + + + 1:912726360885:android:e17435e0beb0303000427c + diff --git a/libraries/pushproviders/firebase/src/release/res/values/firebase.xml b/libraries/pushproviders/firebase/src/release/res/values/firebase.xml new file mode 100644 index 0000000000..3a9a4330d1 --- /dev/null +++ b/libraries/pushproviders/firebase/src/release/res/values/firebase.xml @@ -0,0 +1,4 @@ + + + 1:912726360885:android:d097de99a4c23d2700427c + diff --git a/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/RegisterUnifiedPushUseCase.kt b/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/RegisterUnifiedPushUseCase.kt index 00e5649533..0e1566ba59 100644 --- a/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/RegisterUnifiedPushUseCase.kt +++ b/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/RegisterUnifiedPushUseCase.kt @@ -12,6 +12,7 @@ import android.content.Context import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding import io.element.android.libraries.di.annotations.ApplicationContext +import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.pushproviders.api.Distributor import io.element.android.libraries.pushproviders.unifiedpush.registration.EndpointRegistrationHandler import kotlinx.coroutines.flow.filter @@ -21,7 +22,7 @@ import org.unifiedpush.android.connector.UnifiedPush import kotlin.time.Duration.Companion.seconds interface RegisterUnifiedPushUseCase { - suspend fun execute(distributor: Distributor, clientSecret: String): Result + suspend fun execute(distributor: Distributor, clientSecret: String, sessionId: SessionId): Result } @ContributesBinding(AppScope::class) @@ -29,11 +30,11 @@ class DefaultRegisterUnifiedPushUseCase( @ApplicationContext private val context: Context, private val endpointRegistrationHandler: EndpointRegistrationHandler, ) : RegisterUnifiedPushUseCase { - override suspend fun execute(distributor: Distributor, clientSecret: String): Result { + override suspend fun execute(distributor: Distributor, clientSecret: String, sessionId: SessionId): Result { UnifiedPush.saveDistributor(context, distributor.value) // This will trigger the callback // VectorUnifiedPushMessagingReceiver.onNewEndpoint - UnifiedPush.register(context = context, instance = clientSecret) + UnifiedPush.register(context = context, instance = clientSecret, messageForDistributor = sessionId.value) // Wait for VectorUnifiedPushMessagingReceiver.onNewEndpoint to proceed @Suppress("RunCatchingNotAllowed") return runCatching { diff --git a/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProvider.kt b/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProvider.kt index 7288fccab2..f72a591faa 100644 --- a/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProvider.kt +++ b/libraries/pushproviders/unifiedpush/src/main/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProvider.kt @@ -36,7 +36,7 @@ class UnifiedPushProvider( override suspend fun registerWith(matrixClient: MatrixClient, distributor: Distributor): Result { val clientSecret = pushClientSecret.getSecretForUser(matrixClient.sessionId) - return registerUnifiedPushUseCase.execute(distributor, clientSecret) + return registerUnifiedPushUseCase.execute(distributor, clientSecret, matrixClient.sessionId) .onSuccess { unifiedPushStore.setDistributorValue(matrixClient.sessionId, distributor.value) } diff --git a/libraries/pushproviders/unifiedpush/src/main/res/values-ar/translations.xml b/libraries/pushproviders/unifiedpush/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..355ceef22d --- /dev/null +++ b/libraries/pushproviders/unifiedpush/src/main/res/values-ar/translations.xml @@ -0,0 +1,14 @@ + + + "يتحقق من توفر موزّعي UnifiedPush." + "لم يتم العثور على أي موزّع UnifiedPush." + + "تم العثور على %1$d من موزّعي UnifiedPush: %2$s." + "تم العثور على %1$d موزّع UnifiedPush: %2$s." + "تم العثور على %1$d من موزّعي UnifiedPush: %2$s." + "تم العثور على %1$d من موزّعي UnifiedPush: %2$s." + "تم العثور على %1$d من موزّعي UnifiedPush: %2$s." + "تم العثور على %1$d من موزّعي UnifiedPush: %2$s." + + "التحقق من UnifiedPush" + diff --git a/libraries/pushproviders/unifiedpush/src/main/res/values-fa/translations.xml b/libraries/pushproviders/unifiedpush/src/main/res/values-fa/translations.xml index c80e952967..af2f5f6bad 100644 --- a/libraries/pushproviders/unifiedpush/src/main/res/values-fa/translations.xml +++ b/libraries/pushproviders/unifiedpush/src/main/res/values-fa/translations.xml @@ -2,5 +2,9 @@ "اطمینان از در دسترس بودن توزیعگرهای ارسال یکپارچه." "هیچ توزیعگر ارسال یکپارچه‌ای پیدا نشد." + + "توزیع‌کننده‌ی %1$d پیدا شد: %2$s." + "توزیع‌کنندگان %1$d موارد زیر را یافتند: %2$s." + "بررسی ارسال یکپارچه" diff --git a/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/DefaultRegisterUnifiedPushUseCaseTest.kt b/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/DefaultRegisterUnifiedPushUseCaseTest.kt index fe7da75951..5460005cef 100644 --- a/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/DefaultRegisterUnifiedPushUseCaseTest.kt +++ b/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/DefaultRegisterUnifiedPushUseCaseTest.kt @@ -12,6 +12,7 @@ import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import io.element.android.libraries.matrix.test.AN_EXCEPTION import io.element.android.libraries.matrix.test.A_SECRET +import io.element.android.libraries.matrix.test.A_SESSION_ID import io.element.android.libraries.pushproviders.api.Distributor import io.element.android.libraries.pushproviders.unifiedpush.registration.EndpointRegistrationHandler import io.element.android.libraries.pushproviders.unifiedpush.registration.RegistrationResult @@ -41,7 +42,7 @@ class DefaultRegisterUnifiedPushUseCaseTest : RobolectricTest() { delay(100) endpointRegistrationHandler.registrationDone(RegistrationResult(A_SECRET, Result.success(Unit))) } - val result = useCase.execute(aDistributor, A_SECRET) + val result = useCase.execute(aDistributor, A_SECRET, A_SESSION_ID) assertThat(result.isSuccess).isTrue() } @@ -56,7 +57,7 @@ class DefaultRegisterUnifiedPushUseCaseTest : RobolectricTest() { delay(100) endpointRegistrationHandler.registrationDone(RegistrationResult(A_SECRET, Result.failure(AN_EXCEPTION))) } - val result = useCase.execute(aDistributor, A_SECRET) + val result = useCase.execute(aDistributor, A_SECRET, A_SESSION_ID) assertThat(result.isSuccess).isFalse() } @@ -67,7 +68,7 @@ class DefaultRegisterUnifiedPushUseCaseTest : RobolectricTest() { endpointRegistrationHandler = endpointRegistrationHandler ) val aDistributor = Distributor("aValue", "aName") - val result = useCase.execute(aDistributor, A_SECRET) + val result = useCase.execute(aDistributor, A_SECRET, A_SESSION_ID) assertThat(result.isSuccess).isFalse() } diff --git a/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/FakeRegisterUnifiedPushUseCase.kt b/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/FakeRegisterUnifiedPushUseCase.kt index 3055dad6b7..55729f29f8 100644 --- a/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/FakeRegisterUnifiedPushUseCase.kt +++ b/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/FakeRegisterUnifiedPushUseCase.kt @@ -8,13 +8,14 @@ package io.element.android.libraries.pushproviders.unifiedpush +import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.pushproviders.api.Distributor import io.element.android.tests.testutils.lambda.lambdaError class FakeRegisterUnifiedPushUseCase( - private val result: (Distributor, String) -> Result = { _, _ -> lambdaError() } + private val result: (Distributor, String, SessionId) -> Result = { _, _, _ -> lambdaError() } ) : RegisterUnifiedPushUseCase { - override suspend fun execute(distributor: Distributor, clientSecret: String): Result { - return result(distributor, clientSecret) + override suspend fun execute(distributor: Distributor, clientSecret: String, sessionId: SessionId): Result { + return result(distributor, clientSecret, sessionId) } } diff --git a/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProviderTest.kt b/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProviderTest.kt index e22c1c3bf4..e766068783 100644 --- a/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProviderTest.kt +++ b/libraries/pushproviders/unifiedpush/src/test/kotlin/io/element/android/libraries/pushproviders/unifiedpush/UnifiedPushProviderTest.kt @@ -62,7 +62,7 @@ class UnifiedPushProviderTest { @Test fun `register ok`() = runTest { val getSecretForUserResultLambda = lambdaRecorder { A_SECRET } - val executeLambda = lambdaRecorder> { _, _ -> Result.success(Unit) } + val executeLambda = lambdaRecorder> { _, _, _ -> Result.success(Unit) } val setDistributorValueResultLambda = lambdaRecorder { _, _ -> } val unifiedPushProvider = createUnifiedPushProvider( pushClientSecret = FakePushClientSecret( @@ -82,7 +82,7 @@ class UnifiedPushProviderTest { .with(value(A_SESSION_ID)) executeLambda.assertions() .isCalledOnce() - .with(value(Distributor("value", "Name")), value(A_SECRET)) + .with(value(Distributor("value", "Name")), value(A_SECRET), value(A_SESSION_ID)) setDistributorValueResultLambda.assertions() .isCalledOnce() .with(value(A_SESSION_ID), value("value")) @@ -91,7 +91,7 @@ class UnifiedPushProviderTest { @Test fun `register ko`() = runTest { val getSecretForUserResultLambda = lambdaRecorder { A_SECRET } - val executeLambda = lambdaRecorder> { _, _ -> Result.failure(AN_EXCEPTION) } + val executeLambda = lambdaRecorder> { _, _, _ -> Result.failure(AN_EXCEPTION) } val setDistributorValueResultLambda = lambdaRecorder(ensureNeverCalled = true) { _, _ -> } val unifiedPushProvider = createUnifiedPushProvider( pushClientSecret = FakePushClientSecret( @@ -111,7 +111,7 @@ class UnifiedPushProviderTest { .with(value(A_SESSION_ID)) executeLambda.assertions() .isCalledOnce() - .with(value(Distributor("value", "Name")), value(A_SECRET)) + .with(value(Distributor("value", "Name")), value(A_SECRET), value(A_SESSION_ID)) } @Test diff --git a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStore.kt b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStore.kt index 8a1b2f9f21..cec03e3c78 100644 --- a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStore.kt +++ b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStore.kt @@ -13,15 +13,36 @@ import kotlinx.coroutines.flow.Flow * Store data related to push about a user. */ interface UserPushStore { + /** The push provider selected for this user, or `null` when none has been selected yet. */ suspend fun getPushProviderName(): String? + + /** + * @param value the name of the push provider to remember for this user. + */ suspend fun setPushProviderName(value: String) + + /** The push key last registered with the homeserver, used to detect that a re-registration is needed; `null` when never registered. */ suspend fun getCurrentRegisteredPushKey(): String? + + /** + * @param value the push key that has just been registered, or `null` to forget it after unregistering. + */ suspend fun setCurrentRegisteredPushKey(value: String?) + /** Whether the user has enabled notifications on this device. */ fun getNotificationEnabledForDevice(): Flow + + /** + * @param enabled true to enable notifications on this device. + */ suspend fun setNotificationEnabledForDevice(enabled: Boolean) + /** Whether the user has asked not to be warned about pusher registration failures. */ fun ignoreRegistrationError(): Flow + + /** + * @param ignore true to stop warning the user about registration failures. + */ suspend fun setIgnoreRegistrationError(ignore: Boolean) /** @@ -29,5 +50,6 @@ interface UserPushStore { */ fun useCompleteNotificationFormat(): Boolean + /** Erases every push preference of this user, to be called when their session is removed. */ suspend fun reset() } diff --git a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStoreFactory.kt b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStoreFactory.kt index 78571d8b30..5210602e6c 100644 --- a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStoreFactory.kt +++ b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/UserPushStoreFactory.kt @@ -14,5 +14,10 @@ import io.element.android.libraries.matrix.api.core.SessionId * Store data related to push about a user. */ interface UserPushStoreFactory { + /** + * Returns the push store of a user, creating it on first use. + * + * @param userId the user whose store is requested. + */ fun getOrCreate(userId: SessionId): UserPushStore } diff --git a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecret.kt b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecret.kt index da3ea946f0..a2f4c0ce3b 100644 --- a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecret.kt +++ b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecret.kt @@ -10,15 +10,24 @@ package io.element.android.libraries.pushstore.api.clientsecret import io.element.android.libraries.matrix.api.core.SessionId +/** + * Manages the per-session client secret sent along with a pusher registration. + * + * Push gateways deliver notifications without saying which account they belong to, so the secret is what lets an incoming push be attributed to a session. + */ interface PushClientSecret { /** * To call when registering a pusher. It will return the existing secret or create a new one. + * + * @param userId the user the pusher is being registered for. */ suspend fun getSecretForUser(userId: SessionId): String /** * To call when receiving a push containing a client secret. * Return null if not found. + * + * @param clientSecret the secret carried by the incoming push. */ suspend fun getUserIdFromSecret(clientSecret: String): SessionId? } diff --git a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretFactory.kt b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretFactory.kt index d7ea7d5239..0b425b0115 100644 --- a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretFactory.kt +++ b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretFactory.kt @@ -8,6 +8,10 @@ package io.element.android.libraries.pushstore.api.clientsecret +/** + * Generates the client secrets used to attribute an incoming push to a session; see [PushClientSecret] for how they are used. + */ interface PushClientSecretFactory { + /** Returns a new random secret. */ fun create(): String } diff --git a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretStore.kt b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretStore.kt index ecb87b2b14..c325042ff8 100644 --- a/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretStore.kt +++ b/libraries/pushstore/api/src/main/kotlin/io/element/android/libraries/pushstore/api/clientsecret/PushClientSecretStore.kt @@ -10,9 +10,37 @@ package io.element.android.libraries.pushstore.api.clientsecret import io.element.android.libraries.matrix.api.core.SessionId +/** + * Persists the mapping between sessions and their push client secrets, in both directions. + */ interface PushClientSecretStore { + /** + * Stores the secret of a user, replacing any previous one. + * + * @param userId the user the secret belongs to. + * @param clientSecret the secret to store. + */ suspend fun storeSecret(userId: SessionId, clientSecret: String) + + /** + * Returns the stored secret of a user, or `null` when they have none yet. + * + * @param userId the user whose secret is requested. + */ suspend fun getSecret(userId: SessionId): String? + + /** + * Forgets the secret of a user, to be called when their session is removed. + * + * @param userId the user whose secret is erased. + */ suspend fun resetSecret(userId: SessionId) + + /** + * Reverse lookup used when a push arrives carrying only a secret. + * + * @param clientSecret the secret to resolve. + * @return the user it belongs to, or `null` when no session matches. + */ suspend fun getUserIdFromSecret(clientSecret: String): SessionId? } diff --git a/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectStateProvider.kt b/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectStatePreviewParam.kt similarity index 89% rename from libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectStateProvider.kt rename to libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectStatePreviewParam.kt index e57266b7e7..41fbf93532 100644 --- a/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectStateProvider.kt +++ b/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectStatePreviewParam.kt @@ -13,13 +13,14 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.designsystem.theme.components.SearchBarResultState import io.element.android.libraries.matrix.api.core.RoomAlias import io.element.android.libraries.matrix.api.core.RoomId +import io.element.android.libraries.matrix.ui.components.aMatrixUser import io.element.android.libraries.matrix.ui.components.aSelectRoomInfo import io.element.android.libraries.matrix.ui.model.SelectRoomInfo import io.element.android.libraries.roomselect.api.RoomSelectMode import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf -open class RoomSelectStateProvider : PreviewParameterProvider { +open class RoomSelectStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aRoomSelectState(), @@ -79,5 +80,13 @@ internal fun aRoomSelectRoomList() = persistentListOf( ), aSelectRoomInfo( roomId = RoomId("!room3:domain"), + name = "Alice", + heroes = persistentListOf( + aMatrixUser(id = "@alice:example.org", displayName = "Alice"), + ), + isDm = true, + ), + aSelectRoomInfo( + roomId = RoomId("!room4:domain"), ), ) diff --git a/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectView.kt b/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectView.kt index 7153306746..43b91068f9 100644 --- a/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectView.kt +++ b/libraries/roomselect/impl/src/main/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectView.kt @@ -15,11 +15,16 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items @@ -144,7 +149,13 @@ fun RoomSelectView( .consumeWindowInsets(paddingValues) ) { SearchBar( - modifier = Modifier.fillMaxWidth(), + modifier = Modifier + .fillMaxWidth() + .padding( + WindowInsets.safeDrawing + .only(WindowInsetsSides.Horizontal) + .asPaddingValues() + ), placeHolderTitle = stringResource(CommonStrings.action_search), queryState = state.searchQuery, active = state.isSearchActive, @@ -184,7 +195,10 @@ fun RoomSelectView( showVerticalSpace = true, ) if (state.resultState is SearchBarResultState.Results) { - LazyColumn(state = lazyListState) { + LazyColumn( + state = lazyListState, + contentPadding = lazyColumnContentPadding, + ) { items(state.resultState.results, key = { it.roomId.value }) { roomSummary -> Column { RoomSummaryView( @@ -260,10 +274,11 @@ private fun RoomSummaryView( maxLines = 1, overflow = TextOverflow.Ellipsis ) - // Alias - roomInfo.canonicalAlias?.let { alias -> + val otherUserId = roomInfo.heroes.singleOrNull()?.userId?.takeIf { roomInfo.isDm } + val subtitle = roomInfo.canonicalAlias?.value ?: otherUserId?.value + if (subtitle != null) { Text( - text = alias.value, + text = subtitle, color = ElementTheme.colors.textSecondary, style = ElementTheme.typography.fontBodySmRegular, maxLines = 1, @@ -281,7 +296,7 @@ private fun RoomSummaryView( @PreviewsDayNight @Composable -internal fun RoomSelectViewPreview(@PreviewParameter(RoomSelectStateProvider::class) state: RoomSelectState) = ElementPreview { +internal fun RoomSelectViewPreview(@PreviewParameter(RoomSelectStatePreviewParam::class) state: RoomSelectState) = ElementPreview { RoomSelectView( state = state, onDismiss = {}, diff --git a/libraries/roomselect/impl/src/test/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectViewTest.kt b/libraries/roomselect/impl/src/test/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectViewTest.kt new file mode 100644 index 0000000000..db0219bb04 --- /dev/null +++ b/libraries/roomselect/impl/src/test/kotlin/io/element/android/libraries/roomselect/impl/RoomSelectViewTest.kt @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +@file:OptIn(ExperimentalTestApi::class) + +package io.element.android.libraries.roomselect.impl + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.AndroidComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.v2.runAndroidComposeUiTest +import io.element.android.libraries.designsystem.theme.components.SearchBarResultState +import io.element.android.libraries.matrix.api.core.RoomId +import io.element.android.libraries.matrix.ui.components.aMatrixUser +import io.element.android.libraries.matrix.ui.components.aSelectRoomInfo +import io.element.android.tests.testutils.EnsureNeverCalled +import io.element.android.tests.testutils.EnsureNeverCalledWithParam +import io.element.android.tests.testutils.robolectric.RobolectricTest +import kotlinx.collections.immutable.persistentListOf +import org.junit.Test +import org.robolectric.annotation.Config + +class RoomSelectViewTest : RobolectricTest() { + @Config(qualifiers = "h1024dp") + @Test + fun `a room with a canonical alias renders the alias`() = runAndroidComposeUiTest { + setRoomSelectView( + aRoomSelectState( + resultState = SearchBarResultState.Results(aRoomSelectRoomList()), + ), + ) + onNodeWithText("Room with alias").assertIsDisplayed() + onNodeWithText("#alias:example.org").assertIsDisplayed() + } + + @Config(qualifiers = "h1024dp") + @Test + fun `a direct message without alias renders the matrix id of the other user`() = runAndroidComposeUiTest { + setRoomSelectView( + aRoomSelectState( + resultState = SearchBarResultState.Results(aRoomSelectRoomList()), + ), + ) + onNodeWithText("Alice").assertIsDisplayed() + onNodeWithText("@alice:example.org").assertIsDisplayed() + } + + @Config(qualifiers = "h1024dp") + @Test + fun `a room which is not a direct message does not render the matrix id of its hero`() = runAndroidComposeUiTest { + setRoomSelectView( + aRoomSelectState( + resultState = SearchBarResultState.Results( + persistentListOf( + aSelectRoomInfo( + roomId = RoomId("!room:domain"), + name = "Room with a single hero", + heroes = persistentListOf( + aMatrixUser(id = "@alice:example.org", displayName = "Alice"), + ), + ), + ) + ), + ), + ) + onNodeWithText("Room with a single hero").assertIsDisplayed() + onNodeWithText("@alice:example.org").assertDoesNotExist() + } +} + +private fun AndroidComposeUiTest.setRoomSelectView( + state: RoomSelectState, + onDismiss: () -> Unit = EnsureNeverCalled(), + onSubmit: (List) -> Unit = EnsureNeverCalledWithParam(), +) { + setContent { + RoomSelectView( + state = state, + onDismiss = onDismiss, + onSubmit = onSubmit, + ) + } +} diff --git a/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/SessionStore.kt b/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/SessionStore.kt index fb60311418..641a2afdf2 100644 --- a/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/SessionStore.kt +++ b/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/SessionStore.kt @@ -11,6 +11,11 @@ package io.element.android.libraries.sessionstorage.api import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map +/** + * Persists the logged in sessions and their access tokens, so the app can restore them after a restart. + * + * Sessions are ordered by last usage, which is what makes "the latest session" meaningful across the interface. + */ interface SessionStore { /** * A flow emitting the current logged in state. @@ -27,22 +32,32 @@ interface SessionStore { /** * Add a new session. If other sessions exist, the new one will be set as the latest used one, and * the added session position will be set to a value higher than the other session positions. + * + * @param sessionData the session to store, including its tokens. */ suspend fun addSession(sessionData: SessionData) /** * Will update the session data matching the userId, except the value of loginTimestamp. * No op if userId is not found in DB. + * + * @param sessionData the new content of the session. */ suspend fun updateData(sessionData: SessionData) /** * Update the user profile info of the session matching the userId. + * + * @param sessionId the session to update. + * @param displayName the new display name, or `null` when the user has none. + * @param avatarUrl the new avatar, or `null` when the user has none. */ suspend fun updateUserProfile(sessionId: String, displayName: String?, avatarUrl: String?) /** * Get the session data matching the userId, or null if not found. + * + * @param sessionId the session to read. */ suspend fun getSession(sessionId: String): SessionData? @@ -63,11 +78,15 @@ interface SessionStore { /** * Set the session with [sessionId] as the latest used one. + * + * @param sessionId the session to bring to the front of the ordering. */ suspend fun setLatestSession(sessionId: String) /** * Remove the session matching the sessionId. + * + * @param sessionId the session to forget, which also discards its tokens. */ suspend fun removeSession(sessionId: String) } diff --git a/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionListener.kt b/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionListener.kt index 8dadcafc7d..8d94af5b13 100644 --- a/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionListener.kt +++ b/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionListener.kt @@ -8,7 +8,22 @@ package io.element.android.libraries.sessionstorage.api.observer +/** + * Reacts to sessions being created or deleted; both methods have an empty default so a listener only overrides what it cares about. + */ interface SessionListener { + /** + * Called after a session has been stored, for instance following a login. + * + * @param userId the session that was created. + */ suspend fun onSessionCreated(userId: String) {} + + /** + * Called after a session has been removed, which is where per-session data should be cleaned up. + * + * @param userId the session that was deleted. + * @param wasLastSession true when no session remains, so app-wide data can be cleaned up too. + */ suspend fun onSessionDeleted(userId: String, wasLastSession: Boolean) {} } diff --git a/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionObserver.kt b/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionObserver.kt index fb120acd56..08925ee688 100644 --- a/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionObserver.kt +++ b/libraries/session-storage/api/src/main/kotlin/io/element/android/libraries/sessionstorage/api/observer/SessionObserver.kt @@ -8,7 +8,17 @@ package io.element.android.libraries.sessionstorage.api.observer +/** + * Notifies interested components when a session is created or deleted, so they can set up or clean up their own per-session data. + */ interface SessionObserver { + /** + * @param listener the listener to notify from now on. + */ fun addListener(listener: SessionListener) + + /** + * @param listener the listener to stop notifying. + */ fun removeListener(listener: SessionListener) } diff --git a/libraries/session-storage/impl/src/main/kotlin/io/element/android/libraries/sessionstorage/impl/di/SessionStorageModule.kt b/libraries/session-storage/impl/src/main/kotlin/io/element/android/libraries/sessionstorage/impl/di/SessionStorageBindingContainer.kt similarity index 96% rename from libraries/session-storage/impl/src/main/kotlin/io/element/android/libraries/sessionstorage/impl/di/SessionStorageModule.kt rename to libraries/session-storage/impl/src/main/kotlin/io/element/android/libraries/sessionstorage/impl/di/SessionStorageBindingContainer.kt index 8955aa4a27..e64268d608 100644 --- a/libraries/session-storage/impl/src/main/kotlin/io/element/android/libraries/sessionstorage/impl/di/SessionStorageModule.kt +++ b/libraries/session-storage/impl/src/main/kotlin/io/element/android/libraries/sessionstorage/impl/di/SessionStorageBindingContainer.kt @@ -23,10 +23,10 @@ import timber.log.Timber @BindingContainer @ContributesTo(AppScope::class) -object SessionStorageModule { +object SessionStorageBindingContainer { @Provides @SingleIn(AppScope::class) - fun provideMatrixDatabase( + fun providesSessionDatabase( @ApplicationContext context: Context, ): SessionDatabase { val name = "session_database" diff --git a/libraries/slashcommands/api/src/main/kotlin/io/element/android/libraries/slashcommands/api/SlashCommandService.kt b/libraries/slashcommands/api/src/main/kotlin/io/element/android/libraries/slashcommands/api/SlashCommandService.kt index 9dfca26078..7ae056e38b 100644 --- a/libraries/slashcommands/api/src/main/kotlin/io/element/android/libraries/slashcommands/api/SlashCommandService.kt +++ b/libraries/slashcommands/api/src/main/kotlin/io/element/android/libraries/slashcommands/api/SlashCommandService.kt @@ -9,7 +9,19 @@ package io.element.android.libraries.slashcommands.api import io.element.android.libraries.matrix.api.timeline.Timeline +/** + * Recognises and runs the slash commands the user can type in the composer, such as `/me` or `/join`. + * + * The composer first [parse]s what was typed, then hands the result to whichever proceed method matches its kind; navigation + * commands and the error cases are handled by the composer itself. + */ interface SlashCommandService { + /** + * Returns the commands whose name starts with what has been typed, so the composer can offer an autocomplete list. + * + * @param text the current composer content. + * @param isInThread whether the composer is in a thread, since not every command is available there. + */ suspend fun getSuggestions( text: String, isInThread: Boolean, @@ -17,6 +29,11 @@ interface SlashCommandService { /** * Parse the message and return a SlashCommand. + * Ordinary text comes back as `NotACommand`, and a malformed or unsupported command as one of the error cases, so this never throws. + * + * @param textMessage the composer content as plain text. + * @param formattedMessage the composer content as HTML, or `null` when unformatted. + * @param isInThreadTimeline whether the composer is in a thread. */ suspend fun parse( textMessage: CharSequence, @@ -26,6 +43,9 @@ interface SlashCommandService { /** * Proceed a SlashCommandSendMessage. + * + * @param slashCommand the parsed command, carrying the content to send. + * @param timeline the timeline to send it to. */ suspend fun proceedSendMessage( slashCommand: SlashCommand.SlashCommandSendMessage, @@ -33,7 +53,9 @@ interface SlashCommandService { ): Result /** - * Proceed a SlashCommandAdmin. + * Proceed a SlashCommandAdmin, i.e. one that acts on the room or its members rather than sending a message. + * + * @param slashCommand the parsed command to run. */ suspend fun proceedAdmin( slashCommand: SlashCommand.SlashCommandAdmin, diff --git a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/ComposerModeView.kt b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/ComposerModeView.kt index 9b2260d441..e4a1dbf5a1 100644 --- a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/ComposerModeView.kt +++ b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/ComposerModeView.kt @@ -192,7 +192,7 @@ private fun ReplyToModeView( @PreviewsDayNight @Composable internal fun ComposerModeViewPreview( - @PreviewParameter(MessageComposerModeSpecialProvider::class) mode: MessageComposerMode.Special + @PreviewParameter(MessageComposerModeSpecialPreviewParam::class) mode: MessageComposerMode.Special ) = ElementPreview { ComposerModeView( composerMode = mode, diff --git a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/MessageComposerModeSpecialProvider.kt b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/MessageComposerModeSpecialPreviewParam.kt similarity index 74% rename from libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/MessageComposerModeSpecialProvider.kt rename to libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/MessageComposerModeSpecialPreviewParam.kt index 60850d26c2..2fd367190e 100644 --- a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/MessageComposerModeSpecialProvider.kt +++ b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/MessageComposerModeSpecialPreviewParam.kt @@ -9,15 +9,15 @@ package io.element.android.libraries.textcomposer import androidx.compose.ui.tooling.preview.PreviewParameterProvider -import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsProvider +import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsPreviewParam import io.element.android.libraries.textcomposer.model.MessageComposerMode -class MessageComposerModeSpecialProvider : PreviewParameterProvider { +class MessageComposerModeSpecialPreviewParam : PreviewParameterProvider { override val values: Sequence = sequenceOf( aMessageComposerModeEdit() ) + - // Keep only 3 values from InReplyToDetailsProvider - InReplyToDetailsProvider().values.take(3).map { + // Keep only 3 values from InReplyToDetailsPreviewParam + InReplyToDetailsPreviewParam().values.take(3).map { aMessageComposerModeReply( replyToDetails = it ) diff --git a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/TextComposer.kt b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/TextComposer.kt index 0f62eb5234..fcb89247b5 100644 --- a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/TextComposer.kt +++ b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/TextComposer.kt @@ -76,7 +76,7 @@ import io.element.android.libraries.matrix.api.timeline.item.event.MessageConten import io.element.android.libraries.matrix.api.timeline.item.event.TextMessageType import io.element.android.libraries.matrix.api.timeline.item.event.toEventOrTransactionId import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetails -import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsProvider +import io.element.android.libraries.matrix.ui.messages.reply.InReplyToDetailsPreviewParam import io.element.android.libraries.matrix.ui.messages.reply.aProfileDetailsReady import io.element.android.libraries.testtags.TestTags import io.element.android.libraries.testtags.testTag @@ -131,6 +131,7 @@ fun TextComposer( resolveAtRoomMentionDisplay: () -> TextDisplay, modifier: Modifier = Modifier, showTextFormatting: Boolean = false, + isInThreadTimeline: Boolean = false, ) { val markdown = when (state) { is TextEditorState.Markdown -> state.state.text.value() @@ -153,13 +154,15 @@ fun TextComposer( .fillMaxSize() .height(IntrinsicSize.Min) - val placeholder = if (composerMode.inThread) { + val placeholder = if (composerMode.inThread || composerMode is MessageComposerMode.Normal && isInThreadTimeline) { stringResource(id = CommonStrings.action_reply_in_thread) } else if (composerMode is MessageComposerMode.Attachment || composerMode is MessageComposerMode.EditCaption) { stringResource(id = R.string.rich_text_editor_composer_caption_placeholder) } else { stringResource(id = R.string.rich_text_editor_composer_placeholder) } + val canSendTextMessage = markdown.isNotBlank() || composerMode is MessageComposerMode.Attachment + val textInput: @Composable () -> Unit = when (state) { is TextEditorState.Rich -> { val coroutineScope = rememberCoroutineScope() @@ -215,6 +218,7 @@ fun TextComposer( placeholder = placeholder, placeholderColor = ElementTheme.colors.textSecondary, onTyping = onTyping, + onSendMessage = { if (canSendTextMessage) onSendMessage() }, onReceiveSuggestion = onReceiveSuggestion, richTextEditorStyle = style, onSelectRichContent = onSelectRichContent, @@ -224,8 +228,6 @@ fun TextComposer( } } - val canSendTextMessage = markdown.isNotBlank() || composerMode is MessageComposerMode.Attachment - val textFormattingOptions: @Composable (() -> Unit)? = (state as? TextEditorState.Rich)?.let { @Composable { TextFormatting(state = it.richTextEditorState) } } @@ -243,6 +245,20 @@ fun TextComposer( canSendTextMessage, ) { when { + composerMode.isEditing -> EndButtonParams( + endButtonContentDescriptionResId = CommonStrings.action_send_edited_message, + endButtonClick = { + if (canSendTextMessage) { + onSendMessage() + } + }, + endButtonContent = @Composable { + SendButtonIcon( + canSendMessage = canSendTextMessage, + isEditing = true, + ) + }, + ) !canSendTextMessage -> when (voiceMessageState) { VoiceMessageState.Idle -> EndButtonParams( @@ -294,18 +310,6 @@ fun TextComposer( ) } } - composerMode.isEditing -> EndButtonParams( - endButtonContentDescriptionResId = CommonStrings.action_send_edited_message, - endButtonClick = { - onSendMessage() - }, - endButtonContent = @Composable { - SendButtonIcon( - canSendMessage = true, - isEditing = true, - ) - }, - ) else -> EndButtonParams( endButtonContentDescriptionResId = CommonStrings.action_send_message, endButtonClick = { @@ -857,7 +861,7 @@ internal fun MarkdownTextComposerEditPreview() = ElementPreview { @PreviewsDayNight @Composable -internal fun TextComposerReplyPreview(@PreviewParameter(InReplyToDetailsProvider::class) inReplyToDetails: InReplyToDetails) = ElementPreview { +internal fun TextComposerReplyPreview(@PreviewParameter(InReplyToDetailsPreviewParam::class) inReplyToDetails: InReplyToDetails) = ElementPreview { PreviewColumn( items = aTextEditorStateRichList() ) { textEditorState -> @@ -881,7 +885,7 @@ internal fun TextComposerReplyPreview(@PreviewParameter(InReplyToDetailsProvider heightDp = 800, ) @Composable -internal fun TextComposerReplyNotEncryptedPreview(@PreviewParameter(InReplyToDetailsProvider::class) inReplyToDetails: InReplyToDetails) = ElementPreview { +internal fun TextComposerReplyNotEncryptedPreview(@PreviewParameter(InReplyToDetailsPreviewParam::class) inReplyToDetails: InReplyToDetails) = ElementPreview { PreviewColumn( items = aTextEditorStateRichList(isRoomEncrypted = false) ) { textEditorState -> diff --git a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownEditText.kt b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownEditText.kt index bd808c9acb..8cc06c77c3 100644 --- a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownEditText.kt +++ b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownEditText.kt @@ -9,6 +9,8 @@ package io.element.android.libraries.textcomposer.components.markdown import android.content.Context +import android.view.KeyCharacterMap +import android.view.KeyEvent import android.view.View import androidx.appcompat.widget.AppCompatEditText @@ -17,8 +19,27 @@ internal class MarkdownEditText( ) : AppCompatEditText(context) { var onSelectionChangeListener: ((Int, Int) -> Unit)? = null + var onEnterKeyListener: (() -> Boolean)? = null + private var isModifyingText = false + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (event.keyCode == KeyEvent.KEYCODE_ENTER && + !event.isShiftPressed && + event.deviceId != KeyCharacterMap.VIRTUAL_KEYBOARD + ) { + val listener = onEnterKeyListener + if (listener != null) { + return when (event.action) { + KeyEvent.ACTION_UP -> true + KeyEvent.ACTION_DOWN -> if (event.repeatCount == 0) listener() else true + else -> super.dispatchKeyEvent(event) + } + } + } + return super.dispatchKeyEvent(event) + } + fun updateEditableText(charSequence: CharSequence) { isModifyingText = true editableText.clear() diff --git a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownTextInput.kt b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownTextInput.kt index 064ef03106..63f9e0a8ea 100644 --- a/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownTextInput.kt +++ b/libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/components/markdown/MarkdownTextInput.kt @@ -51,6 +51,7 @@ fun MarkdownTextInput( placeholder: String, placeholderColor: androidx.compose.ui.graphics.Color, onTyping: (Boolean) -> Unit, + onSendMessage: () -> Unit, onReceiveSuggestion: (Suggestion?) -> Unit, richTextEditorStyle: RichTextEditorStyle, onSelectRichContent: ((Uri) -> Unit)?, @@ -132,6 +133,10 @@ fun MarkdownTextInput( update = { editText -> editText.contentDescription = placeholder editText.applyStyleInCompose(richTextEditorStyle) + editText.onEnterKeyListener = { + onSendMessage() + true + } val text = state.text.value() mentionSpanUpdater.updateMentionSpans(text) if (state.text.needsDisplaying()) { @@ -210,6 +215,7 @@ internal fun MarkdownTextInputPreview() { placeholder = "Placeholder", placeholderColor = ElementTheme.colors.textSecondary, onTyping = {}, + onSendMessage = {}, onReceiveSuggestion = {}, richTextEditorStyle = style, onSelectRichContent = {}, diff --git a/libraries/textcomposer/impl/src/main/res/values-ar/translations.xml b/libraries/textcomposer/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..594a06ab15 --- /dev/null +++ b/libraries/textcomposer/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,33 @@ + + + "إضافة مرفق" + "تبديل قائمة النقاط" + "إلغاء وإغلاق خيارات تنسيق النص" + "تبديل كتلة التعليمات البرمجية" + "أضف تعليقًا توضيحيًا" + "رسالة مشفّرة…" + "راسل…" + "رسالة غير مشفّرة…" + "إنشاء رابط" + "تعديل الرابط" + "%1$s، الحالة: %2$s" + "تطبيق التنسيق الغامق" + "تطبيق التنسيق المائل" + "معطّل" + "غير مفعّل" + "مفعّل" + "تطبيق التنسيق الذي يتوسّطه خط" + "تطبيق التنسيق الذي تحته خط" + "تبديل وضع ملء الشاشة" + "ترك مسافة بادئة" + "تطبيق تنسيق الكود المضمن" + "تعيين الرابط" + "تبديل القائمة المرقمة" + "فتح خيارات كتابة الرسالة" + "تبديل الاقتباس" + "حذف الرابط" + "إزالة المسافة البادئة" + "الرابط" + "قد لا تكون التعليقات التوضيحية مرئية للأشخاص الذين يستخدمون تطبيقات أقدم." + "اضغط مطولًا للتسجيل" + diff --git a/libraries/textcomposer/impl/src/main/res/values-es/translations.xml b/libraries/textcomposer/impl/src/main/res/values-es/translations.xml index 68b8b7b02c..16016658e5 100644 --- a/libraries/textcomposer/impl/src/main/res/values-es/translations.xml +++ b/libraries/textcomposer/impl/src/main/res/values-es/translations.xml @@ -10,9 +10,12 @@ "Mensaje no cifrado…" "Crear un enlace" "Editar enlace" + "%1$s, estado: %2$s" "Aplicar formato negrita" "Aplicar formato cursiva" "deshabilitado" + "desactivado" + "activado" "Aplicar formato tachado" "Aplicar formato de subrayado" "Pantalla completa" diff --git a/libraries/textcomposer/impl/src/main/res/values-fa/translations.xml b/libraries/textcomposer/impl/src/main/res/values-fa/translations.xml index fd55fdf9d9..c3fcffc642 100644 --- a/libraries/textcomposer/impl/src/main/res/values-fa/translations.xml +++ b/libraries/textcomposer/impl/src/main/res/values-fa/translations.xml @@ -28,5 +28,6 @@ "برداشتن پیوند" "تونرفتگی" "پیوند" + "ممکن است زیرنویس‌ها برای افرادی که از برنامه‌های قدیمی‌تر استفاده می‌کنند قابل مشاهده نباشند." "نگه داشتن برای ضبط" diff --git a/libraries/textcomposer/impl/src/test/kotlin/io/element/android/libraries/textcomposer/TextComposerEndButtonTest.kt b/libraries/textcomposer/impl/src/test/kotlin/io/element/android/libraries/textcomposer/TextComposerEndButtonTest.kt new file mode 100644 index 0000000000..c979e8c909 --- /dev/null +++ b/libraries/textcomposer/impl/src/test/kotlin/io/element/android/libraries/textcomposer/TextComposerEndButtonTest.kt @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2026 Element Creations Ltd. + * Copyright 2026 New Vector Ltd. + * + * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial. + * Please see LICENSE files in the repository root for full details. + */ + +@file:OptIn(ExperimentalTestApi::class) + +package io.element.android.libraries.textcomposer + +import androidx.activity.ComponentActivity +import androidx.compose.ui.test.AndroidComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.v2.runAndroidComposeUiTest +import io.element.android.libraries.textcomposer.model.MessageComposerMode +import io.element.android.libraries.textcomposer.model.VoiceMessageState +import io.element.android.libraries.textcomposer.model.aTextEditorStateMarkdown +import io.element.android.libraries.ui.strings.CommonStrings +import io.element.android.tests.testutils.robolectric.RobolectricTest +import io.element.android.wysiwyg.display.TextDisplay +import org.junit.Test + +class TextComposerEndButtonTest : RobolectricTest() { + @Test + fun `editing a message with text shows the send edited message button`() = runAndroidComposeUiTest { + setTextComposer(text = "Some text", composerMode = aMessageComposerModeEdit()) + onNodeWithContentDescription(getString(CommonStrings.action_send_edited_message)).assertIsDisplayed() + } + + @Test + fun `emptying the composer while editing keeps the send edited message button`() = runAndroidComposeUiTest { + setTextComposer(text = "", composerMode = aMessageComposerModeEdit()) + onNodeWithContentDescription(getString(CommonStrings.action_send_edited_message)).assertIsDisplayed() + onNodeWithContentDescription(getString(CommonStrings.a11y_voice_message_record)).assertDoesNotExist() + } + + @Test + fun `emptying the composer while editing a caption keeps the send edited message button`() = runAndroidComposeUiTest { + setTextComposer(text = "", composerMode = aMessageComposerModeEditCaption(content = "An existing caption")) + onNodeWithContentDescription(getString(CommonStrings.action_send_edited_message)).assertIsDisplayed() + onNodeWithContentDescription(getString(CommonStrings.a11y_voice_message_record)).assertDoesNotExist() + } + + @Test + fun `an empty composer outside of edition still offers to record a voice message`() = runAndroidComposeUiTest { + setTextComposer(text = "", composerMode = MessageComposerMode.Normal) + onNodeWithContentDescription(getString(CommonStrings.a11y_voice_message_record)).assertIsDisplayed() + } + + private fun AndroidComposeUiTest.getString(resId: Int): String { + return activity!!.getString(resId) + } + + private fun AndroidComposeUiTest.setTextComposer( + text: String, + composerMode: MessageComposerMode, + ) { + setContent { + TextComposer( + state = aTextEditorStateMarkdown(initialText = text, initialFocus = true), + voiceMessageState = VoiceMessageState.Idle, + composerMode = composerMode, + onRequestFocus = {}, + onSendMessage = {}, + onResetComposerMode = {}, + onAddAttachment = {}, + onDismissTextFormatting = {}, + onVoiceRecorderEvent = {}, + onVoicePlayerEvent = {}, + onSendVoiceMessage = {}, + onDeleteVoiceMessage = {}, + onError = {}, + onTyping = {}, + onReceiveSuggestion = {}, + onSelectRichContent = null, + resolveMentionDisplay = { _, _ -> TextDisplay.Plain }, + resolveAtRoomMentionDisplay = { TextDisplay.Plain }, + ) + } + } +} diff --git a/libraries/textcomposer/impl/src/test/kotlin/io/element/android/libraries/textcomposer/impl/components/markdown/MarkdownTextInputTest.kt b/libraries/textcomposer/impl/src/test/kotlin/io/element/android/libraries/textcomposer/impl/components/markdown/MarkdownTextInputTest.kt index ba49428cae..d08048241e 100644 --- a/libraries/textcomposer/impl/src/test/kotlin/io/element/android/libraries/textcomposer/impl/components/markdown/MarkdownTextInputTest.kt +++ b/libraries/textcomposer/impl/src/test/kotlin/io/element/android/libraries/textcomposer/impl/components/markdown/MarkdownTextInputTest.kt @@ -10,6 +10,8 @@ package io.element.android.libraries.textcomposer.impl.components.markdown +import android.view.KeyCharacterMap +import android.view.KeyEvent import android.widget.EditText import androidx.activity.ComponentActivity import androidx.compose.ui.test.AndroidComposeUiTest @@ -32,12 +34,51 @@ import io.element.android.libraries.textcomposer.model.MarkdownTextEditorState import io.element.android.libraries.textcomposer.model.Suggestion import io.element.android.libraries.textcomposer.model.SuggestionType import io.element.android.libraries.textcomposer.model.aMarkdownTextEditorState +import io.element.android.tests.testutils.EnsureCalledOnce import io.element.android.tests.testutils.EnsureCalledOnceWithParam import io.element.android.tests.testutils.EventsRecorder import io.element.android.tests.testutils.robolectric.RobolectricTest import org.junit.Test class MarkdownTextInputTest : RobolectricTest() { + @Test + fun `pressing enter on a physical keyboard sends the message`() = runAndroidComposeUiTest { + val state = aMarkdownTextEditorState(initialText = "Hello", initialFocus = true) + val onSendMessage = EnsureCalledOnce() + setMarkdownTextInput(state = state, onSendMessage = onSendMessage) + val editor = activity!!.findEditor() + editor.pressEnter() + awaitIdle() + onSendMessage.assertSuccess() + assertThat(editor.editableText.toString()).isEqualTo("Hello") + } + + @Test + fun `pressing shift enter on a physical keyboard inserts a new line`() = runAndroidComposeUiTest { + val state = aMarkdownTextEditorState(initialText = "Hello", initialFocus = true) + var sendCount = 0 + setMarkdownTextInput(state = state, onSendMessage = { sendCount++ }) + val editor = activity!!.findEditor() + editor.setSelection(editor.editableText.length) + editor.pressEnter(metaState = KeyEvent.META_SHIFT_ON) + awaitIdle() + assertThat(sendCount).isEqualTo(0) + assertThat(editor.editableText.toString()).isEqualTo("Hello\n") + } + + @Test + fun `pressing enter on the soft keyboard does not send the message`() = runAndroidComposeUiTest { + val state = aMarkdownTextEditorState(initialText = "Hello", initialFocus = true) + var sendCount = 0 + setMarkdownTextInput(state = state, onSendMessage = { sendCount++ }) + val editor = activity!!.findEditor() + editor.setSelection(editor.editableText.length) + editor.pressEnter(deviceId = KeyCharacterMap.VIRTUAL_KEYBOARD) + awaitIdle() + assertThat(sendCount).isEqualTo(0) + assertThat(editor.editableText.toString()).isEqualTo("Hello\n") + } + @Test fun `when user types onTyping is triggered with value 'true'`() = runAndroidComposeUiTest { val state = aMarkdownTextEditorState(initialFocus = true) @@ -150,6 +191,7 @@ class MarkdownTextInputTest : RobolectricTest() { state: MarkdownTextEditorState = aMarkdownTextEditorState(), onTyping: (Boolean) -> Unit = {}, onSuggestionReceived: (Suggestion?) -> Unit = {}, + onSendMessage: (() -> Unit) = {}, ) { setContent { val style = ElementRichTextEditorStyle.composerStyle(hasFocus = state.hasFocus) @@ -161,6 +203,27 @@ class MarkdownTextInputTest : RobolectricTest() { onReceiveSuggestion = onSuggestionReceived, richTextEditorStyle = style, onSelectRichContent = null, + onSendMessage = onSendMessage, + ) + } + } + + private fun EditText.pressEnter( + metaState: Int = 0, + deviceId: Int = PHYSICAL_KEYBOARD_DEVICE_ID, + ) { + listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP).forEach { action -> + dispatchKeyEvent( + KeyEvent( + 0L, + 0L, + action, + KeyEvent.KEYCODE_ENTER, + 0, + metaState, + deviceId, + 0, + ) ) } } @@ -168,4 +231,8 @@ class MarkdownTextInputTest : RobolectricTest() { private fun ComponentActivity.findEditor(): EditText { return window.decorView.findViewWithTag(TestTags.plainTextEditor.value) } + + private companion object { + const val PHYSICAL_KEYBOARD_DEVICE_ID = 1 + } } diff --git a/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootNavigator.kt b/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootNavigator.kt index a4be22e70b..69a0561d25 100644 --- a/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootNavigator.kt +++ b/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootNavigator.kt @@ -8,6 +8,10 @@ package io.element.android.libraries.troubleshoot.api.test +/** + * Lets a troubleshooting test's quick fix send the user to another screen, without the test itself knowing about navigation. + */ interface NotificationTroubleshootNavigator { + /** Opens the blocked users screen, so the user can unblock someone whose messages were being filtered out. */ fun navigateToBlockedUsers() } diff --git a/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootTest.kt b/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootTest.kt index 27f3bcf8ed..98898ad483 100644 --- a/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootTest.kt +++ b/libraries/troubleshoot/api/src/main/kotlin/io/element/android/libraries/troubleshoot/api/test/NotificationTroubleshootTest.kt @@ -20,11 +20,36 @@ import kotlinx.coroutines.flow.StateFlow * the component they're injected into is bound to [SessionScope] and so should these (https://github.com/ZacSweers/metro/issues/1932). */ interface NotificationTroubleshootTest { + /** Position of this test in the list shown to the user; tests run in ascending order. */ val order: Int + + /** The current state of this test, which the UI observes to show it as idle, running, successful or failed. */ val state: StateFlow + + /** + * Whether this test applies to the current setup, so that irrelevant tests are hidden rather than shown as failing. + * + * @param data the current push provider and distributor, used to decide relevance. + */ fun isRelevant(data: TestFilterData): Boolean = true + + /** + * Runs the test, reporting its outcome through [state] rather than by returning or throwing. + * + * @param coroutineScope the scope to launch any work that must outlive the call itself. + */ suspend fun run(coroutineScope: CoroutineScope) + + /** Returns the test to its idle state so it can be run again. */ suspend fun reset() + + /** + * Attempts to fix what this test detected, for the tests that can offer it. Throws by default, so check the state's quick fix + * flag before calling. + * + * @param coroutineScope the scope to launch any work that must outlive the call itself. + * @param navigator used by the fixes that have to send the user to another screen. + */ suspend fun quickFix( coroutineScope: CoroutineScope, navigator: NotificationTroubleshootNavigator, diff --git a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsStateProvider.kt b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsStatePreviewParam.kt similarity index 97% rename from libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsStateProvider.kt rename to libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsStatePreviewParam.kt index 5cc565559e..54dd40617f 100644 --- a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsStateProvider.kt +++ b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsStatePreviewParam.kt @@ -12,7 +12,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.troubleshoot.api.test.NotificationTroubleshootTestState import kotlinx.collections.immutable.toImmutableList -open class TroubleshootNotificationsStateProvider : PreviewParameterProvider { +open class TroubleshootNotificationsStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aTroubleshootNotificationsState( diff --git a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsView.kt b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsView.kt index 4e0f89155d..d168cfd764 100644 --- a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsView.kt +++ b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/TroubleshootNotificationsView.kt @@ -207,7 +207,7 @@ private fun ColumnScope.TestSuiteView( @PreviewsDayNight @Composable internal fun TroubleshootNotificationsViewPreview( - @PreviewParameter(TroubleshootNotificationsStateProvider::class) state: TroubleshootNotificationsState, + @PreviewParameter(TroubleshootNotificationsStatePreviewParam::class) state: TroubleshootNotificationsState, ) = ElementPreview { TroubleshootNotificationsView( state = state, diff --git a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryStateProvider.kt b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryStatePreviewParam.kt similarity index 97% rename from libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryStateProvider.kt rename to libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryStatePreviewParam.kt index e7384048f4..968de5534c 100644 --- a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryStateProvider.kt +++ b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryStatePreviewParam.kt @@ -16,7 +16,7 @@ import io.element.android.libraries.matrix.api.core.SessionId import io.element.android.libraries.push.api.history.PushHistoryItem import kotlinx.collections.immutable.toImmutableList -open class PushHistoryStateProvider : PreviewParameterProvider { +open class PushHistoryStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aPushHistoryState(), diff --git a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryView.kt b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryView.kt index 21e9c64139..7315cb4e5a 100644 --- a/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryView.kt +++ b/libraries/troubleshoot/impl/src/main/kotlin/io/element/android/libraries/troubleshoot/impl/history/PushHistoryView.kt @@ -268,7 +268,7 @@ private fun PushHistoryItem( @PreviewsDayNight @Composable internal fun PushHistoryViewPreview( - @PreviewParameter(PushHistoryStateProvider::class) state: PushHistoryState, + @PreviewParameter(PushHistoryStatePreviewParam::class) state: PushHistoryState, ) = ElementPreview { PushHistoryView( state = state, diff --git a/libraries/troubleshoot/impl/src/main/res/values-ar/translations.xml b/libraries/troubleshoot/impl/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..85331aa86a --- /dev/null +++ b/libraries/troubleshoot/impl/src/main/res/values-ar/translations.xml @@ -0,0 +1,12 @@ + + + "سجل الإشعارات الفورية" + "تشغيل الاختبارات" + "تشغيل الاختبارات مرة أخرى" + "فشلت بعض الاختبارات. يرجى التحقق من التفاصيل." + "شغّل الاختبارات لاكتشاف أي مشكلة في إعداداتك قد تجعل الإشعارات لا تعمل كما هو متوقع." + "محاولة الإصلاح" + "اجتازت جميع الاختبارات بنجاح." + "استكشاف أخطاء الإشعارات وإصلاحها" + "تتطلب بعض الاختبارات انتباهك. يرجى التحقق من التفاصيل." + diff --git a/libraries/ui-strings/src/main/res/values-ar/translations.xml b/libraries/ui-strings/src/main/res/values-ar/translations.xml new file mode 100644 index 0000000000..d8862e6dc7 --- /dev/null +++ b/libraries/ui-strings/src/main/res/values-ar/translations.xml @@ -0,0 +1,611 @@ + + + "أضف صورة رمزية" + "أضف تفاعل: %1$s" + "العنوان" + "الصورة الرمزية" + "مسح حقل البحث" + "تصغير حقل نص الرسالة" + "تقليل عدد الأصوات المسموح بها لكل شخص" + "زيادة عدد الأصوات المسموح بها لكل شخص" + "احذف" + + "تم إدخال %1$d أرقام" + "تم إدخال %1$d رقم" + "تم إدخال %1$d رقمين" + "تم إدخال %1$d أرقام" + "تم إدخال %1$d رقمًا" + "تم إدخال %1$d رقم" + + "المدة: %1$s" + "تعديل الصورة الرمزية" + "العنوان الكامل سيكون %1$s" + "تفاصيل التشفير" + "تكبير حقل نص الرسالة" + "أخفِ كلمة السر" + "معلومات" + "انضم للمكالمة" + "الانتقال للأسفل" + "الانتقال إلى الرسائل غير المقروءة" + "انقل الخريطة إلى موقعي" + "الإشارات فقط" + "مكتوم" + "إشارات جديدة" + "رسائل جديدة" + "مكالمة جارية" + "صورة رمزية لمستخدم آخر" + "الصفحة %1$d" + "إيقاف مؤقت" + "الرسالة الصوتية، المدة: %1$s ، الموضع الحالي: %2$s" + "معاينة الصورة" + "حقل الرمز السري (PIN) " + "موقع محدد" + "تشغيل" + "سرعة التشغيل" + "استفتاء" + "استفتاء منتهٍ" + "الموضع: %1$s" + "رمز QR" + "تفاعل مع %1$s" + "تفاعل مع الرموز التعبيرية الأخرى" + "قرأ %1$s و%2$s الرسالة السابقة" + + "قرأ %1$s و%2$d آخرون الرسالة السابقة" + "قرأ %1$s و%2$d آخر الرسالة السابقة" + "قرأ %1$s و%2$d آخران الرسالة السابقة" + "قرأ %1$s و%2$d آخرون الرسالة السابقة" + "قرأ %1$s و%2$d آخر الرسالة السابقة" + "قرأ %1$s و%2$d آخر الرسالة السابقة" + + "قرأ %1$s الرسالة السابقة" + "إظهار كل إيصالات القراءة" + "أزِل التفاعل: %1$s" + "أزِل التفاعل بـ %1$s" + "الصورة الرمزية للغرفة" + "إرسال ملفات" + "موقع المرسل" + "أرسلها %1$s في %2$s" + "إجراء مقيد زمنياً، لديك دقيقة واحدة للتحقق " + "الإعدادات، إجراء مطلوب" + "إظهار كلمة السر" + "بدء مكالمة" + "بدء مكالمة فيديو" + "بدء مكالمة صوتية" + "سلسلة في %1$s" + "سلاسل في %1$s" + "غرفة مستبدلة" + "الصورة الرمزية للمستخدم" + "قائمة المستخدم" + "معاينة الفيديو" + "عرض الصورة الرمزية" + "عرض التفاصيل" + "رسالة صوتية، المدة: %1$s" + "تسجيل رسالة صوتية." + "إيقاف التسجيل" + "الصورة الرمزية الخاصة بك" + "قبول" + "أضف وصف" + "إضافة غرف موجودة" + "أضف إلى الجدول الزمني" + "رجوع" + "مكالمة" + "الغاء" + "ليس الآن" + "اختيار ملف" + "اختيار صورة" + "مسح" + "إغلاق" + "أتمم التحقق" + "تأكيد" + "تأكيد كلمة المرور" + "المتابعة" + "نسخ" + "نسخ التعليق التوضيحي" + "نسخ الرابط" + "نسخ رابط الرسالة" + "انسخ النص" + "إنشاء" + "إنشاء غرفة" + "إنشاء مساحة" + "تعطيل" + "تعطيل الحساب" + "رفض" + "رفض وحظر" + "حذف" + "حذف الحساب" + "حذف الملف" + "حذف الاستطلاع" + "إلغاء تحديد الكل" + "تعطيل" + "تجاهل" + "إغلاق" + "تم" + "تنزيل" + "تعديل" + "تعديل التعليق التوضيحي" + "تعديل الاستفتاء" + "تمكين" + "إنهاء الاستفتاء" + "إدخال رمز PIN" + "استكشاف المساحات العامة" + "إنهاء" + "أنسيت كلمة السر؟" + "إعادة توجيه" + "ارجع" + "الانتقال إلى الأدوار والصلاحيات" + "اذهب إلى الإعدادات" + "تجاهل" + "دعوة " + "دعوة أشخاص" + "قم بدعوة الأصدقاء إلى %1$s" + "دعوة أشخاص إلى %1$s" + "الدعوات" + "إنضمام" + "تعلم المزيد" + "مغادرة" + "مغادرة المحادثة" + "مغادرة الغرفة" + "مغادرة المساحة" + "تحميل المزيد" + "إدارة الحساب" + "إدارة الحساب والأجهزة" + "إدارة الأجهزة" + "إدارة الغرف" + "إرسال رسالة" + "تصغير" + "التالي" + "لا" + "ليس الآن" + "حسناً" + "فتح قائمة السياق" + "الإعدادات" + "فتح باستخدام" + "تثبيت" + "رد سريع " + "عبارة" + "تفاعَل" + "رفض" + "ازالة" + "إزالة التعليق التوضيحي" + "إزالة الرسالة" + "رد" + "ردّ في ثريد" + "إبلاغ" + "الإبلاغ عن مشكلة" + "الابلاغ عن المحتوى" + "الإبلاغ عن المحادثة" + "الإبلاغ عن الغرفة" + "إعادة تعيين" + "إعادة تعيين الهوية" + "اعادة المحاولة" + "أعد محاولة فك التشفير" + "حفظ" + "بحث" + "تحديد الكل" + "ارسال" + "إرسال الرسالة المعدّلة" + "أرسل رسالة" + "إرسال رسالة صوتية" + "مشاركة" + "مشاركة رابط" + "مشاركة الموقع المباشر" + "إظهار" + "تسجيل الدخول مرة أخرى" + "إزالة هذا الجهاز" + "إزالة هذا الجهاز على أي حال" + "تخطي" + "ابدأ" + "ابدأ المحادثة" + "البدء من جديد" + "ابدأ التحقق" + "انقر لتحميل الخريطة" + "إيقاف" + "التقاط صورة" + "اضغط لعرض الخيارات" + "ترجمة" + "حاول مرة أخرى" + "إلغاء التثبيت" + "مكالمة فيديو" + "عرض" + "عرض في المخطط الزمني" + "عرض المصدر" + "مكالمة صوتية" + "نعم" + "نعم، حاول مرة أخرى" + "يدعم خادمك الآن بروتوكولًا جديدًا أسرع. سجّل الخروج ثم سجّل الدخول مرة أخرى للترقية الآن. سيساعدك القيام بذلك الآن على تجنب تسجيل خروج قسري عند إزالة البروتوكول القديم لاحقًا." + "ترقية متاحة" + "حول التطبيق" + "سياسة الاستخدام المقبول" + "إضافة حساب" + "إضافة حساب آخر" + "جارٍ إضافة تعليق توضيحي" + "إعدادات متقدمة" + "صورة" + "التحليلات" + "قمتَ بمغادرة المجموعة" + "تم تسجيل خروجك من الجلسة" + "المظهر" + "الصوت" + "تجريبي" + "المستخدمون المحظورون" + "فقاعات" + "تم رفض المكالمة" + "مكالمة جارية" + "بدأت المكالمة" + "رفضت مكالمة" + "النسخ الاحتياطي للدردشة" + "تم النسخ إلى الحافظة" + "حقوق الملكية" + "يتم إنشاء الغرفة…" + "جارٍ إنشاء المساحة…" + "تم إلغاء الطلب" + "غادرت الغرفة" + "غادرت المساحة" + "تم رفض الدعوة" + "خطأ في فك التشفير" + "الوصف" + "خيارات المطوِّرين" + "معرّف الجهاز" + "الدردشة المباشرة" + "عدم إظهار هذا مرة أخرى" + "فشل التنزيل" + "جارٍ التنزيل" + "(مُعدّلة)" + "تعديل" + "جارٍ تعديل التعليق التوضيحي" + "* %1$s %2$s" + "ملف فارغ" + "التشفير" + "التشفير مفعّل" + "ينتهي عند %1$s" + "أدخل رمز PIN الخاص بك" + "خطأ" + "حدث خطأ، قد لا تتلقى إشعارات للرسائل الجديدة. يرجى استكشاف أخطاء الإشعارات وإصلاحها من الإعدادات. + +السبب: %1$s." + "الجميع" + "فشل" + "مفضلة" + "مضافة إلى المفضلة" + "جارٍ مزامنة الإشعارات…" + "ملف" + "تمت إزالة الملف" + "تم حفظ الملف" + "تم حفظ الملف في التنزيلات" + "إعادة توجيه الرسالة" + "المستخدمة بكثرة" + "المعرض" + "GIF" + "مكالمة جماعية جارية" + "صورة" + "ردٌّ على %1$s" + "تثبيت ملف الـAPK" + "لم يتم العثور على الـMatrix ID هذا، ولذا فالدعوة قد لا تكون وصلت." + "تتم مغادرة المجموعة" + "جارٍ مغادرة المساحة" + "تم نسخ السطر إلى الحافظة" + "تم نسخ الرابط إلى الحافظة" + "ربط جهاز جديد" + "الموقع المباشر" + "انتهت مشاركة الموقع المباشر" + "جارٍ التحميل…" + "جارٍ تحميل المزيد…" + + "%d آخرون" + "%d آخر" + "%d آخران" + "%d آخرون" + "%d آخر" + "%d آخر" + + + "%1$d أعضاء" + "%1$d عضو" + "%1$d عضو" + "%1$d أعضاء" + "%1$d عضو" + "%1$d عضو" + + "رسالة" + "إجراءات الرسالة" + "فشل إرسال الرسالة" + "مظهر الرسائل" + "حُذِفت الرسالة" + "حديث" + "كتم" + "الاسم" + "%1$s (%2$s)" + "لا نتائج" + "لا يوجد اسم للغرفة" + "لا يوجد اسم للمساحة" + "غير مشفّر" + "غير متصل" + "تراخيص المصادر المفتوحة" + "أو" + "خيارات أخرى" + "كلمة السر" + "الأشخاص" + "الرابط الثابت" + "الإذن" + "مثبّتة" + "يرجى التحقق من اتصالك بالإنترنت" + "يرجى الانتظار…" + "أمتأكد من رغبتك بإنهاء الاستفتاء؟" + "استفتاء: %1$s" + "استطلاع" + "مجموع الأصوات: %1$s" + "ستظهر النتائج في حين انتهاء الاستفتاء" + + "%d صوت" + "%d صوت" + "%d صوت" + "%d أصوات" + "%d صوت" + "%d صوت" + + "جارٍ التحضير…" + "سياسة الخصوصية" + "خاصة" + "غرفة خاصة" + "مساحة خاصة" + "عامة" + "غرفة عامة" + "مساحة عامة" + "التفاعل" + "ردود الفعل" + "السبب" + "مفتاح الاسترداد" + "يتم التحديث…" + "جارٍ الإزالة…" + + "%1$d ردود" + "%1$d رد" + "%1$d ردّان" + "%1$d ردود" + "%1$d ردًا" + "%1$d رد" + + "الرد على %1$s" + "الإبلاغ عن مشكلة" + "أُرسِل الإبلاغ" + "محرر النص المنسق" + "الدور" + "غرفة" + "اسم الغرفة" + "مثال: اسم مشروعك" + + "%1$d غرف" + "%1$d غرفة" + "%1$d غرفتان" + "%1$d غرف" + "%1$d غرفة" + "%1$d غرفة" + + "تم حفظ التغييرات" + "جارٍ الحفظ" + "قفل الشاشة" + "اِبحث عن شخص ما" + "نتائج البحث" + "الأمان" + "شوهد بواسطة" + "اختر حسابًا" + + "تم تحديد %1$d" + "تم تحديد %1$d" + "تم تحديد %1$d" + "تم تحديد %1$d" + "تم تحديد %1$d" + "تم تحديد %1$d" + + "إرسال إلى" + "جارٍ الإرسال…" + "فشل الإرسال" + "تم الإرسال" + ". " + "السيرفر غير مدعوم" + "الخادم غير متاح" + "عنوان URL للسيرفر" + "الإعدادات" + "مشاركة المساحة" + "يمكن للأعضاء الجدد رؤية السجل" + "تمت مشاركة الموقع المباشر" + "الموقع المشارَك" + "مساحة مشتركة" + "جارٍ إزالة الجهاز" + "حدث خطأ ما" + "واجهنا مشكلة. يرجى المحاولة مرة أخرى." + "مساحة" + "أعضاء المساحة" + "ما موضوع هذه المساحة؟" + + "%1$d مساحات" + "%1$d مساحة" + "%1$d مساحتان" + "%1$d مساحات" + "%1$d مساحة" + "%1$d مساحة" + + "يتم بدء المحادثة…" + "مُلصَق" + "تمت العملية بنجاح" + "مقترح" + "اقتراحات" + "تتم المزامنة" + "نص" + "إشعارات الجهات الخارجية" + "ثريد" + "السلاسل" + "الموضوع" + "ما موضوع هذه الغرفة؟" + "غير قادر على فك التشفير" + "أُرسلت من جهاز غير آمن" + "ليس لديك صلاحية الوصول إلى هذه الرسالة" + "تمت إعادة تعيين الهوية الرقمية الموثّقة للمرسل" + "لم يتم التمكن من إرسال الدعوة إلى عضو أو أكثر." + "غير قادر على إرسال الدعوة (الدعوات)" + "إلغاء القفل" + "إلغاء الكتم" + "مكالمة غير مدعومة" + "حدث غير مدعوم" + "بدأ %1$s مكالمة" + "اسم المستخدم" + "أُلغيَ التحقق" + "اكتمل التحقق" + "فشل التحقق" + "تم التحقق" + "التحقّق من الجهاز" + "تحقّق من الهوية" + "تحقّق من المستخدم" + "فيديو" + "جودة عالية" + "أفضل جودة، لكن بحجم ملف أكبر" + "جودة منخفضة" + "أسرع سرعة رفع وأصغر حجم ملف" + "جودة قياسية" + "توازن بين الجودة وسرعة الرفع" + "رسالة صوتية" + "جارٍ الانتظار…" + "في انتظار هذه الرسالة" + "في انتظار الموقع المباشر…" + "يمكن لأي شخص رؤية السجل" + "أنت" + "التنزيل غير متاح." + "لم يتم العثور على الملف" + "جاري المسح…" + "تم تعطيل المعاينة والتنزيل." + "الملف غير آمن" + "شارك %1$s (%2$s) هذه الرسالة لأنك لم تكن في الغرفة عند إرسالها." + "شارك %1$s هذه الرسالة لأنك لم تكن في الغرفة عند إرسالها." + "تم إعداد هذه الغرفة بحيث يمكن للأعضاء الجدد قراءة السجل. %1$s" + "تمت إعادة تعيين الهوية الرقمية لـ %1$s. %2$s" + "تمت إعادة تعيين الهوية الرقمية الخاصة بـ %1$s %2$s. %3$s" + "(%1$s)" + "تمت إعادة تعيين الهوية الرقمية الخاصة بـ %1$s." + "تمت إعادة تعيين الهوية الرقمية الخاصة بـ %1$s %2$s. %3$s" + "إلغاء التحقق" + "السماح بالوصول" + "ينقلك الرابط %1$s إلى موقع آخر %2$s + +هل أنت متأكد من رغبتك في المتابعة؟" + "تحقّق جيدًا من هذا الرابط" + "اختر الجودة الافتراضية للفيديوهات التي ترفعها." + "جودة رفع الفيديو" + "الحد الأقصى المسموح به لحجم الملف هو: %1$s" + "حجم الملف كبير جدًا ولا يمكن رفعه" + "تم الإبلاغ عن الغرفة" + "تم الإبلاغ عن الغرفة ومغادرتها" + "التأكيد" + "خطأ" + "تمت العملية بنجاح" + "تحذير" + "لديك تغييرات غير محفوظة." + "لم تُحفظ تغييراتك. هل أنت متأكد من أنك تريد الرجوع؟" + "حفظ التغييرات؟" + "الحد الأقصى المسموح به لحجم الملف هو: %1$s" + "اختر جودة الفيديو الذي تريد رفعه." + "اختر جودة رفع الفيديو" + "لقد سجّلت الدخول بالفعل على هذا الجهاز باسم %1$s." + "يجب ترقية خادمك المنزلي لدعم Matrix Authentication Service وإنشاء الحسابات." + "فشِل إنشاء رابطٍ دائم (permalink)" + "%1$s لم يستطع تحميل الخريطة. يرجى المحاولة مجدداً لاحقاً." + "فشِل تحميل الرسائل" + "%1$s لم يستطع الوصول إلى موقعك. يرجى المحاولة مجدداً لاحقاً." + "تعذّر رفع رسالتك الصوتية." + "لم تعد الغرفة موجودة أو لم تعد الدعوة صالحة." + "يرجى تفعيل GPS للوصول إلى الميزات المستندة إلى الموقع." + "لم يتم العثور على الرسالة" + "لا يملك %1$s الإذن بالوصول إلى موقعك. يمكنك تفعيل وصوله في الإعدادات." + "لا يملك %1$s الإذن بالوصول إلى موقعك. فعّل وصوله تحت." + "ليس لدى %1$s إذن للوصول إلى الميكروفون. اسمح بالوصول لتسجيل رسالة صوتية." + "قد يكون ذلك بسبب مشكلات في الشبكة أو الخادم." + "عنوان الغرفة هذا موجود بالفعل. يرجى محاولة تعديل حقل عنوان الغرفة أو تغيير اسم الغرفة" + "بعض الأحرف غير مسموح بها. يُسمح فقط بالحروف والأرقام والرموز التالية: ! $ & ‘ ( ) * + / ; = ? @ [ ] - . _" + "لم تُرسَل بعض الرسائل" + "عذراً، قد حدث خطأ" + "🔐️ انضم إليّ في %1$s" + "مرحباً، راسلني في %1$s: %2$s" + "مشاركة الموقع المباشر" + "جارٍ مشاركة الموقع" + "%1$s - الموقع المباشر" + "%1$s Android" + "رجّ الهاتف للإبلاغ عن خطأ" + "لقطة شاشة" + "%1$s: %2$s" + "الخيارات" + "إزالة %1$s" + "الإعدادات" + "الأصوات المسموح بها لكل شخص" + "لا يشارك أحد موقعه" + "مشاركة الموقع المباشر" + + "%1$d أشخاص" + "%1$d شخص" + "%1$d شخصان" + "%1$d أشخاص" + "%1$d شخصًا" + "%1$d شخص" + + "على الخريطة" + "تعذّر اختيار الوسائط، يرجى المحاولة مجدداً." + "اضغط على رسالة واختر “%1$s” لإضافتها هنا." + "ثبّت الرسائل المهمة لتسهيل العثور عليها" + + "%1$d رسائل مثبّتة" + "%1$d رسالة مثبّتة" + "%1$d رسالتان مثبّتتان" + "%1$d رسائل مثبّتة" + "%1$d رسالة مثبّتة" + "%1$d رسالة مثبّتة" + + "الرسائل المثبّتة" + "أنت على وشك الانتقال إلى حسابك على %1$s لإعادة تعيين هويتك الرقمية. بعد ذلك ستعود إلى التطبيق." + "لا يمكنك التأكيد؟ انتقل إلى حسابك لإعادة تعيين هويتك الرقمية." + "إلغاء التحقق والإرسال" + "يمكنك إلغاء التحقق الذي أجريته وإرسال هذه الرسالة على أي حال، أو الإلغاء في الوقت الحالي والمحاولة مرة أخرى لاحقًا بعد إعادة التحقق من %1$s." + "لم تُرسل رسالتك لأن الهوية الرقمية الموثّقة لـ %1$s أُعيد تعيينها" + "إرسال الرسالة على أي حال" + "يستخدم %1$s جهازًا واحدًا أو أكثر لم يتم التحقق منه. يمكنك إرسال الرسالة على أي حال، أو الإلغاء في الوقت الحالي والمحاولة مرة أخرى لاحقًا بعد أن يتحقق %2$s من جميع أجهزته." + "لم تُرسل رسالتك لأن %1$s لم يتحقق من جميع الأجهزة" + "لم يتم التحقق من جهاز واحد أو أكثر من أجهزتك. يمكنك إرسال الرسالة على أي حال، أو الإلغاء في الوقت الحالي والمحاولة مرة أخرى لاحقًا بعد أن تتحقق من جميع أجهزتك." + "لم تُرسل رسالتك لأنك لم تتحقق من جهاز واحد أو أكثر من أجهزتك" + "تعديل المسؤولين أو المالكين" + "تعذّرت معالجة الوسائط من أجل رفعها، يرجى المحاولة مجدداً." + "تعذّر استرداد معلومات المستخدم" + "رسالة في %1$s" + "توسيع" + "طي" + "مشاركة الموقع المباشر" + "أنت في هذه الغرفة بالفعل!" + "%1$s من %2$s" + "%1$s رسائل مثبّتة" + "جارٍ تحميل الرسالة…" + "عرض الكل" + "الدردشة" + "مشاركة موقع" + "شارك موقعي" + "فتح في Apple Maps" + "فتح في Google Maps" + "فتح في OpenStreetMap" + "مشاركة الموقع الجغرافي المُحدّد" + "خيارات المشاركة" + "المساحات التي أنشأتها أو انضممت إليها." + "%1$s • %2$s" + "أنشئ مساحات لتنظيم الغرف" + "مساحة %1$s" + "المساحات" + "تمت المشاركة %1$s" + "على الخريطة" + "لم تُرسل الرسالة لأن الهوية الرقمية الموثّقة لـ %1$s أُعيد تعيينها." + "لم تُرسل الرسالة لأن %1$s لم يتحقق من جميع الأجهزة." + "لم تُرسل الرسالة لأنك لم تتحقق من جهاز واحد أو أكثر من أجهزتك." + "الموقع" + "الإصدار: %1$s (%2$s)" + "ar" + "الرسائل السابقة غير متاحة على هذا الجهاز" + "يجب التحقق من هذا الجهاز للوصول إلى الرسائل السابقة" + "ليس لديك صلاحية الوصول إلى هذه الرسالة" + "تعذّر فك تشفير الرسالة" + "تم حظر هذه الرسالة إما لأنك لم تتحقق من جهازك أو لأن المرسل يحتاج إلى التحقق من هويتك الرقمية." + "جهازك قديم جدًا؛ يلزم جهاز يعمل بنظام Android 8 أو أحدث." + "عرض الخرائط غير مدعوم" + diff --git a/libraries/ui-strings/src/main/res/values-de/translations.xml b/libraries/ui-strings/src/main/res/values-de/translations.xml index d83fb1ee64..bcc897751a 100644 --- a/libraries/ui-strings/src/main/res/values-de/translations.xml +++ b/libraries/ui-strings/src/main/res/values-de/translations.xml @@ -35,12 +35,12 @@ "QR-Code" "Reagiere mit %1$s" "Mit anderen Emojis reagieren" - "Gelesen von %1$s und %2$s" + "Vorherige Nachricht gelesen von %1$s und %2$s" - "Gelesen von %1$s und %2$d weiteren" - "Gelesen von %1$s und %2$d weiteren" + "Vorherige Nachricht gelesen von %1$s und %2$d weiteren" + "Vorherige Nachricht gelesen von %1$s und %2$d weiteren" - "Gelesen von %1$s" + "Vorherige Nachricht gelesen von %1$s" "Reaktion mit %1$s entfernen" "Entferne Reaktionen mit %1$s" "Avatar" @@ -49,6 +49,7 @@ "Zeitlich begrenzte Handlung erforderlich, du hast eine Minute Zeit zur Verifizierung" "Passwort anzeigen" "Anruf starten" + "Starte einen Videoanruf" "Sprachanruf starten" "Stillgelegter Chat" "Nutzer-Avatar" @@ -460,6 +461,13 @@ Möchtest du wirklich fortfahren?" "Optionen" "Entferne %1$s" "Einstellungen" + "Niemand teilt seinen Standort" + "Live-Standort teilen" + + "%1$d Person" + "%1$d Leute" + + "Auf der Karte" "Medienauswahl fehlgeschlagen, bitte versuche es erneut." "Halte eine Nachricht gedrückt und wähle “%1$s”, um sie hier einzufügen." "Fixiere wichtige Nachrichten, so dass sie leicht gefunden werden können" @@ -484,6 +492,7 @@ Möchtest du wirklich fortfahren?" "Nachricht in %1$s" "Erweitern" "Verkleinern" + "Live-Standort teilen" "Du siehst diesen Chat bereits!" "%1$s von %2$s" "%1$s fixierte Nachrichten" diff --git a/libraries/ui-strings/src/main/res/values-es/translations.xml b/libraries/ui-strings/src/main/res/values-es/translations.xml index c068e23d6c..8a28af1e9c 100644 --- a/libraries/ui-strings/src/main/res/values-es/translations.xml +++ b/libraries/ui-strings/src/main/res/values-es/translations.xml @@ -1,51 +1,101 @@ + "Añadir avatar" "Añadir reacción: %1$s" + "Dirección" "Avatar" + "Borrar consulta" + "Minimizar el campo de texto del mensaje" + "Disminuir el número de votos permitidos por persona" + "Aumentar el número de votos permitidos por persona" + "Emoji personalizado" "Borrar" "%1$d dígito introducido" "%1$d dígitos introducidos" + "Duración: %1$s" + "Editar avatar" + "La dirección completa será %1$s" + "Detalles de cifrado" + "Expandir campo de texto del mensaje" + "Galería, archivo adjunto %1$d" + "Galería, escaneo fallido %1$d" + "Galería, imagen %1$d" + + "Galería, %1$d elemento multimedia más" + "Galería, %1$d elementos multimedia más" + + "Galería, escaneando %1$d" + "Galería, vídeo %1$d" "Ocultar contraseña" + "Info" "Unirse a la llamada" "Ir al final" + "Ir a los mensajes no leídos" + "Ir al primer mensaje no leído" + "Desplazar el mapa a mi ubicación" "Sólo menciones" "Silenciado" + "Menciones nuevas" + "Mensajes nuevos" + "Llamada en curso" + "Avatar del otro usuario" "Página %1$d" "Pausar" "Mensaje de voz, duración: %1$s, posición actual: %2$s" + "Vista previa de la foto" "Campo PIN" + "Ubicación fijada" "Reproducir" + "Velocidad de reproducción" "Encuesta" "Encuesta finalizada" + "Posición: %1$s" + "Código QR" "Reacciona con %1$s" "Reacciona con otros emojis" - "Leído por %1$s y %2$s" + "Mensaje anterior leído por %1$s y %2$s" - "Leído por %1$s y %2$d otro" - "Leído por %1$s y %2$d otros" + "Mensaje anterior leído por %1$s y %2$d más" + "Mensaje anterior leído por %1$s y %2$d más" - "Leído por %1$s" + "Mensaje anterior leído por %1$s" + "mostrar todas las confirmaciones de lectura" "Elimina la reacción con %1$s" "Retirar la reacción con %1$s" "Avatar de la sala" "Enviar archivos" + "Ubicación del remitente" + "Enviado por %1$s a las %2$s" + "Acción de tiempo limitado requerida, tienes un minuto para hacer la verificación" + "Ajustes, acción requerida" "Mostrar contraseña" "Iniciar llamada" + "Iniciar una videollamada" + "Iniciar una llamada de voz" + "Estado" + "Hilo en %1$s" + "Hilos en %1$s" + "Sala clausurada" + "Avatar del usuario" "Menú de usuario" + "Vista previa del vídeo" "Ver avatar" "Mostrar detalles" "Mensaje de voz, duración: %1$s" "Grabar mensaje de voz" "Detener grabación" + "Tu avatar" "Aceptar" "Agregar leyenda" + "Añadir salas existentes" "Añadir a la cronología" "Atrás" "Llamar" "Cancelar" "Cancelar por ahora" + "Seleccionar archivo" "Elegir foto" "Borrar" "Cerrar" @@ -60,24 +110,34 @@ "Copiar texto" "Crear" "Crear una sala" + "Crear espacio" "Desactivar" "Desactivar cuenta" "Rechazar" "Rechazar y bloquear" + "Eliminar" + "Eliminar cuenta" + "Eliminar archivo" "Eliminar encuesta" + "Deseleccionar todo" "Desactivar" "Descartar" "Descartar" "Hecho" + "Descargar" "Editar" "Editar leyenda" "Editar encuesta" "Activar" "Finalizar encuesta" "Introducir PIN" + "Explorar espacios públicos" + "Finalizar" "¿Olvidaste tu contraseña?" "Reenviar" "Volver atrás" + "Ir a roles y permisos" + "Ir a ajustes" "Ignorar" "Invitar" "Invitar personas" @@ -89,14 +149,20 @@ "Salir" "Salir de la conversación" "Salir de la sala" + "Salir del espacio" "Cargar más" "Gestionar cuenta" + "Gestionar cuenta y dispositivos" "Administrar dispositivos" + "Gestionar salas" + "Marcar como leído" "Enviar mensaje" + "Minimizar" "Siguiente" "No" "Ahora no" "OK" + "Abrir menú contextual" "Ajustes" "Abrir con" "Fijar" @@ -108,7 +174,7 @@ "Quitar leyenda" "Eliminar mensaje" "Responder" - "Responder en el hilo" + "Responder en hilo" "Denunciar" "Informar de un error" "Denunciar contenido" @@ -120,51 +186,69 @@ "Reintentar descifrado" "Guardar" "Buscar" + "Seleccionar todo" "Enviar" + "Enviar mensaje editado" "Enviar mensaje" + "Enviar mensaje de voz" "Compartir" "Compartir enlace" + "Compartir ubicación en directo" "Mostrar" "Inicia sesión de nuevo" - "Cerrar sesión" - "Cerrar sesión de todos modos" + "Eliminar este dispositivo" + "Eliminar este dispositivo de todos modos" "Saltar" "Comenzar" "Iniciar chat" "Empezar de nuevo" "Iniciar la verificación" "Pulsa para cargar el mapa" + "Parar" "Hacer foto" "Toca para ver opciones" + "Traducir" "Intentar de nuevo" "Desprender" + "Videollamada" "Ver" "Ver en la cronología" "Ver fuente" + "Llamada de voz" "Sí" "Sí, intentar de nuevo" "Tu servidor es ahora compatible con un protocolo nuevo y más rápido. Cierra la sesión y vuelve a iniciarla para actualizar ahora. Haciéndolo ahora, evitarás tener que cerrar la sesión cuando se elimine el protocolo antiguo." "Actualización disponible" "Acerca de" "Política de uso aceptable" + "Añadir una cuenta" + "Añadir cuenta" "Añadiendo leyenda" "Ajustes avanzados" "una imagen" "Estadísticas" "Saliste de la sala" + "Se te ha desconectado de la sesión" "Apariencia" "Sonido" + "Beta" "Usuarios bloqueados" "Burbujas" + "Llamada rechazada" + "Llamada en curso" "Llamada iniciada" + "Rechazaste una llamada" "Copia de seguridad del chat" "Copiado al portapapeles" "Derechos de autor" "Creando sala…" + "Creando espacio…" "Solicitud cancelada" "Saliste de la sala" + "Saliste del espacio" "Invitación rechazada" "Error de descifrado" + "Descripción" "Opciones de desarrollador" "ID de dispositivo" "Chat directo" @@ -178,6 +262,7 @@ "Archivo vacío" "Cifrado" "Cifrado activado" + "Termina a las %1$s" "Introduce tu PIN" "Error" "Se ha producido un error, es posible que no recibas notificaciones de mensajes nuevos. Soluciona los problemas con las notificaciones desde los ajustes. @@ -187,20 +272,35 @@ Motivo: %1$s." "Falló" "Favorito" "Marcado como favorito" + "Sincronizando notificaciones…" "Archivo" "Archivo eliminado" "Archivo guardado" "Archivo guardado en Descargas" "Reenviar mensaje" "Usado frecuentemente" + "Galería" + + "%1$d archivo adjunto…" + "%1$d archivos adjuntos…" + + + "%1$d elemento multimedia…" + "%1$d elementos multimedia…" + "GIF" + "Llamada grupal en curso" "Imagen" "En respuesta a %1$s" "Instalar APK" "No se encontró este ID de Matrix, por lo que es posible que no se reciba la invitación." "Saliendo de la sala" + "Saliendo del espacio" "Línea copiada al portapapeles" "Enlace copiado al portapapeles" + "Vincular un dispositivo nuevo" + "Location en directo" + "La ubicación en tiempo real ha terminado" "Cargando…" "Cargando más…" @@ -213,17 +313,22 @@ Motivo: %1$s." "Mensaje" "Acciones del mensaje" + "El mensaje no se pudo enviar" "Diseño de los mensajes" "Mensaje eliminado" "Moderno" "Silenciar" + "Nombre" "%1$s (%2$s)" "No hay resultados" "Sala sin nombre" + "Espacio sin nombre" "No cifrado" "Sin conexión" + "En una llamada" "Licencias de código abierto" "o" + "Otras opciones" "Contraseña" "Personas" "Enlace permanente" @@ -233,27 +338,43 @@ Motivo: %1$s." "Espera, por favor…" "¿Estás seguro de que quieres finalizar esta encuesta?" "Encuesta: %1$s" + "Encuesta" "Total de votos: %1$s" "Los resultados se mostrarán una vez finalizada la encuesta" "%d voto" "%d votos" + "Preparando…" "Política de privacidad" + "Privado" "Sala privada" + "Espacio privado" + "Público" "Sala pública" + "Espacio público" "Reacción" "Reacciones" "Motivo" "Clave de recuperación" "Recargando…" + "Eliminando…" + + "%1$d respuesta" + "%1$d respuestas" + "Respondiendo a %1$s" "Informar de un problema" "Informe enviado" "Editor de texto enriquecido" + "Rol" "Sala" "Nombre de la sala" "p. ej., el nombre de tu proyecto" + + "%1$d sala" + "%1$d salas" + "Cambios guardados" "Guardando" "Bloqueo de pantalla" @@ -261,37 +382,58 @@ Motivo: %1$s." "Buscar resultados" "Seguridad" "Visto por" + "Elige una cuenta" + + "%1$d seleccionado" + "%1$d seleccionados" + "Enviar a" "Enviando…" "Fallo al enviar" "Enviado" + ". " "Servidor no compatible" + "Servidor inaccesible" "Dirección del servidor" "Ajustes" + "Compartir espacio" + "Los miembros nuevos ven el historial" + "Ubicación compartida en directo" "Ubicación compartida" - "Cerrando sesión" + "Espacio compartido" + "Eliminando dispositivo" "Algo salió mal" "Hemos encontrado un problema. Inténtalo de nuevo." + "Espacio" + "Miembros del espacio" + "¿De qué trata este espacio?" + + "%1$d espacio" + "%1$d espacios" + "Iniciando chat…" "Sticker" "Terminado" + "Sugerido" "Sugerencias" "Sincronizando" "Texto" "Avisos de terceros" "Hilo" + "Hilos" "Tema" "¿De qué trata esta sala?" "No se puede descifrar" "Enviado desde un dispositivo no seguro" "No tienes acceso a este mensaje" - "Se restableció la identidad verificada del remitente" + "Se restableció la identidad digital verificada del remitente" "Las invitaciones no se pudieron enviar a uno o más usuarios." "No se pudo enviar la(s) invitación(es)" "Desbloquear" "Dejar de silenciar" "Llamada no compatible" "Evento no compatible" + "%1$s inició una llamada" "Usuario" "Verificación cancelada" "Verificación completada" @@ -301,20 +443,41 @@ Motivo: %1$s." "Verificar identidad" "Verificar usuario" "Vídeo" + "Calidad alta" + "La mejor calidad, pero mayor tamaño de archivo" + "Calidad baja" + "Velocidad de subida más rápida y tamaño de archivo más pequeño" + "Calidad estándar" + "Equilibrio entre calidad y velocidad de subida" "Mensaje de voz" "Esperando…" "Esperando este mensaje" + "Esperando la ubicación en directo…" + "Cualquiera puede ver el historial" "Tú" - "Se restableció la identidad de %1$s. %2$s" - "Se restableció la identidad de %1$s %2$s. %3$s" + "Descarga no disponible." + "Algo salió mal" + "Escaneando…" + "Se ha desactivado la vista previa y la descarga." + "El archivo no es seguro" + "%1$s (%2$s) compartió este mensaje ya que no estabas en la sala cuando se envió." + "%1$s compartió este mensaje ya que no estabas en la sala cuando se envió." + "Esta sala se ha configurado para que los miembros nuevos puedan leer el historial. %1$s" + "Se restableció la identidad digital de %1$s. %2$s" + "Se restableció la identidad digital de %1$s %2$s. %3$s" "(%1$s)" - "Se restableció la identidad de %1$s." - "Se restableció la identidad de %1$s %2$s. %3$s" + "Se restableció la identidad digital de %1$s." + "Se restableció la identidad digital de %1$s %2$s. %3$s" "Retirar la verificación" + "Permitir acceso" "El enlace %1$s te está llevando a otro sitio %2$s ¿Estás seguro de que quieres continuar?" "Revisa este enlace" + "Selecciona la calidad por defecto de los vídeos que subas." + "Calidad de subida de vídeos" + "El tamaño máximo de archivo permitido es: %1$s" + "El archivo es demasiado grande para ser subido" "Sala denunciada" "Denunciaste y saliste de la sala" "Confirmar" @@ -324,6 +487,10 @@ Motivo: %1$s." "Tienes cambios sin guardar." "Tus cambios no se han guardado. ¿Estás seguro de que quieres volver atrás?" "¿Guardar cambios?" + "El tamaño máximo de archivo permitido es: %1$s" + "Selecciona la calidad del vídeo que quieres subir." + "Selecciona la calidad de subida del vídeo" + "Ya has iniciado sesión en este dispositivo como %1$s." "Tu servidor base debe actualizarse para admitir Matrix Authentication Service y la creación de cuentas." "No se pudo crear el enlace permanente" "%1$s no pudo cargar el mapa. Por favor vuelve a intentarlo más tarde." @@ -331,6 +498,7 @@ Motivo: %1$s." "%1$s no ha podido acceder a tu ubicación. Por favor vuelve a intentarlo más tarde." "No se pudo cargar tu mensaje de voz." "La sala ya no existe o la invitación ya no es válida." + "Activa el GPS para acceder a las funciones basadas en la ubicación." "Mensaje no encontrado" "%1$s no tiene permiso para acceder a tu ubicación. Puedes habilitar el acceso en Ajustes." "%1$s no tiene permiso para acceder a tu ubicación. Habilita el acceso a continuación." @@ -342,10 +510,26 @@ Motivo: %1$s." "Lo siento, se ha producido un error" "🔐️ Únete a mí en %1$s" "Hola, puedes hablar conmigo en %1$s: %2$s" + "Compartir la ubicación en directo" + "Se está compartiendo actualmente la ubicación" + "%1$s Ubicación en tiempo real" "%1$s Android" "Agitar con fuerza para informar de un error" + "Captura de pantalla" + "%1$s: %2$s" "Opciones" + "Eliminar %1$s" "Ajustes" + "Votos permitidos por persona" + "Nadie está compartiendo su ubicación" + "Compartiendo ubicación en tiempo real" + + "%1$d persona" + "%1$d personas" + + "En el mapa" + "Tu servidor base está en tu red local. Para conectarse, %1$s necesita permiso para acceder a los dispositivos de esta red." + "Permite el acceso a la red local" "Error al seleccionar archivos multimedia, por favor inténtalo de nuevo." "Presiona sobre un mensaje y selecciona «%1$s» para incluirlo aquí." "Fija los mensajes importantes para que se puedan descubrir fácilmente" @@ -354,21 +538,23 @@ Motivo: %1$s." "%1$d mensajes fijados" "Mensajes fijados" - "Estás a punto de ir a tu cuenta de %1$s para restablecer tu identidad. Posteriormente volverás a la aplicación." - "¿No puedes confirmar? Ve a tu cuenta para restablecer tu identidad." + "Estás a punto de ir a tu cuenta de %1$s para restablecer tu identidad digital. Posteriormente volverás a la aplicación." + "¿No puedes confirmarla? Ve a tu cuenta para restablecer tu identidad digital." "Retirar la verificación y enviar" "Puedes retirar tu verificación y enviar este mensaje de todos modos, o puedes cancelarlo por ahora e intentarlo de nuevo más tarde después de volver a verificar a %1$s." - "Tu mensaje no se envió porque la identidad verificada de %1$s fue restablecida" + "Tu mensaje no se envió porque la identidad digital verificada de %1$s fue restablecida" "Enviar mensaje de todos modos" "%1$s utiliza uno o más dispositivos no verificados. Puedes enviar el mensaje de todos modos, o puedes cancelarlo por ahora y volver a intentarlo más tarde, una vez %2$s haya verificado todos sus dispositivos." "Tu mensaje no se envió porque %1$s no ha verificado todos los dispositivos" "Uno o más de tus dispositivos no están verificados. Puedes enviar el mensaje de todos modos, o puedes cancelarlo por ahora e intentarlo de nuevo más tarde, una vez hayas verificado todos tus dispositivos." "Tu mensaje no se envió porque no has verificado uno o más de tus dispositivos" + "Editar administradores o propietarios" "Error al procesar el contenido multimedia, por favor inténtalo de nuevo." "No se pudieron recuperar los detalles del usuario" "Mensaje en %1$s" "Expandir" "Reducir" + "Compartiendo ubicación en tiempo real" "¡Ya estás viendo esta sala!" "%1$s de %2$s" "%1$s mensajes fijados" @@ -380,8 +566,20 @@ Motivo: %1$s." "Abrir en Apple Maps" "Abrir en Google Maps" "Abrir en OpenStreetMap" - "Compartir esta ubicación" - "Mensaje no enviado porque la identidad verificada de %1$s fue restablecida." + "Compartir ubicación seleccionada" + "Cómo compartir" + "Espacios que has creado o a los que te has unido." + "%1$s • %2$s" + "Crea espacios para organizar salas" + "Espacio %1$s" + "Espacios" + "Compartida %1$s" + "En el mapa" + + "Se unió %1$d" + "Se unieron %1$d" + + "Mensaje no enviado porque la identidad digital verificada de %1$s fue restablecida." "Mensaje no enviado porque %1$s no ha verificado todos los dispositivos." "Mensaje no enviado porque no has verificado uno o más de tus dispositivos." "Ubicación" @@ -391,5 +589,7 @@ Motivo: %1$s." "Debes verificar este dispositivo para acceder a los mensajes históricos" "No tienes acceso a este mensaje" "No se ha podido descifrar el mensaje" - "Este mensaje fue bloqueado bien sea porque no verificaste tu dispositivo o porque el remitente necesita verificar tu identidad." + "Este mensaje fue bloqueado bien sea porque no verificaste tu dispositivo o porque el remitente necesita verificar tu identidad digital." + "Tu dispositivo es demasiado antiguo; necesitas un dispositivo con Android 8 o posterior." + "No se admite el renderizado de mapas" diff --git a/libraries/ui-strings/src/main/res/values-fa/translations.xml b/libraries/ui-strings/src/main/res/values-fa/translations.xml index 03d1172040..49a790c2ea 100644 --- a/libraries/ui-strings/src/main/res/values-fa/translations.xml +++ b/libraries/ui-strings/src/main/res/values-fa/translations.xml @@ -1,18 +1,30 @@ + "اضافه کردن آواتار" "افزودن واکنش: %1$s" + "آدرس" "چهرک" + "پاک کردن فیلد جستجو" + "کوچک کردن فیلد متن پیام" + "کاهش آرای مجاز برای هر نفر" + "افزایش تعداد آرای مجاز برای هر نفر" + "ایموجی‌های سفارشی" "حذف" "%1$d رقم وارد شده" "%1$d رقم وارد شده" + "مدت زمان: %1$s" "ویرایش چهرک" "نشانی کامل %1$s خواهد بود" "جزییات رمزنگاری" + "فیلد متن پیام را گسترش دهید" "نهفتن گذرواژه" + "اطلاعات" "پیوستن به تماس" "به پایین بروید" + "پرش به خوانده نشده" + "پرش به اولین پیام خوانده نشده" "جابه‌جایی نقشه به مکانم" "فقط اشاره‌ها" "خموش" @@ -23,10 +35,15 @@ "صفحهٔ %1$d" "مکث" "پیام صوتی. طول %1$s. موقعیت کنونی: %2$s" + "پیش‌نمایش عکس" "زمینهٔ پین" + "مکان پین شده" "پخش" + "سرعت پخش" "نظرسنجی" "نظرسنجی پایان یافته" + "موقعیت: %1$s" + "کد QR" "واکنش با %1$s" "واکنش با شکلک‌های دیگر" "پیام پیشین به دست %1$s و %2$s خوانده شد" @@ -35,15 +52,26 @@ "پیام پیشین به دست %1$s و %2$d دیگر خوانده شد" "پیام قبلی به دست %1$s خوانده شد" + "نمایش همه رسیدهای خوانده شده" "برداشتن واکنش با %1$s" "برداشتن واکنش با %1$s" "چهرک اتاق" "ارسال پرونده‌ها" - "نیازمند کنش محدود به زمان" + "مکان فرستنده" + "ارسال شده توسط %1$s در %2$s" + "اقدام مورد نیاز با محدودیت زمانی، شما یک دقیقه برای تأیید فرصت دارید" + "تنظیمات، اقدام مورد نیاز" "نمایش گذرواژه" "آغاز یک تماس" + "شروع تماس ویدیویی" + "شروع تماس صوتی" + "وضعیت" + "رزوه در %1$s" + "موضوعات در %1$s" + "اتاق سنگ قبر" "چهرک کاربر" "فهرست کاربر" + "پیش‌نمایش ویدیو" "دیدن چهرک" "دیدن جزییات" "پیام صوتی. طول %1$s" @@ -52,11 +80,13 @@ "چهرکتان" "پذیرش" "افزودن عنوان" + "افزودن اتاق‌های موجود" "افزودن به خط زمانی" "بازگشت" "تماس" "لغو" "لغو برای امنون" + "انتخاب فایل" "گزینش عکس" "پاک سازی" "بستن" @@ -71,26 +101,34 @@ "رونوشت از متن" "ایجاد" "ایجاد اتاق" + "ایجاد فضا" "غیرفعّال" "غیرفعّال‌سازی حساب" "رد" "رد و انسداد" + "پاک‌کردن" + "حذف حساب کاربری" + "حذف فایل" "حذف نظرسنجی" "ناگزینش همه" "از کار انداختن" "دور ریختن" "دورانداختن" "انجام شد" + "دانلود" "ویرایش" "ویرایش عنوان" "ویرایش نظرسنجی" "به کار انداختن" "پایان نظرسنجی" "ورود پین" + "کاوش در فضاهای عمومی" "پایان" "گذرواژه را فراموش کردید؟" "پیشروی" "پس‌روی" + "به نقش‌ها و مجوزها بروید" + "به تنظیمات بروید" "نادیده‌گرفتن" "دعوت" "دعوت افراد" @@ -105,8 +143,12 @@ "ترک فضا" "بار کردن بیش‌تر" "مدیریت حساب" + "مدیریت حساب و دستگاه‌ها" "مدیریت افزاره‌ها" + "مدیریت اتاق‌ها" + "علامت‌گذاری به عنوان خوانده شده" "پیام" + "کوچک کردن" "بعدی" "نه" "الآن نه" @@ -120,8 +162,8 @@ "واکنش" "رد کردن" "حذف" - "برداشتن عنوان" - "برداشتن پیام‌ها" + "حذف عنوان" + "حذف پیام" "پاسخ" "پاسخ در رشته" "گزارش" @@ -142,25 +184,31 @@ "فرستادن پیام صوتی" "هم‌رسانی" "هم‌رسانی پیوند" + "اشتراک گذاری موقعیت مکانی زنده" "نمایش" "ورود دوباره" "برداشتن این افزاره" "به هر حال این دستگاه را حذف کنید" - "پرش" + "رد شدن" "آغاز" "آغاز گپ" "آغاز از نو" "آغاز تأیید" "زدن برای بار کردن نقشه" + "توقف" "عکس گرفتن" "زدن برای گزینه‌ها" + "ترجمه" "تلاش دوباره" "سنجاق نکردن" + "تماس تصویری" "نما" "دیدن در خط زمانی" "دیدن منبع" + "تماس صوتی" "بله" "بله. تلاش دوباره" + "سرور شما اکنون از یک پروتکل جدید و سریع‌تر پشتیبانی می‌کند. برای ارتقا، از سیستم خارج شوید و دوباره وارد شوید. انجام این کار در حال حاضر به شما کمک می‌کند تا از خروج اجباری هنگام حذف پروتکل قدیمی در آینده جلوگیری کنید." "ارتقا موجود است" "درباره" "سیاست استفادهٔ پذیرفتنی" @@ -168,18 +216,24 @@ "افزودن حسابی دیگر" "افزودن عنوان" "تنظیمات پیش‌رفته" + "یک تصویر" "تجزیه و تحلیل" "اتاق را ترک کردید" + "شما از جلسه خارج شدید" "ظاهر" "صدا" "آزمایشی" "کاربران مسدود" "حباب‌ها" + "تماس رد شد" + "تماس در جریان است" "تماس آغاز شد" + "شما یک تماس را رد کردید" "پشتیبان گپ" "در تخته‌گیره رونوشت شد" "حق رونوشت" "ایجاد کردن اتاق…" + "ایجاد فضای…" "درخواست لغو شد" "اتاق را ترک کرد" "فضا را ترک کرد" @@ -199,19 +253,34 @@ "پروندهٔ خالی" "رمزنگاری" "رمزنگاری به کار افتاده" + "در %1$s پایان می‌یابد" "پینتان را وارد کنید" "خطا" + "خطایی رخ داده است، ممکن است اعلان‌های مربوط به پیام‌های جدید را دریافت نکنید. لطفاً اعلان‌ها را از تنظیمات عیب‌یابی کنید. + +دلیل: %1$s." "هرکسی" "شکست خورد" "برگزیده" "برگزیده" + "همگام‌سازی اعلان‌ها…" "پرونده" "پرونده حذف شد" "پرونده ذخیره شد" "پرونده در بارگیری‌ها ذخیره شد" "هدایت پیام" "پراستفاده" + "گالری" + + "پیوست %1$d…" + "پیوست‌های %1$d…" + + + "مورد رسانه‌ای %1$d…" + "موارد رسانه‌ای %1$d…" + "جیف" + "تماس گروهی در جریان است" "تصویر" "در پاسخ به %1$s" "نصب APK" @@ -220,6 +289,9 @@ "ترک کردن فضا" "خط در تخته‌گیره رونوشت شد" "پیوند در تخته‌گیره رونوشت شد" + "اتصال دستگاه جدید" + "مکان زنده" + "مکان زنده به پایان رسید" "بار کردن…" "بار کردن بیش‌تر…" @@ -232,18 +304,22 @@ "پیام" "کنش‌های پیام" + "پیام ارسال نشد" "جینش پیام" "پیام برداشته شد" "نوین" "بی‌صدا" + "نام" "%1$s ‏(%2$s)" "بدون نتیجه" "بدون نام اتاق" "بدون نام فضا" "رمزنگاری نشده" "برون‌خط" + "در یک تماس" "پروانه‌های نرم‌افزاری آزاد" "یا" + "گزینه‌های دیگر" "گذرواژه" "افراد" "پایاپیوند" @@ -253,6 +329,7 @@ "لطفا صبر کنید…" "مطئنید که می‌خواهید این نظرسنجی را پایان دهید؟" "نظرسنجی: %1$s" + "نظرسنجی" "مجموع آرا: %1$s" "نتیجه‌ها پس از پایان نظرسنجی نشان داده خواهند شد" @@ -261,8 +338,10 @@ "آماده سازی…" "سیاست محرمانگی" + "خصوصی" "اتاق خصوصی" "فضای خصوصی" + "عمومی" "اتاق عمومی" "فضای عمومی" "واکنش" @@ -270,13 +349,23 @@ "دلیل" "کلید بازیابی" "تازه سازی…" + "در حال حذف…" + + "پاسخ %1$d" + "پاسخ‌های %1$d" + "پاسخ دادن به %1$s" "گزارش مشکل" "گزارش ثبت شد" "ویرایشگر متن غنی" + "نقش" "اتاق" "نام اتاق" "برای نمونه نام پروژه‌تان" + + "اتاق %1$d" + "اتاق‌های %1$d" + "تغییرات ذخیره شده" "ذخیره کردن" "قفل صفحه" @@ -285,6 +374,10 @@ "امنیت" "دیده شده به دست" "گزینش حساب" + + "%1$d انتخاب شد" + "%1$d انتخاب شد" + "فرستادن به" "فرستادن…" "فرستادن شکست خورد" @@ -295,29 +388,43 @@ "نشانی کارساز" "تنظیمات" "هم‌رسانی فضا" + "اعضای جدید تاریخچه را می‌بینند" + "مکان زنده به اشتراک‌گذاری شده" "مکان هم‌رسانده" "فضای اشتراکی" "خارج شدن" "چیزی اشتباه پیش رفت" + "با مشکلی مواجه شدیم. لطفا دوباره امتحان کنید." "فاصله" + "اعضای فضا" + "این فضا مربوط به چیست؟" + + "فضای %1$d" + "فضاهای %1$d" + "آغازیدن گپ…" "عکس برگردان" "موفّقیت" + "پیشنهادی" "پیشنهادها" "هم‌گام ساختن" "متن" "تذکّرهای سوم‌شخص" "رشته" + "موضوعات" "موضوع" "این اتاق دربارهٔ چیست؟" "ناتوان در رمزگشایی" + "ارسال شده از یک دستگاه ناامن" "به این پیام دسترسی ندارید" + "هویت دیجیتال تأیید شده فرستنده بازنشانی شد" "دعوت‌ها نتوانستند به کاربرانی برسند." "ناتوان در فرستادن دعوت(ها)" "قفل‌گشایی" "باصدا" "تماس پشتیبانی نشده" "رویداد پشتیبانی نشده" + "%1$s یک تماس را آغاز کرد" "نام کاربری" "تأیید لغو شد" "تأیید کامل شد" @@ -328,17 +435,40 @@ "تأیید کاربر" "ویدیو" "کیفیت بالا" + "بهترین کیفیت اما حجم فایل بیشتر" "کیفیت پایین" + "سریع‌ترین سرعت آپلود و کمترین حجم فایل" "کیفیت استاندارد" + "تعادل بین کیفیت و سرعت آپلود" "پیام صوتی" "در انتظار…" "در انتظار این پیام" + "در انتظار موقعیت مکانی زنده…" + "هر کسی می‌تواند تاریخچه را ببیند" "شما" - "هویت %1$s بازنشانی شد. %2$s" + "دانلود در دسترس نیست." + "چیزی اشتباه پیش رفت" + "اسکن…" + "پیش‌نمایش و دانلود غیرفعال شده‌اند." + "فایل امن نیست" + "%1$s (%2$s) این پیام را به اشتراک گذاشته است زیرا شما هنگام ارسال آن در اتاق حضور نداشتید." + "%1$s این پیام را به اشتراک گذاشت زیرا شما هنگام ارسال آن در اتاق نبودید." + "این اتاق طوری پیکربندی شده است که اعضای جدید بتوانند تاریخچه را بخوانند. %1$s" + "هویت دیجیتال %1$s بازنشانی شد. %2$s" + "هویت دیجیتال %2$s مربوط به %1$s بازنشانی شد. %3$s" "(%1$s)" + "هویت دیجیتال %1$s بازنشانی شد." + "هویت دیجیتال %2$s مربوط به %1$s بازنشانی شد. %3$s" "انصراف از تأیید" + "اجازه دسترسی" + "لینک %1$s شما را به سایت دیگری هدایت می‌کند %2$s + +آیا مطمئنید که می‌خواهید ادامه دهید؟" "این پیوند را دوباره بررسی کنید" + "کیفیت پیش‌فرض ویدیوهایی که آپلود می‌کنید را انتخاب کنید." "کیفیت بارگذاری ویدیو" + "حداکثر اندازه فایل مجاز: %1$s" + "حجم فایل برای آپلود بسیار زیاد است" "اتاق گزارش شد" "گزارش و از اتاق خارج شد" "تایید" @@ -348,35 +478,75 @@ "تغییراتی ذخیره نشده دارید." "تغییراتتان ذخیره نشده‌اند. مطمئنید که می‌خواهید برگردید؟" "ذخیرهٔ تغییرات؟" + "حداکثر اندازه فایل مجاز: %1$s" + "کیفیت ویدیویی که می‌خواهید آپلود کنید را انتخاب کنید." + "کیفیت آپلود ویدیو را انتخاب کنید" + "شما قبلاً با نام کاربری %1$s در این دستگاه وارد سیستم شده‌اید." + "سرور خانگی شما باید ارتقا یابد تا از سرویس احراز هویت ماتریکس و ایجاد حساب کاربری پشتیبانی کند." "شکست در ایجاد پایاپیوند" "%1$s نتوانست نقشه را بارگیری کند. لطفا بعدا دوباره امتحان کنید." "شکست در بار کردن پیام‌ها" "‏%1$s نمی تواند به مکانتان دسنترسی داشته باشد. لطفا بعدا دوباره امتحان کنید." "شکست در بارگذاری پیام صوتیتان." + "اتاق دیگر وجود ندارد یا دعوتنامه دیگر معتبر نیست." + "برای دسترسی به ویژگی‌های مبتنی بر موقعیت مکانی، لطفاً GPS خود را فعال کنید." "پیام پیدا نشد" "‏%1$s اجازهٔ دسترسی به مکانتان را ندارد. می توانید دسترسی را در تنظیمات به کار بیندازید." "%1$s اجازهٔ دسترسی به مکانتان را ندارد. دسترسی را در زیر به کار بیندازید." "%1$s اجازه دسترسی به میکروفون شما را ندارد. دسترسی را برای ضبط پیام صوتی فعال کنید." + "این مشکل ممکن است به دلیل مشکلات شبکه یا سرور باشد." + "این آدرس اتاق از قبل وجود دارد. لطفاً فیلد آدرس اتاق را ویرایش کنید یا نام اتاق را تغییر دهید." + "بعضی از کاراکترها مجاز نیستند. فقط حروف، ارقام و نمادهای زیر پشتیبانی می‌شوند! $ &amp; ' ( ) * + / ; = ? @ [ ] - . _" "برخی پیام‌ها ارسال نشده‌اند" "متأسفیم ، خطایی رخ داد" "🔐️ پییوستن به من روی %1$s" "درود. با من روی %1$s صحبت کن: %2$s" + "اشتراک‌گذاری موقعیت مکانی زنده" + "اشتراک‌گذاری موقعیت مکانی در حال انجام است" + "موقعیت مکانی زنده %1$s" "%1$s اندروید" "Rageshake برای گزارش اشکال" "نماگرفت" "%1$s: %2$s" "گزینه‌ها" + "حذف %1$s" "تنظیمات" + "تعداد آرای مجاز برای هر نفر" + "هیچ‌کس موقعیت مکانی خود را به اشتراک نمی‌گذارد" + "اشتراک‌گذاری موقعیت مکانی زنده" + + "شخص %1$d" + "افراد %1$d" + + "روی نقشه" + "سرور خانگی شما در شبکه محلی شما قرار دارد. برای اتصال، %1$s برای دسترسی به دستگاه‌های این شبکه به مجوز نیاز دارد." + "اجازه دسترسی به شبکه محلی" "گزینش رسانه شکست خورد. لطفاً دوباره تلاش کنید." + "روی یک پیام کلیک کنید و «%1$s» را برای گنجاندن در اینجا انتخاب کنید." + "پیام‌های مهم را سنجاق کنید تا به راحتی قابل مشاهده باشند" + + "پیام پین شده %1$d" + "پیام‌های پین‌شده %1$d" + "پیام‌های سنجاق شده" - "داردید برای بازنشانی هویتتان به حساب %1$s می‌روید. پس از آن به کاره برگردانده خواهید شد." + "شما در شرف رفتن به حساب %1$s خود برای تنظیم مجدد هویت دیجیتال خود هستید. پس از آن به برنامه بازگردانده خواهید شد." + "نمی‌توانید تأیید کنید؟ برای بازنشانی هویت دیجیتال خود به حساب کاربری خود بروید." + "تأیید را لغو و ارسال کنید" + "شما می‌توانید تأیید خود را پس بگیرید و در هر صورت این پیام را ارسال کنید، یا می‌توانید فعلاً لغو کنید و پس از تأیید مجدد %1$s، بعداً دوباره امتحان کنید." + "پیام شما ارسال نشد زیرا هویت دیجیتال تأیید شده %1$s بازنشانی شده است." "فرستادن پیام به هر روی" + "%1$s از یک یا چند دستگاه تأیید نشده استفاده می‌کند. در هر صورت می‌توانید پیام را ارسال کنید، یا می‌توانید فعلاً لغو کنید و بعداً پس از تأیید تمام دستگاه‌های %2$s دوباره امتحان کنید." + "پیام شما ارسال نشد زیرا %1$s همه دستگاه‌ها را تأیید نکرده است." + "یک یا چند دستگاه شما تأیید نشده‌اند. در هر صورت می‌توانید پیام را ارسال کنید، یا می‌توانید فعلاً لغو کنید و بعداً پس از تأیید همه دستگاه‌هایتان دوباره امتحان کنید." + "پیام شما ارسال نشد زیرا یک یا چند دستگاه خود را تأیید نکرده‌اید" "ویرایش مدیران یا مالکان" "پردازش رسانه برای بارگذاری شکست خورد. لطفاً دوباره تلاش کنید." "نمی توان جزئیات کاربر را بازیابی کرد" "پیام در %1$s" "گسترش" "کاهش" + "اشتراک گذاری موقعیت مکانی زنده" + "درحال مشاهده این اتاق هستید!" "%1$s از %2$s" "%1$s پیام‌های سنجاق شده" "بار کردن پیام‌ها…" @@ -388,13 +558,30 @@ "گشودن در نقشه‌های گوگل" "گشودن در اوپن‌استریت‌مپ" "هم‌رسانی مکان گزیده" + "گزینه‌های اشتراک‌گذاری" "فضاهایی که ساخته یا پیوسته‌اید." "%1$s • %2$s" + "ایجاد فضاهایی برای سازماندهی اتاق‌ها" "‏%1$s فضا" "فضاها" + "%1$s اشتراک‌گذاری شده" + "روی نقشه" + + "%1$d عضو شد" + "%1$d عضو شد" + + "پیام ارسال نشد زیرا هویت دیجیتال تأیید شده %1$s بازنشانی شده است." + "پیام ارسال نشد زیرا %1$s همه دستگاه‌ها را تأیید نکرده است." + "پیام ارسال نشد زیرا شما یک یا چند دستگاه خود را تأیید نکرده‌اید." "مکان" "نگارش : %1$s (%2$s)" "fa" "en" + "پیام‌های تاریخی در این دستگاه موجود نیست" + "برای دسترسی به پیام‌های قدیمی، باید این دستگاه را تأیید کنید" "به این پیام دسترسی ندارید" + "رمزگشایی پیام ممکن نیست" + "این پیام یا به این دلیل مسدود شده است که شما دستگاه خود را تأیید نکرده‌اید یا به این دلیل که فرستنده باید هویت دیجیتال شما را تأیید کند." + "دستگاه شما خیلی قدیمی است، دستگاهی با اندروید ۸ یا جدیدتر مورد نیاز است." + "رندر کردن نقشه‌ها پشتیبانی نمی‌شود" diff --git a/libraries/ui-strings/src/main/res/values-fi/translations.xml b/libraries/ui-strings/src/main/res/values-fi/translations.xml index 52d3bf16e5..11ca38edf0 100644 --- a/libraries/ui-strings/src/main/res/values-fi/translations.xml +++ b/libraries/ui-strings/src/main/res/values-fi/translations.xml @@ -8,6 +8,7 @@ "Pienennä viestin tekstikenttä" "Vähennä sallittujen äänien määrää per henkilö" "Lisää sallittujen äänien määrää per henkilö" + "Mukautettu emoji" "Poista" "%1$d numero syötetty" @@ -18,11 +19,21 @@ "Täysi osoite tulee olemaan %1$s" "Salauksen tiedot" "Laajenna viestin tekstikenttä" + "Galleria, liite %1$d" + "Galleria, epäonnistunut skannaus %1$d" + "Galleria, kuva %1$d" + + "Galleria, %1$d media lisää" + "Galleria, %1$d mediaa lisää" + + "Galleria, skannataan %1$d" + "Galleria, video %1$d" "Piilota salasana" "Tiedot" "Liity puheluun" "Siirry loppuun" "Siirry lukemattomiin" + "Siirry ensimmäiseen lukemattomaan viestiin" "Siirrä kartta sijaintiini" "Vain maininnat" "Mykistetty" @@ -63,6 +74,7 @@ "Aloita puhelu" "Aloita videopuhelu" "Aloita äänipuhelu" + "Tila" "Viestiketju huoneessa %1$s" "Viestiketjut huoneessa %1$s" "Haudattu huone" @@ -143,6 +155,7 @@ "Hallitse tiliä ja laitteita" "Hallitse laitteita" "Huoneiden hallitseminen" + "Merkitse luetuksi" "Lähetä viesti" "Pienennä" "Seuraava" @@ -515,6 +528,8 @@ Haluatko varmasti jatkaa?" "%1$d henkilöä" "Kartalla" + "Kotipalvelimesi on paikallisverkossasi. Yhdistääksesi, %1$s tarvitsee luvan tavoittaa laitteita tässä verkossa." + "Salli pääsy paikallisverkkoon" "Median valinta epäonnistui, yritä uudelleen." "Paina viestiä ja valitse “%1$s” lisätäksesi sen tänne." "Kiinnitä tärkeät viestit, jotta ne löytyvät helposti." diff --git a/libraries/ui-strings/src/main/res/values-fr/translations.xml b/libraries/ui-strings/src/main/res/values-fr/translations.xml index 8d550ae51e..6aced99b00 100644 --- a/libraries/ui-strings/src/main/res/values-fr/translations.xml +++ b/libraries/ui-strings/src/main/res/values-fr/translations.xml @@ -6,6 +6,9 @@ "Avatar" "Effacer le champ de recherche" "Réduire la taille du composeur" + "Diminuer le nombre de votes autorisés par personne" + "Augmenter le nombre de votes autorisés par personne" + "Émojis personnalisés" "Supprimer" "%1$d chiffre saisi" @@ -16,11 +19,21 @@ "L’adresse complète sera %1$s" "Détails du chiffrement" "Augmenter la taille du composeur" + "Galerie, élément %1$d" + "Galerie, échec de l’analyse de l’élément %1$d" + "Galerie, image %1$d" + + "Galerie, %1$d média de plus" + "Galerie, %1$d média de plus" + + "Galerie, analyse en cours de l’élément %1$d" + "Galerie, vidéo %1$d" "Masquer le mot de passe" "Info" "Rejoindre l’appel" "Retourner à la fin de la conversation" "Aller aux messages non lus" + "Aller au premier message non lu" "Déplacer la carte vers ma position" "Mentions uniquement" "En sourdine" @@ -31,6 +44,7 @@ "Page %1$d" "Pause" "Message vocal, durée: %1$s, position actuelle: %2$s" + "Aperçu de la photo" "Code PIN" "Position épinglée" "Lecture" @@ -41,12 +55,13 @@ "Code QR" "Réagir avec %1$s" "Réagir avec d’autres émojis" - "Lu par %1$s et %2$s" + "Message précédent lu par %1$s et %2$s" - "Lu par %1$s et %2$d autre" - "Lu par %1$s et %2$d autres" + "Message précédent lu par %1$s et %2$d autre" + "Message précédent lu par %1$s et %2$d autres" - "Lu par %1$s" + "Message précédent lu par %1$s" + "afficher tous les accusés de réception" "Supprimer la réaction avec %1$s" "Supprimer la réaction avec %1$s" "Avatar du salon" @@ -59,11 +74,13 @@ "Démarrer un appel" "Passer un appel vidéo" "Lancer un appel vocal" + "Statut" "Discussion dans %1$s" "Discussions dans %1$s" "Salon clôturé" "Avatar de l’utilisateur" "Menu utilisateur" + "Aperçu vidéo" "Voir l’avatar" "Afficher les détails" "Message vocal, durée: %1$s" @@ -138,6 +155,7 @@ "Gérer le compte et les appareils" "Gérez les sessions" "Gérer les salons" + "Marquer comme lu" "Message" "Minimiser" "Suivant" @@ -192,9 +210,11 @@ "Traduire" "Essayer à nouveau" "Désépingler" + "Appel vidéo" "Voir" "Voir dans la discussion" "Afficher la source" + "Appel audio" "Oui" "Oui, réessayez" "Votre serveur prend désormais en charge un nouveau protocole plus rapide. Déconnectez-vous, puis reconnectez-vous pour effectuer la mise à niveau dès maintenant. En le faisant tout de suite, vous éviterez une déconnexion forcée lorsque l’ancien protocole sera supprimé." @@ -215,6 +235,7 @@ "Utilisateurs bloqués" "Bulles" "Appel rejeté" + "Appel en cours" "Appel démarré" "Vous avez rejeté un appel" "Sauvegarde des discussions" @@ -258,7 +279,17 @@ Raison : %1$s." "Fichier enregistré dans Téléchargements" "Transférer le message" "Fréquemment utilisé" + "Galerie" + + "%1$d élément…" + "%1$d éléments…" + + + "%1$d élément multimédia…" + "%1$d éléments multimédia…" + "GIF" + "Appel de groupe en cours" "Image" "En réponse à %1$s" "Installer l’APK" @@ -294,6 +325,7 @@ Raison : %1$s." "Espace sans nom" "Non chiffré" "Hors ligne" + "En appel" "Licences open source" "ou" "Autres options" @@ -401,6 +433,7 @@ Raison : %1$s." "Retirer la sourdine" "Appel non pris en charge" "Événement non pris en charge" + "%1$s a commencé un appel" "Nom d’utilisateur" "Vérification annulée" "Vérification terminée" @@ -422,6 +455,11 @@ Raison : %1$s." "En attente de la position en temps réel…" "Tout le monde peut voir les anciens messages" "Vous" + "Téléchargement indisponible." + "Une erreur est survenue" + "Analyse en cours…" + "L’aperçu et le téléchargement ont été désactivés." + "Le fichier n’est pas sûr" "%1$s (%2$s) a partagé ce message avec vous car vous n’étiez pas dans le salon lors de son envoi." "%1$s a partagé ce message avec vous car vous n’étiez pas dans le salon lors de son envoi." "Ce salon a été configuré pour que les nouveaux membres puissent lire l’historique. %1$s" @@ -482,6 +520,7 @@ Raison : %1$s." "Options" "Supprimer %1$s" "Paramètres" + "Nombre de votes autorisés par personne" "Personne ne partage sa position" "Partage de la position en direct" @@ -489,6 +528,8 @@ Raison : %1$s." "%1$d personnes" "Sur la carte" + "Votre fournisseur de compte se trouve sur votre réseau local. Pour pouvoir communiquer, %1$s a besoin de l’autorisation d’accéder aux appareils de ce réseau." + "Autoriser l’accès au réseau local" "Échec de la sélection du média, veuillez réessayer." "Cliquez (clic long) sur un message et choisissez « %1$s » pour qu‘il apparaisse ici." "Épinglez les messages importants pour leur donner plus de visibilité" @@ -534,6 +575,10 @@ Raison : %1$s." "Espaces" "Partagé %1$s" "Sur la carte" + + "%1$d participant" + "%1$d participants" + "Le message n’a pas été envoyé car l’identité numérique vérifiée de %1$s a été réinitialisée." "Le message n’a pas été envoyé car %1$s n’a pas vérifié tous ses appareils." "Message non envoyé car vous n’avez pas vérifié tous vos appareils." diff --git a/libraries/ui-strings/src/main/res/values-hr/translations.xml b/libraries/ui-strings/src/main/res/values-hr/translations.xml index 3c02673a22..c0879d3a2e 100644 --- a/libraries/ui-strings/src/main/res/values-hr/translations.xml +++ b/libraries/ui-strings/src/main/res/values-hr/translations.xml @@ -8,6 +8,7 @@ "Minimiziraj tekstno polje poruke" "Smanjenje dopuštenih glasova po osobi" "Povećanje broja dopuštenih glasova po osobi" + "Prilagođeni Emoji" "Izbriši" "%1$d unesena znamenka" @@ -65,6 +66,7 @@ "Započni poziv" "Započni videopoziv" "Započni glasovni poziv" + "Stanje" "Nit u %1$s" "Teme u %1$s" "Soba označena za uklanjanje" diff --git a/libraries/ui-strings/src/main/res/values-hu/translations.xml b/libraries/ui-strings/src/main/res/values-hu/translations.xml index 0a37baf199..f198cc0510 100644 --- a/libraries/ui-strings/src/main/res/values-hu/translations.xml +++ b/libraries/ui-strings/src/main/res/values-hu/translations.xml @@ -8,6 +8,7 @@ "Üzenet szövegmezőjének minimalizálása" "Személyenként engedélyezett szavazatok számának csökkentése" "Személyenként engedélyezett szavazatok számának növelése" + "Egyéni emoji" "Törlés" "%1$d megadott számjegy" @@ -23,6 +24,7 @@ "Csatlakozás a híváshoz" "Ugrás az aljára" "Ugrás az olvasatlanhoz" + "Ugrás az első olvasatlan üzenetre" "Térkép áthelyezése a jelenlegi helyre" "Csak megemlítések" "Némítva" @@ -63,6 +65,7 @@ "Hanghívás indítása" "Videohívás indítása" "Hanghívás indítása" + "Állapot" "Üzenetszál itt: %1$s" "Üzenetszálak itt: %1$s" "Elévült szoba" @@ -143,6 +146,7 @@ "Fiók és eszközök kezelése" "Eszközök kezelése" "Szobák kezelése" + "Megjelölés olvasottként" "Üzenet" "Minimalizálás" "Következő" @@ -267,6 +271,14 @@ Ok: %1$s." "Üzenet továbbítása" "Gyakran használt" "Galéria" + + "%1$d melléklet…" + "%1$d melléklet…" + + + "%1$d média…" + "%1$d média…" + "GIF" "Csoportos hívás folyamatban" "Kép" @@ -304,6 +316,7 @@ Ok: %1$s." "Nincs térnév" "Nincs titkosítva" "Kapcsolat nélkül" + "Hívásban" "Nyílt forráskódú licencek" "vagy" "További lehetőségek" @@ -505,6 +518,8 @@ Biztos, hogy folytatja?" "%1$d személy" "A térképen" + "A Matrix-kiszolgáló helyi hálózaton található. A csatlakozáshoz engedélyre van szüksége ennek: %1$s , hogy elérje a hálózaton lévő eszközöket." + "Hozzáférés engedélyezése a helyi hálózathoz" "Nem sikerült kiválasztani a médiát, próbálja újra." "Nyomjon hosszan az üzenetre, és válassza a „%1$s” lehetőséget, hogy itt szerepeljen." "Tűzze ki a fontos üzeneteket, hogy könnyen felfedezhetők legyenek" diff --git a/libraries/ui-strings/src/main/res/values-pl/translations.xml b/libraries/ui-strings/src/main/res/values-pl/translations.xml index 0234af883a..f0ac7785da 100644 --- a/libraries/ui-strings/src/main/res/values-pl/translations.xml +++ b/libraries/ui-strings/src/main/res/values-pl/translations.xml @@ -20,6 +20,16 @@ "Podgląd pełnego adresu %1$s" "Szczegóły szyfrowania" "Powiększ pole tekstowe wiadomości" + "Galeria, załącznik %1$d" + "Galeria, nieudane skanowanie %1$d" + "Galeria, obraz %1$d" + + "Galeria, %1$d dodatkowe media" + "Galeria, %1$d dodatkowe media" + "Galeria, %1$d dodatkowych mediów" + + "Galeria, skanowanie %1$d" + "Galeria, wideo %1$d" "Ukryj hasło" "Informacje" "Dołącz do połączenia" @@ -184,8 +194,8 @@ "Wyślij edytowaną wiadomość" "Wyślij wiadomość" "Wyślij wiadomość głosową" - "Wyślij" - "Wyślij link" + "Udostępnij" + "Udostępnij link" "Udostępnij lokalizację na żywo" "Pokaż" "Zaloguj się ponownie" diff --git a/libraries/ui-strings/src/main/res/values-ro/translations.xml b/libraries/ui-strings/src/main/res/values-ro/translations.xml index 4eba83312b..cd18373e6a 100644 --- a/libraries/ui-strings/src/main/res/values-ro/translations.xml +++ b/libraries/ui-strings/src/main/res/values-ro/translations.xml @@ -1,23 +1,41 @@ + "Adăugați un avatar" "Adăugați o reacție: %1$s" "Adresă" "Imagine de profil" + "Ștergeți câmpul de căutare" "Micșorați câmpul mesajului" + "Reduceți numărul de voturi permise per persoană" + "Măriți numărul de voturi permise per persoană" + "Emoji personalizat" "Ștergere" "%1$d cifră introdusă" "%1$d cifre introduse" "%1$d cifre introduse" + "Durată: %1$s" "Editați avatarul" "Adresa completă va fi %1$s" "Detalii privind criptarea" "Extindeți câmpul mesajului" + "Galerie, atașament %1$d" + "Galerie, scanare eșuată %1$d" + "Galerie, imagine %1$d" + + "Galerie, încă %1$d fișier media" + "Galerie, încă %1$d fișiere media" + "Galerie, încă %1$d fișiere media" + + "Galerie, scanare %1$d" + "Galerie, videoclip %1$d" "Ascundeți parola" "Informații" "Alăturați-vă apelului" "Mergeți în jos" + "Săriți la necitite" + "Săriți la primul mesaj necitit" "Mutați harta la locația mea" "Doar mențiuni" "Notificări dezactivate" @@ -28,12 +46,14 @@ "Pagina %1$d" "Pauză" "Mesaj vocal, durată:%1$s, poziție curentă: %2$s" + "Previzualizare foto" "Câmp PIN" "Locație fixată" "Redați" "Viteză de redare" "Sondaj" "Sondaj încheiat" + "Poziție: %1$s" "Cod QR" "Reacționați cu %1$s" "Reacționați cu alte emoji-uri" @@ -44,20 +64,26 @@ "Citit de %1$s și incă %2$d" "Citit de %1$s" + "afișați toate confirmările de citire" "Îndepărtați reacția cu %1$s" "Îndepărtați reacția %1$s" "Avatarul camerei" "Trimiteți fișiere" "Locația expeditorului" + "Trimis de %1$s la %2$s" "Acțiune limitată în timp necesară, aveți un minut pentru a verifica" "Setări, acțiune necesară" "Afișați parola" "Începeți un apel" "Inițiați un apel video" "Inițiați un apel vocal" + "Statuts" + "Fir în: %1$s" + "Fire în %1$s" "Cameră terminată" "Avatar utilizator" "Meniu utilizator" + "Previzualizare video" "Vizualizați avatarul" "Vizualizați detalii" "Mesaj vocal, durată: %1$s" @@ -94,6 +120,7 @@ "Refuzați și blocați" "Ștergere" "Ștergeți contul" + "Ștergeți fișierul" "Ștergeți sondajul" "Deselectați tot" "Dezactivați" @@ -131,6 +158,7 @@ "Gestionați contul și dispozitivele" "Gestionați dispozitivele" "Gestionați camerele" + "Marcați ca citit" "Contactați" "Minimizați" "Următorul" @@ -185,9 +213,11 @@ "Traduceți" "Încercați din nou" "Defixați" + "Apel video" "Vizualizați" "Vedeți în lista de mesaje" "Vedeți sursă" + "Apel vocal" "Da" "Da, încercați din nou" "Serverul dvs. acceptă acum un protocol nou, mai rapid. Deconectați-vă și conectați-vă din nou pentru a face upgrade acum. Dacă faceți acest lucru acum, vă va ajuta să evitați o deconectare forțată atunci când vechiul protocol este eliminat ulterior." @@ -208,6 +238,7 @@ "Utilizatori blocați" "Baloane" "Apel respins" + "Apel în curs" "Apel inițiat" "Ați respins un apel" "Backup conversații" @@ -251,7 +282,19 @@ Motiv:%1$s." "Fișier salvat în Descărcări" "Redirecționați mesajul" "Utilizate frecvent" + "Galerie" + + "%1$d atașament…" + "%1$d atașamente…" + "%1$d atașamente…" + + + "%1$d element media…" + "%1$d elemente media…" + "%1$d elemente media…" + "GIF" + "Apel de grup în curs" "Imagine" "Ca răspuns la %1$s" "Instalați APK" @@ -289,6 +332,7 @@ Motiv:%1$s." "Fără nume de spațiu" "Necriptat" "Deconectat" + "Într-un apel" "Licențe open source" "sau" "Alte opțiuni" @@ -301,6 +345,7 @@ Motiv:%1$s." "Va rugam asteptati…" "Sunteți sigur că doriți să încheiați acest sondaj?" "Sondajul %1$s" + "Sondaj" "Total voturi: %1$s" "Rezultatele vor fi afișate după încheierea sondajului" @@ -400,6 +445,7 @@ Motiv:%1$s." "Activare sunet" "Apel incompatibil" "Eveniment neacceptat" + "%1$s a inițiat un apel" "Utilizator" "Verificare anulată" "Verificare completă" @@ -421,6 +467,11 @@ Motiv:%1$s." "Se așteptă localizarea în timp real…" "Oricine poate vedea istoricul" "Dumneavoastră" + "Descărcarea nu este disponibilă." + "Ceva nu a mers bine" + "Se scanează…" + "Previzualizarea și descărcarea au fost dezactivate." + "Fișierul nu este sigur" "%1$s (%2$s) a distribuit acest mesaj deoarece nu erați în cameră când a fost trimis." "%1$s a distribuit acest mesaj deoarece nu erați în cameră când a fost trimis." "Această cameră a fost configurată astfel încât noii membri să poată citi istoricul. %1$s" @@ -481,6 +532,7 @@ Sunteți sigur că doriți să continuați?" "Opțiuni" "Ștergeți %1$s" "Setări" + "Voturi permise per persoană" "Nimeni nu își partajează locația" "Se partajează locația în timp real" @@ -489,6 +541,8 @@ Sunteți sigur că doriți să continuați?" "%1$d persoane" "Pe hartă" + "Homeserverul dumneavoastră se află în rețeaua locală. Pentru a se conecta, %1$s are nevoie de permisiunea de a accesa dispozitive din această rețea." + "Permiteți accesul la rețeaua locală" "Selectarea fișierelor media a eșuat, încercați din nou." "Apăsați pe un mesaj și alegeți \"%1$s\" pentru a-l include aici." "Fixați mesajele importante, astfel încât să poată fi descoperite cu ușurință" @@ -535,6 +589,11 @@ Sunteți sigur că doriți să continuați?" "Spații" "Partajat %1$s" "Pe hartă" + + "%1$d s-a alăturat" + "%1$d s-au alăturat" + "%1$d s-au alăturat" + "Mesajul nu a fost trimis deoarece identitatea digitala verificată a lui %1$s s-a schimbat." "Mesajul nu a fost trimis deoarece %1$s nu a verificat toate dispozitivele." "Mesajul nu a fost trimis deoarece nu ați verificat unul sau mai multe dispozitive." @@ -546,4 +605,6 @@ Sunteți sigur că doriți să continuați?" "Nu aveți acces la acest mesaj" "Nu s-a putut decripta mesajul" "Acest mesaj a fost blocat fie pentru că nu ați verificat dispozitivul, fie pentru că expeditorul trebuie să vă verifice identitatea digitală." + "Dispozitivul dumneavoastră este prea vechi, este necesar un dispozitiv cu Android 8 sau o versiune mai nouă." + "Afișarea hărților nu este suportată" diff --git a/libraries/ui-strings/src/main/res/values-sv/translations.xml b/libraries/ui-strings/src/main/res/values-sv/translations.xml index 4e46cd4653..cdaa72f5d3 100644 --- a/libraries/ui-strings/src/main/res/values-sv/translations.xml +++ b/libraries/ui-strings/src/main/res/values-sv/translations.xml @@ -440,7 +440,7 @@ Anledning:%1$s." "Öppna i Apple Maps" "Öppna i Google Maps" "Öppna i OpenStreetMap" - "Dela fäst plats" + "Dela vald plats" "Utrymmen som du har skapat eller gått med i." "%1$s • %2$s" "Utrymmen" diff --git a/libraries/ui-strings/src/main/res/values-uk/translations.xml b/libraries/ui-strings/src/main/res/values-uk/translations.xml index 9e93cdb891..e00a269473 100644 --- a/libraries/ui-strings/src/main/res/values-uk/translations.xml +++ b/libraries/ui-strings/src/main/res/values-uk/translations.xml @@ -20,6 +20,16 @@ "Повна адреса буде %1$s" "Подробиці шифрування" "Розгорнути текстове поле повідомлення" + "Галерея, вкладення %1$d" + "Галерея, невдалося сканувати %1$d" + "Галерея, зображення %1$d" + + "Галерея, ще %1$d медіа" + "Галерея, ще %1$d медіа" + "Галерея, ще %1$d медіа" + + "Галерея, сканування %1$d" + "Галерея, відео %1$d" "Cховати пароль" "Інформація" "Приєднатися до виклику" diff --git a/libraries/ui-strings/src/main/res/values-zh-rTW/translations.xml b/libraries/ui-strings/src/main/res/values-zh-rTW/translations.xml index c2ff955eac..171551d71e 100644 --- a/libraries/ui-strings/src/main/res/values-zh-rTW/translations.xml +++ b/libraries/ui-strings/src/main/res/values-zh-rTW/translations.xml @@ -1,20 +1,29 @@ + "新增大頭照" "新增反應:%1$s" "地址" "大頭貼" + "清除搜尋欄位" "最小化訊息文字欄位" + "減少每人可投的票數" + "增加每人可投的票數上限" + "自訂表情符號" "刪除" "已輸入 %1$d 個位數" + "持續時間:%1$s" "編輯大頭照" "完整地址為 %1$s" "加密詳細資訊" "展開訊息文字欄位" "隱藏密碼" + "資訊" "加入通話" "跳至底部" + "跳至未讀訊息" + "跳到第一則未讀訊息" "將地圖移動到我的位置" "僅限提及" "已關閉通知" @@ -25,33 +34,42 @@ "第 %1$d 頁" "暫停" "語音訊息,時長:%1$s,目前位置:%2$s" + "照片預覽" "PIN 碼欄位" "固定位置" "播放" "播放速度" "投票" "投票已結束" + "位置:%1$s" "QR Code" "使用 %1$s 回應" "用其他表情符號回應" - "%1$s 和 %2$s 已讀" + "上一則訊息已被 %1$s 和 %2$s 閱讀" - "%1$s 與其他 %2$d 個人已讀" + "前一則訊息已被 %1$s 及另外 %2$d 人閱讀" - "%1$s 已讀" + "上一則訊息由 %1$s 閱讀" + "顯示所有讀取回條" "移除 %1$s 的反應" "移除反應 %1$s" "聊天室大頭照" "傳送檔案" "傳送者位置" + "由 %1$s 於 %2$s 傳送" "需要限時動作,您有一分鐘可以驗證" + "設定,需採取行動" "顯示密碼" "開始通話" "開始視訊通話" "開始語音通話" + "狀態" + "%1$s 中的討論串" + "%1$s 中的討論串" "墓碑聊天室" "使用者大頭照" "使用者選單" + "影片預覽" "檢視大頭照" "檢視詳細資訊" "語音訊息,時長:%1$s" @@ -66,6 +84,7 @@ "通話" "取消" "暫時取消" + "選擇檔案" "選擇照片" "清除" "關閉" @@ -85,12 +104,16 @@ "停用帳號" "拒絕" "拒絕並封鎖" + "刪除" + "刪除帳號" + "刪除檔案" "刪除投票" "取消全選" "停用" "捨棄" "關閉" "完成" + "下載" "編輯" "編輯標題" "編輯投票" @@ -121,6 +144,7 @@ "管理帳號與裝置" "管理裝置" "管理聊天室" + "標記為已讀" "聊天" "最小化" "下一步" @@ -175,9 +199,11 @@ "翻譯" "再試一次" "取消釘選" + "視訊通話" "檢視" "在時間軸中檢視" "檢視來源" + "語音通話" "是" "是的,再試一次" "您的伺服器現在支援新的、更快的協定。立即登出並重新登入以進行升級。現在這樣做將協助您避免在稍後移除舊協定時被強制登出。" @@ -197,7 +223,10 @@ "測試版" "封鎖的使用者" "泡泡" + "通話被拒" + "通話中" "開始通話" + "您拒絕了通話" "聊天室備份" "已複製到剪貼簿" "著作權" @@ -239,7 +268,15 @@ "檔案已儲存至 Downloads" "轉寄訊息" "經常使用" + "圖庫" + + "%1$d 個附件⋯⋯" + + + "%1$d 個媒體項目⋯⋯" + "GIF" + "群組通話進行中" "圖片" "回覆 %1$s" "安裝 APK" @@ -273,6 +310,7 @@ "沒有空間名稱" "未加密" "離線" + "正在通話" "開放原始碼授權條款" "或" "其他選項" @@ -285,6 +323,7 @@ "請稍等…" "您確定要結束這項投票嗎?" "投票:%1$s" + "投票" "總票數:%1$s" "結果將在投票結束後公佈" @@ -374,6 +413,7 @@ "開啟通知" "不支援的通話" "不支援的事件" + "%1$s 已發起通話" "使用者名稱" "驗證已取消" "驗證完成" @@ -395,6 +435,11 @@ "正在等待即時位置……" "任何人都可以檢視歷史" "您" + "無法下載。" + "發生錯誤" + "正在掃描⋯⋯" + "預覽與下載功能已停用。" + "檔案不安全" "因為您當時不在聊天室內,所以 %1$s (%2$s) 分享了此訊息。" "因為您當時不在聊天室裡面,因此 %1$s 分享了此訊息。" "此聊天室被設定為方便新成員閱讀歷史紀錄。%1$s" @@ -445,6 +490,9 @@ "抱歉,發生錯誤" "🔐️ 在 %1$s 上加入我" "嘿,來 %1$s 和我聊天:%2$s" + "即時位置分享" + "正在分享位置" + "%1$s 即時位置" "%1$s Android" "憤怒搖晃以回報臭蟲" "螢幕截圖" @@ -452,6 +500,15 @@ "選項" "移除 %1$s" "設定" + "每人可投票數" + "沒有人在分享位置" + "分享即時位置" + + "%1$d 人" + + "在地圖上" + "您的家伺服器位於區域網路。要連線,%1$s 需要取得存取此網路上裝置的權限。" + "允許存取區域網路" "選取媒體失敗,請再試一次。" "按一下訊息,然後選擇「%1$s」以加入至此。" "釘選重要訊息,如此才能輕鬆發現" @@ -496,6 +553,9 @@ "空間" "已分享 %1$s" "在地圖上" + + "%1$d 人已加入" + "因為 %1$s 的驗證數位身份已重設,因此未傳送訊息。" "訊息未傳送,因為 %1$s 尚未驗證所有裝置。" "因為您尚未驗證一個或多個裝置,因此未傳送訊息" @@ -507,4 +567,6 @@ "您無法存取此則訊息" "無法解密訊息" "此訊息被封鎖,原因可能是您尚未驗證裝置,或是寄件者需要驗證您的數位身分。" + "您的裝置版本過舊,需要執行 Android 8 或更新版本的裝置。" + "不支援顯示地圖" diff --git a/libraries/ui-strings/src/main/res/values-zh/translations.xml b/libraries/ui-strings/src/main/res/values-zh/translations.xml index 0ecd99f6c8..03929c0182 100644 --- a/libraries/ui-strings/src/main/res/values-zh/translations.xml +++ b/libraries/ui-strings/src/main/res/values-zh/translations.xml @@ -18,6 +18,14 @@ "完整地址为 %1$s" "加密详情" "展开消息文本框" + "媒体组,第 %1$d 个附件" + "媒体组,第 %1$d 个扫描失败" + "媒体组,第 %1$d 个图像" + + "媒体组,其余 %1$d 个媒体" + + "媒体组,正在扫描第 %1$d 个" + "媒体组,第 %1$d 个视频" "隐藏密码" "信息" "加入通话" @@ -268,7 +276,7 @@ "文件已保存到“下载”" "转发消息" "常用" - "图库" + "媒体组" "%1$d 个附件…" diff --git a/libraries/ui-strings/src/main/res/values/localazy.xml b/libraries/ui-strings/src/main/res/values/localazy.xml index 49dedb49e1..92899ba9da 100644 --- a/libraries/ui-strings/src/main/res/values/localazy.xml +++ b/libraries/ui-strings/src/main/res/values/localazy.xml @@ -19,6 +19,15 @@ "The full address will be %1$s" "Encryption details" "Expand message text field" + "Gallery, attachment %1$d" + "Gallery, failed scan %1$d" + "Gallery, image %1$d" + + "Gallery, %1$d more media" + "Gallery, %1$d more medias" + + "Gallery, scanning %1$d" + "Gallery, video %1$d" "Hide password" "Info" "Join call" diff --git a/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserListDataSource.kt b/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserListDataSource.kt index 0f7e02c7a8..3697125922 100644 --- a/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserListDataSource.kt +++ b/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserListDataSource.kt @@ -11,8 +11,24 @@ package io.element.android.libraries.usersearch.api import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.user.MatrixUser +/** + * Low-level access to the homeserver's user directory; see [UserRepository] for the search used by the UI. + */ interface UserListDataSource { - // TODO should probably have a flow + /** + * Searches the user directory, returning an empty list rather than failing when the request does not succeed. + * TODO should probably have a flow + * + * @param query the text to look for in user ids and display names. + * @param count the maximum number of results to return. + */ suspend fun search(query: String, count: Long): List + + /** + * Fetches one user's profile. + * + * @param userId the user whose profile is requested. + * @return the profile, or `null` when it could not be retrieved. + */ suspend fun getProfile(userId: UserId): MatrixUser? } diff --git a/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserRepository.kt b/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserRepository.kt index f7e5367a9a..b3be565ca5 100644 --- a/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserRepository.kt +++ b/libraries/usersearch/api/src/main/kotlin/io/element/android/libraries/usersearch/api/UserRepository.kt @@ -10,6 +10,15 @@ package io.element.android.libraries.usersearch.api import kotlinx.coroutines.flow.Flow +/** + * Searches for users to start a conversation with or invite, combining the homeserver directory with what the app already knows. + */ interface UserRepository { + /** + * Runs a search and emits its progress, so the UI can show local results before the directory answers. + * A query that is a well-formed user id other than the current user's also yields that user, even when the directory does not know them. + * + * @param query the text typed by the user. + */ fun search(query: String): Flow } diff --git a/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessagePresenterFactory.kt b/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessagePresenterFactory.kt index 0229ed991f..1b576a6d72 100644 --- a/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessagePresenterFactory.kt +++ b/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessagePresenterFactory.kt @@ -13,7 +13,17 @@ import io.element.android.libraries.matrix.api.core.EventId import io.element.android.libraries.matrix.api.media.MediaSource import kotlin.time.Duration +/** + * Creates the presenter of a single voice message player, one per voice message shown in a timeline. + */ interface VoiceMessagePresenterFactory { + /** + * @param eventId the event carrying the voice message, or `null` while it is still a local echo. + * @param mediaSource where the audio is fetched from. + * @param mimeType the MIME type of the audio, or `null` when the event did not state it. + * @param filename the file name to display, or `null` when the event did not state it. + * @param duration the length of the recording, used to render the waveform before the audio is downloaded. + */ fun createVoiceMessagePresenter( eventId: EventId?, mediaSource: MediaSource, diff --git a/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessageStateProvider.kt b/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessageStatePreviewParam.kt similarity index 95% rename from libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessageStateProvider.kt rename to libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessageStatePreviewParam.kt index dd8d222e69..f417947cb6 100644 --- a/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessageStateProvider.kt +++ b/libraries/voiceplayer/api/src/main/kotlin/io/element/android/libraries/voiceplayer/api/VoiceMessageStatePreviewParam.kt @@ -10,7 +10,7 @@ package io.element.android.libraries.voiceplayer.api import androidx.compose.ui.tooling.preview.PreviewParameterProvider -open class VoiceMessageStateProvider : PreviewParameterProvider { +open class VoiceMessageStatePreviewParam : PreviewParameterProvider { override val values: Sequence get() = sequenceOf( aVoiceMessageState( diff --git a/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorder.kt b/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorder.kt index 5e4c9ae132..4823c67c6a 100644 --- a/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorder.kt +++ b/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorder.kt @@ -71,14 +71,17 @@ class DefaultVoiceRecorder( override val state: StateFlow = _state @RequiresPermission(Manifest.permission.RECORD_AUDIO) - override suspend fun startRecord() { + override suspend fun startRecord() = lock.withLock { + if (recordingJob != null) { + Timber.w("Voice recorder is already recording, ignoring this start") + return@withLock + } + Timber.i("Voice recorder started recording") outputFile = fileManager.createFile() .also(encoder::init) - lock.withLock { - levels.clear() - } + levels.clear() val audioRecorder = audioReaderFactory.create(config, dispatchers).also { audioReader = it } diff --git a/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/di/VoiceRecorderModule.kt b/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/di/VoiceRecorderBindingContainer.kt similarity index 87% rename from libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/di/VoiceRecorderModule.kt rename to libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/di/VoiceRecorderBindingContainer.kt index ee9f7bfa9d..3dd1b902fa 100644 --- a/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/di/VoiceRecorderModule.kt +++ b/libraries/voicerecorder/impl/src/main/kotlin/io/element/android/libraries/voicerecorder/impl/di/VoiceRecorderBindingContainer.kt @@ -22,9 +22,9 @@ import io.element.android.opusencoder.OggOpusEncoder @BindingContainer @ContributesTo(RoomScope::class) -object VoiceRecorderModule { +object VoiceRecorderBindingContainer { @Provides - fun provideAudioConfig(): AudioConfig { + fun providesAudioConfig(): AudioConfig { val sampleRate = SampleRate return AudioConfig( format = AudioFormat.Builder() @@ -40,7 +40,7 @@ object VoiceRecorderModule { } @Provides - public fun provideVoiceFileConfig(): VoiceFileConfig = + public fun providesVoiceFileConfig(): VoiceFileConfig = VoiceFileConfig( cacheSubdir = "voice_recordings", fileExt = "ogg", @@ -48,5 +48,5 @@ object VoiceRecorderModule { ) @Provides - fun provideOggOpusEncoder(): OggOpusEncoder = OggOpusEncoder.create() + fun providesOggOpusEncoder(): OggOpusEncoder = OggOpusEncoder.create() } diff --git a/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorderTest.kt b/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorderTest.kt index e3ff6f9198..070b341d76 100644 --- a/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorderTest.kt +++ b/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/impl/DefaultVoiceRecorderTest.kt @@ -18,7 +18,7 @@ import io.element.android.libraries.voicerecorder.api.VoiceRecorderState import io.element.android.libraries.voicerecorder.impl.audio.Audio import io.element.android.libraries.voicerecorder.impl.audio.AudioConfig import io.element.android.libraries.voicerecorder.impl.audio.SampleRate -import io.element.android.libraries.voicerecorder.impl.di.VoiceRecorderModule +import io.element.android.libraries.voicerecorder.impl.di.VoiceRecorderBindingContainer import io.element.android.libraries.voicerecorder.test.FakeAudioLevelCalculator import io.element.android.libraries.voicerecorder.test.FakeAudioReaderFactory import io.element.android.libraries.voicerecorder.test.FakeEncoder @@ -39,6 +39,7 @@ import kotlin.time.TestTimeSource class DefaultVoiceRecorderTest { private val fakeFileSystem = FakeFileSystem() private val timeSource = TestTimeSource() + private val audioReaderFactory = FakeAudioReaderFactory(audio = AUDIO) @Test fun `it emits the initial state`() = runTest { @@ -109,6 +110,32 @@ class DefaultVoiceRecorderTest { } } + @Test + fun `when startRecord is called twice, the second call is ignored`() = runTest { + val voiceRecorder = createDefaultVoiceRecorder() + voiceRecorder.state.test { + assertThat(awaitItem()).isEqualTo(VoiceRecorderState.Idle) + + voiceRecorder.startRecord() + voiceRecorder.startRecord() + assertThat(audioReaderFactory.createdCount).isEqualTo(1) + + skipItems(1) + timeSource += 5.seconds + skipItems(2) + voiceRecorder.stopRecord() + assertThat(awaitItem()).isEqualTo( + VoiceRecorderState.Finished( + file = File(FILE_PATH), + mimeType = MimeTypes.Ogg, + waveform = List(100) { 1f }, + duration = 5.seconds, + ) + ) + expectNoEvents() + } + } + @Test fun `when cancelled, it deletes the file`() = runTest { val voiceRecorder = createDefaultVoiceRecorder() @@ -124,13 +151,11 @@ class DefaultVoiceRecorderTest { } private fun TestScope.createDefaultVoiceRecorder(): DefaultVoiceRecorder { - val fileConfig = VoiceRecorderModule.provideVoiceFileConfig() + val fileConfig = VoiceRecorderBindingContainer.providesVoiceFileConfig() return DefaultVoiceRecorder( dispatchers = testCoroutineDispatchers(), timeSource = timeSource, - audioReaderFactory = FakeAudioReaderFactory( - audio = AUDIO, - ), + audioReaderFactory = audioReaderFactory, encoder = FakeEncoder(fakeFileSystem), config = AudioConfig( format = audioFormat, diff --git a/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/test/FakeAudioReaderFactory.kt b/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/test/FakeAudioReaderFactory.kt index d4bd241aaa..d3e434538e 100644 --- a/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/test/FakeAudioReaderFactory.kt +++ b/libraries/voicerecorder/impl/src/test/kotlin/io/element/android/libraries/voicerecorder/test/FakeAudioReaderFactory.kt @@ -16,7 +16,11 @@ import io.element.android.libraries.voicerecorder.impl.audio.AudioReader class FakeAudioReaderFactory( private val audio: List