Compare commits

...

1527 Commits

Author SHA1 Message Date
Damir Jelić 9ffe5aa6ca chore: Add a description to the test utils crate 2025-09-04 16:42:00 +02:00
Damir Jelić c604e4acd2 chore: Update the cargo lock file for the matrix-sdk-test-utils crate 2025-09-04 16:38:45 +02:00
Damir Jelić f8b343bece chore: Include the test-utils crate in the release
Turns out, we do actually need to release it :(
2025-09-04 16:36:05 +02:00
Damir Jelić 94f8f8c44c Revert "chore: Disable releases for the matrix-sdk-test-utils crate"
This reverts commit f9bf492fdb.
2025-09-04 16:36:05 +02:00
Damir Jelić 4c1f80faf7 chore: Release matrix-sdk version 0.14.0 2025-09-04 16:05:48 +02:00
Damir Jelić f9bf492fdb chore: Disable releases for the matrix-sdk-test-utils crate
The crate is only used as a dev dependency, as such we don't need to
release it.
2025-09-04 16:05:48 +02:00
Damir Jelić 824fc0b62e chore: Add a changelog for the matrix-sdk-search crate 2025-09-04 16:05:48 +02:00
Kévin Commaille 359db7f28b Add changelog
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-09-04 11:48:48 +02:00
Kévin Commaille 30672e6feb Upgrade Ruma
Use the brand new release.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-09-04 11:48:48 +02:00
Benjamin Bouvier f9b419077d refactor(sdk): limit the quantity of data passed to the read receipt processor
This limits cloning.
2025-09-03 16:56:53 +02:00
Benjamin Bouvier d46f934d57 perf: process read receipts concurrently
By slightly changing the shape of the function used to process read
receipts, we can make it so that it's trivial to run concurrently, which
gives some nice speedups locally.

Distribution of 6 worst case processing time, initial response:

Before:
0.172524963s
0.216173016s
0.252289760s
0.257619156s
0.275838632s
0.280295891s

After:
0.083094692s
0.117074046s
0.130246646s
0.132577343s
0.138685246s
0.170287945s
2025-09-03 16:56:53 +02:00
Damir Jelić 0bed6afc29 fix(multiverse): Define the color of the placeholder text of the input line
This ensures that we're using the same color despite what your color
scheme of your terminal is. Some color schemes might produce unreadable
combinations of foreground color and background color.
2025-09-03 15:45:48 +02:00
Shrey Patel 412d4b80ee refactor(search): Move event processing out. 2025-09-03 15:05:23 +02:00
multi prise bcabf1bda4 Improve perfomance of build_room_key_bundle 2025-09-03 14:18:40 +02:00
Jorge Martín 7767ef6ca3 fix(ffi): Adapt FFI calls to Client::server_vendor_info to the new API
Specially important, the one from `ClientBuilder::build` as it avoids a situation where the builder would infinitely try to get a response for this request and never create the `Client` or fail.
2025-09-03 13:18:14 +02:00
Jorge Martín 6765ca0c39 refactor(sdk): Make Client::server_vendor_info accept an optional request config 2025-09-03 13:18:14 +02:00
Benjamin Bouvier 17abab0d53 chore(ci): bump wasm-pack and the runtime timeout 2025-09-03 12:46:09 +02:00
Benjamin Bouvier cc0bf91a06 feat(ffi): add a sync profiling log pack 2025-09-03 12:46:09 +02:00
Benjamin Bouvier 0b3345f592 feat(sdk): add more timers to sync processing 2025-09-03 12:46:09 +02:00
Benjamin Bouvier 472b934816 refactor(sdk): remove a few useless async 2025-09-02 19:56:23 +02:00
Ivan Enderlin 27a28e55d1 feat(ui): Add is_own and profile to LatestEventValue::Remote.
This patch adds 2 fields to `LatestEventValue::Remote`: `is_own` and
`profile`, which are necessary for the app consumers.
2025-09-02 18:18:26 +02:00
Ivan Enderlin d6a418f46a feat(ffi): Create Room::new_latest_event + LatestEventValue.
This patch creates the `LatestEventValue` in `matrix_sdk_ffi` and
exposes it via `Room::new_latest_event`.
2025-09-02 18:18:26 +02:00
Ivan Enderlin 268e14e4f5 feat(ui): Create timeline::LatestEventValue. 2025-09-02 18:18:26 +02:00
Ivan Enderlin f1190deef9 refactor(ui): TimelineAction::from_event zips two arguments.
This patch zips the `unable_to_decrypt_info` and the `meta` arguments
into a single one. They are strictly related, `meta` has no sense if
`unable_to_decrypt_info` has no sense neither.
2025-09-02 18:18:26 +02:00
Michael Goldenberg ee62cd749f refactor(indexeddb): add migrations and types for media retention metadata index
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-09-02 15:38:34 +02:00
Michael Goldenberg cea5c190d8 refactor(indexeddb): add migrations and types for media last access index
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-09-02 15:38:34 +02:00
Michael Goldenberg ad4cb4f6c9 refactor(indexeddb): add migrations and types for media source index
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-09-02 15:38:34 +02:00
Michael Goldenberg 949e7a6cac refactor(indexeddb): add migrations and types for media content size index
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-09-02 15:38:34 +02:00
Michael Goldenberg 8e66963a1e refactor(indexeddb): add types and migrations for storing media via event cache
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-09-02 15:38:34 +02:00
Michael Goldenberg aa02e31cf6 refactor(indexeddb): add types for representing media and associated metadata
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-09-02 15:38:34 +02:00
Michael Goldenberg 57c7972c63 refactor(indexeddb): add foreign (de)serialization for IgnoreMediaRetentionPolicy
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-09-02 15:38:34 +02:00
Benjamin Bouvier e89ac3d7df tests: add some sliding sync tests for thread subscriptions and catchup 2025-09-02 14:57:49 +02:00
Benjamin Bouvier a3704c3563 tests: rearrange some imports ni the sdk/tests/integration/client file 2025-09-02 14:57:49 +02:00
Benjamin Bouvier 5fb728e8f0 feat(sdk): use local thread subscription data if it's accurate \o/ 2025-09-02 14:57:49 +02:00
Benjamin Bouvier eab62ec0b5 feat(sdk): automatically catch up missing thread subscriptions 2025-09-02 14:57:49 +02:00
Benjamin Bouvier 2fae949a42 feat(sliding sync): add support for the thread subscriptions extension 2025-09-02 14:57:49 +02:00
Benjamin Bouvier 4adbb4aa88 feat(sdk): add support for persisting the thread subscription catchup tokens 2025-09-02 14:57:49 +02:00
Benjamin Bouvier 18affe3edd chore: bump Ruma 2025-09-02 14:57:49 +02:00
multisme ea59bc8955 Implement querying inboundgroupsessions by room_id (#5534)
History sharing: improve efficiency of building key bundle

Signed-off-by: multi
[multiestunhappydev@gmail.com](mailto:multiestunhappydev@gmail.com)

Partially Implement
https://github.com/matrix-org/matrix-rust-sdk/issues/5513

---------

Signed-off-by: multisme <korokoko.toi@gmail.com>
Co-authored-by: Richard van der Hoff <richard@matrix.org>
2025-09-02 12:07:07 +01:00
Shrey Patel 68f6d927f1 test(search): Add tests for edits in search index. 2025-09-02 12:25:53 +02:00
Shrey Patel c3766789cc feat(search): add edits to search index. 2025-09-02 12:25:53 +02:00
Shrey Patel 7c31525f68 test(search): Add tests for indexing redactions. 2025-09-02 12:25:53 +02:00
Shrey Patel b2dd5ce02d feat(search): add deletion from index 2025-09-02 12:25:53 +02:00
dependabot[bot] 1f2b4f87bc chore(deps): bump CodSpeedHQ/action from 3.8.0 to 3.8.1
Bumps [CodSpeedHQ/action](https://github.com/codspeedhq/action) from 3.8.0 to 3.8.1.
- [Release notes](https://github.com/codspeedhq/action/releases)
- [Changelog](https://github.com/CodSpeedHQ/action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codspeedhq/action/compare/0b6e7a3d96c9d2a6057e7bcea6b45aaf2f7ce60b...76578c2a7ddd928664caa737f0e962e3085d4e7c)

---
updated-dependencies:
- dependency-name: CodSpeedHQ/action
  dependency-version: 3.8.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-02 08:42:02 +02:00
dependabot[bot] 893c45af74 chore(deps): bump crate-ci/typos from 1.35.5 to 1.35.7
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.35.5 to 1.35.7.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.35.5...v1.35.7)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.35.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-02 08:41:24 +02:00
Richard van der Hoff a161dfa9a0 crypto: log message index for megolm sessions received over olm
When we receive a to-device message that contains a megolm decryption key, log
the ratchet index of the received key, for debugging.
2025-09-01 17:42:33 +01:00
Damir Jelić 20cd0bedfa chore: Fix a clippy warning about a useless conversion 2025-09-01 16:33:10 +02:00
Damir Jelić d4a1ce06e4 chore: Allow the CDLA license 2025-09-01 16:33:10 +02:00
Damir Jelić e53906a920 chore: Bump vergen
Vergen has split into multiple, more dedicated crates. This bump is
therefore a migration to vergen-gitcl.
2025-09-01 16:33:10 +02:00
Damir Jelić 1e30916754 chore: Bump most of our deps 2025-09-01 16:33:10 +02:00
Damir Jelić 15c46b503c chore: Update our deny config 2025-09-01 10:46:10 +02:00
Damir Jelić 5cd3818841 chore: Fix a clippy warning about unused lifetimes 2025-09-01 10:46:10 +02:00
Damir Jelić 79b7d6d235 chore: Use the upstream tracing repo
The necessary patch was merged[1] now, thanks to Jonas. We still need
the patch section since we don't have a release with the patch.

[1]: https://github.com/tokio-rs/tracing/pull/3000
2025-09-01 10:46:10 +02:00
Damir Jelić 05d0f9e077 chore: Don't patch the paranoid-android crate
Our paranoid-android for was configured to use our fork of the tracing
crates.

But paranoid-android will already use our tracing fork since it's
defined in the patch section. The patch section will override the
dependencies for all of our dependencies as well.

This can be seen in the dependency tree using:
    $ cargo tree -p matrix-sdk-ffi --target=aarch64-linux-android
2025-09-01 10:46:10 +02:00
Damir Jelić 4c1e2d6d51 chore: Fix a warning about a type visibility 2025-09-01 10:46:10 +02:00
Damir Jelić c9162373a1 chore: Bump the tracing version we're using
This gets rid of a vulnerability[1] in tracing-subscriber. The forked
version we're using for the bindings were bumped as well.


[1]: https://github.com/advisories/GHSA-xwfj-jgwm-7wp5
2025-09-01 10:46:10 +02:00
Benjamin Bouvier 9f22f550bf refactor(sdk): avoid duplicating the comparison of bumpstamps 2025-09-01 10:38:34 +02:00
Benjamin Bouvier 7a762035f1 feat(sdk): store the thread subscription bumpstamp and implement the correct upsert semantics 2025-09-01 10:38:34 +02:00
Benjamin Bouvier 8c0a918e6e refactor(sdk): introduce a lightweight ThreadSubscription for external consumers, and rename previous one to StoredThreadSubscription
External consumers are likely not interested about unsubscriptions and
the bump stamp values themselves, so let's not expose these to them.
2025-09-01 10:38:34 +02:00
Benjamin Bouvier 33c317e6d2 refactor(sdk): put the subscription status + bumpstamp back into the stored thread subscription 2025-09-01 10:38:34 +02:00
Eric Eastwood 371ed49670 Document --proxy option in the multiverse client
To be able to inspect network requests flying around as you interact

Spawning from https://github.com/matrix-org/matrix-rust-sdk/issues/5600#issuecomment-3238128112
2025-08-30 09:56:33 +02:00
Stefan Ceriu f0c1c65308 fix(spaces): mitigate eventual race conditions when updating the pagination state (part #2) 2025-08-29 18:35:27 +03:00
Stefan Ceriu ea5063ca84 fix(spaces): address potential race when setting up the room updates listener 2025-08-29 18:35:27 +03:00
Stefan Ceriu dcc07e1049 chore(spaces): acquire and retain an async lock on the pagination token for the duration of the request to futher prevent inconsistencies 2025-08-29 18:35:27 +03:00
Stefan Ceriu 76a0eb1599 fix(spaces): mitigate eventual race conditions when updating the pagination state 2025-08-29 18:35:27 +03:00
Stefan Ceriu a9c16c96e0 chore(spaces): cleanup clone names in room updates listener 2025-08-29 18:35:27 +03:00
Stefan Ceriu 93f8ebba27 chore(spaces): simplify the SpaceGraph interfaces
Fix graph reference crap
2025-08-29 18:35:27 +03:00
Stefan Ceriu 95bb153269 chore(spaces): improve how space graph edge additions work 2025-08-29 18:35:27 +03:00
Stefan Ceriu ff72a09870 chore(spaces): fix typo 2025-08-29 18:35:27 +03:00
Stefan Ceriu 06de58dee9 chore(spaces): switch some flat_maps to filter_map 2025-08-29 18:35:27 +03:00
Stefan Ceriu fbb49e9b65 chore(spaces): simplify the SpaceGraph interfaces 2025-08-29 18:35:27 +03:00
Stefan Ceriu 04728cc1a6 chore(spaces): various documentation fixes 2025-08-29 18:35:27 +03:00
Stefan Ceriu d43d141dc8 chore(spaces): use Client::joined_space_rooms within the space service to reduce the number of iterations required 2025-08-29 18:35:27 +03:00
Stefan Ceriu 3c069f0c5c fix(spaces): compute the initial joined_spaces value when first setting up a subscription
- fixes values being reported only after the first sync update
2025-08-29 18:35:27 +03:00
Stefan Ceriu a2200b6324 chore(spaces): switch from manually dropping JoinHandles to AbortOnDrop 2025-08-29 18:35:27 +03:00
Stefan Ceriu 9caa0817ae docs(spaces): add documentation, comments and examples 2025-08-29 18:35:27 +03:00
Stefan Ceriu b3229041fb chore(spaces): ignore room list change updates if empty 2025-08-29 18:35:27 +03:00
Stefan Ceriu 50446377de change(spaces): publish VectorDiffs instead of a full vectors for joined spaces and space room list subscriptions 2025-08-29 18:35:27 +03:00
Stefan Ceriu 4f02a6d3be chore(spaces): add changelog 2025-08-29 18:35:27 +03:00
Stefan Ceriu 87fdd3c3bf chore(spaces): converge on single naming scheme for all spaces related components on both the UI and the FFI crates 2025-08-29 18:35:27 +03:00
Stefan Ceriu 990fe86fdc change(spaces): make the SpaceService constructor non-async and instead automatically setup a client subscription when requesting the joined services subscription 2025-08-29 18:35:27 +03:00
Stefan Ceriu be2ba26974 fix(spaces): filter out the current parent space from the /hierarchy responses and SpaceServiceRoomList instances 2025-08-29 18:35:27 +03:00
Stefan Ceriu 1392a0e637 change(spaces): put a limit of 1 on the max depth of the /hierarchy calls so only the direct children are fetche 2025-08-29 18:35:27 +03:00
Stefan Ceriu 03ffa4c9a4 feat(spaces): expose the number of children each space room has 2025-08-29 18:35:27 +03:00
Stefan Ceriu f8b5992101 fix(spaces): return the TaskHandle from the FFI space service subscription methods so it can be retained on the client side 2025-08-29 18:35:27 +03:00
Stefan Ceriu 97a5fbebfb feat(ffi): expose SpaceService::subscribe_to_joined_spaces and SpaceServiceRoomList::paginate 2025-08-29 18:35:27 +03:00
Stefan Ceriu 74c2032974 chore(spaces): build a graph from joined spaces parent and child relations to correctly detect all the edges and be able to remove any cycles.
- cycle removing is done through DFS and keeping a list of visited nodes
2025-08-29 18:35:27 +03:00
Stefan Ceriu 274aaf5ba3 change(room_list): request both m.space.parent and m.space.child state events in the sliding sync required state as they're both required to build a full view of the space room hierarchy 2025-08-29 18:35:27 +03:00
Stefan Ceriu 3e72cce7a0 fix(spaces): use wasm compatible executor spawn and JoinHandle 2025-08-29 18:35:27 +03:00
Stefan Ceriu aa4b176ab3 fix(spaces): fix complement-crypto failures because of using an outdated uniffi version
- automatic Arc inference was introduced in 0.27 and complement is using 0.25
2025-08-29 18:35:27 +03:00
Stefan Ceriu ad2f4c731a feat(spaces): have the SpaceRoomList publish updates as known room states change i.e. they get joined or left. 2025-08-29 18:35:27 +03:00
Stefan Ceriu f78015fae1 change(spaces): return only top level joined rooms from SpaceService::joined_spaces and its reactive counterpart 2025-08-29 18:35:27 +03:00
Stefan Ceriu 211a1f5a40 feat(spaces): add a reactive version of the joined_spaces method 2025-08-29 18:35:27 +03:00
Stefan Ceriu b8be1fdb26 feat(spaces): introduce a SpaceRoomList that allows pagination and provides reactive interfaces to its rooms and pagination state 2025-08-29 18:35:27 +03:00
Stefan Ceriu a43e42c170 chore(spaces): introduce a SpaceServiceRoom 2025-08-29 18:35:27 +03:00
Stefan Ceriu f031eaf96b chore(spaces): setup a simple space service and some unit tests 2025-08-29 18:35:27 +03:00
Benjamin Bouvier 3ba31d1e97 tests: clarify that the other thread subscription endpoints are grouped by room 2025-08-29 11:28:29 +02:00
Benjamin Bouvier bbf8f9f900 feat(sdk): add support for msc4308 accompanying endpoint (fetching thread subscriptions) 2025-08-29 11:28:29 +02:00
Benjamin Bouvier 49dc2bb640 chore: bump Ruma
We get test fixes for free, thanks to the new push rules semantics
implemented in Ruma \o/
2025-08-29 11:28:29 +02:00
Skye Elliot 99af951d7a feat(crypto): Add EncryptionSettings::encrypt_state_events
This will be used inside the WASM SDK to introduce a similar field to
its EncryptionSettings struct.

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-28 14:00:23 +02:00
Ivan Enderlin a17bf18ff2 chore(sdk): Improve a log message. 2025-08-28 12:58:19 +02:00
Ivan Enderlin 5d87570a33 doc(sdk,base): Fix outdated documentation and typos. 2025-08-28 12:58:19 +02:00
Ivan Enderlin 80806303b5 feat(sdk): The LatestEventValue is stored in RoomInfo and persisted.
This patch updates `LatestEvent::update` to call the new
`LatestEvent::store` method, which will store the new `LatestEventValue`
in the `RoomInfo` struct, and will persist it in the `StateStore`.

This patch also adds the test for this new feature.
2025-08-28 12:58:19 +02:00
Ivan Enderlin 6155772bb1 feat(base): Add RoomInfo::new_latest_event.
This patch adds the new `new_latest_event: LatestEventValue` field in
`RoomInfo`. The `latest_event` is kept for the moment, but it will be
removed once the new API has landed entirely.
2025-08-28 12:58:19 +02:00
Ivan Enderlin 33db267a89 test(base): test_cached_latest_event_can_be_redacted runs only if e2e-encryption is enabled.
This patch puts `test_cached_latest_event_can_be_redacted` as it runs
only if `e2e-encryption` is turned on.
2025-08-28 12:58:19 +02:00
Ivan Enderlin 6fc68dac83 refactor(sdk,base): Move LatestEventValue into matrix_sdk_base.
This patch moves `LatestEventValue` into the
`matrix_sdk_base::latest_event` module. If we want to store this value
in `RoomInfo`, it must be in this crate.

Because it's not allowed to `impl T` where `T` lives in a different
crate, this patch changes the `impl LatestEventValue` to `struct
LatestEventValueBuilder` + `impl LatestEventValueBuilder`. Luckily, all
methods on `LatestEventValue` are only constructors, so the change is
super straightforward.
2025-08-28 12:58:19 +02:00
Ivan Enderlin f3eeb82b0b refactor(sdk): LatestEvent::_room_id becomes _weak_room: WeakRoom.
This patch replaces `OwnedRoomId` by `WeakRoom` in `LatestEvent`. Apart
from simplifying a couple of method' signatures, it also opens the road
for storing the `LatestEventValue` in `RoomInfo`.
2025-08-28 12:58:19 +02:00
Richard van der Hoff 951d22ac24 common: js_tracing: drop TRACE logs
Now that (since https://github.com/matrix-org/matrix-js-sdk/pull/4918) Element
Web uses separate subscribers for each OlmMachine, rather than a single global
one with a separate LevelFilter, EW's logs are very verbose because they
receive all the TRACE logs.

Dropping the TRACE logs on the floor isn't my favourite solution, but
everything else seems to be a bit harder than I have time for right
now:

* Sending TRACE logs up to the JS side in case it wants to print them would (a)
  increase overhead and (b) be an annoying breaking change in JsLogger

* Ideally we'd let the application configure its logging more precisely via an
  `EnvFilter` or something, but I'm not really sure what the API would look like
  for that.

So for now, we take the easy path.
2025-08-28 11:55:04 +01:00
Damir Jelić 527d001010 fix: Only report duplicate one-time key errors once
Since the server will reject any duplicate one-time keys forever,
clients which encounter such an error will spam sentry with such
reports.

This patch ensures that we only send the sentry report once.
2025-08-28 12:48:30 +02:00
Stefan Ceriu 759eeeb27f feat(test): add event factory methods for creating space rooms and populating parent-children relationships. 2025-08-28 10:55:00 +03:00
Stefan Ceriu 97d6f57aee feat(base): add SyncResponse::RoomUpdates::is_empty method to check if there were any room updates 2025-08-28 10:45:02 +03:00
Stefan Ceriu 6622a3ac93 fix(room): fix event types in matrix_sdk::Room::parent_spaces method comments 2025-08-28 09:37:07 +02:00
Stefan Ceriu 39730173d4 chore(ffi): expose the SyncService.expire_sessions so client can expire Sliding Sync positions on demand
This is useful when changing the required sliding sync state in between position resets which Synapse doesn't handle well at the moment as per https://github.com/element-hq/synapse/issues/18844
2025-08-28 10:32:32 +03:00
Stefan Ceriu 763314645b feat(sdk): add a Client::joined_space_rooms method that allows retrieving the list of joined spaces. 2025-08-28 09:28:04 +02:00
Ivan Enderlin b2fee72d79 refactor(sdk): Revisit the assert_latest_event_content macro.
This patch revisits the `assert_latest_event_content` macro to not take
a `true` or `false` value. It feels a bit weird to read. Instead, `with
|factory| { … }, true` becomes `event |factory| { … } is a candidate`.
Same for the `false`case which becomes `is not a candidate`. No more
comma, it feels a bit more like a sentence.
2025-08-27 16:45:48 +02:00
Ivan Enderlin 9803d2bcca refactor(sdk): Use SerializableEventContent.
This patch replaces `LocalLatestEventValue::content` and `…::event_type`
fields by using the existing `SerializableEventContent`. It does exactly
the same thing.
2025-08-27 16:45:48 +02:00
Ivan Enderlin 296867d2ac feat(sdk): LatestEventValue implements Serialize and Deserialize.
This patch implements `Serialize` and `Deserialize` on
`LatestEventValue`.
2025-08-27 16:45:48 +02:00
Ivan Enderlin 710b57e035 refactor(sdk): Remove LatestEventContent.
The problem is: `LatestEventContent` cannot be serialized. It's annoying
because it means we can't store a `LatestEventValue` (that wraps a
`LatestEventContent`) in the database.

This patch revisits `LatestEventValue`. Before we got:

```rust
pub enum LatestEventValue {
     None,
     Remote(LatestEventContent),
     LocalIsSending(LatestEventContent),
     LocalCannotBeSent(LatestEventContent),
}

pub enum LatestEventContent {
    RoomMessage(RoomMessageEventContent),
    Sticker(StickerEventContent),
    Poll(UnstablePollStartEventContent),
    CallInvite(CallInviteEventContent),
    CallNotify(CallNotifyEventContent),
    KnockedStateEvent(RoomMemberEventContent),
    Redacted(AnySyncMessageLikeEvent),
}
```

`LatestEventContent::Redacted` contains an `AnySyncMessageLikeEvent`.
That's the part that is not serializable.

It appears that `LatestEventContent` isn't necessary! The only thing we
need is to _filter_ the events by their type, no need to _find and
map_. The `LatestEventValue` can contain the entry event directly (e.g.
a `TimelineEvent` for the event cache). Okay, let's do that.

```rust
pub enum LatestEventValue {
    None,
    Remote(RemoteLatestEventValue),
    LocalIsSending(???),
    LocalCannotBeSent(???),
}

type RemoteLatestEventValue = TimelineEvent;
```

What about the `Local*` variants? We can't use a `TimelineEvent`. We
need a new type for that:

```rust
pub enum LatestEventValue {
    None,
    Remote(RemoteLatestEventValue),
    LocalIsSending(LocalLatestEventValue),
    LocalCannotBeSent(LocalLatestEventValue),
}

pub struct LocalLatestEventValue {
    pub timestamp: MilliSecondsSinceUnixEpoch,
    pub content: Raw<AnyMessageLikeEventContent>,
    pub event_type: String,
}
```

We don't need the event ID nor the transaction ID in
`LocalLatestEventValue`.

That's the only change. All the other changes are about the tests.
2025-08-27 16:45:48 +02:00
Skye Elliot baa75368d6 ci: Add feature matrix for integration testing
This will resolve a number of transitive dependency issues when testing
crates that do not enable the `experimental-encrypted-state-events` feature
flag by default.

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-27 14:55:45 +02:00
Damir Jelić feb264e899 test: Add a test to check that we don't create event cache reference cycles 2025-08-27 13:03:44 +02:00
Skye Elliot 8e5075569e feat: Add top-level support for decrypting state events (#5552)
Implements support for decryption of state events

- [ ] Introduce a case for `AnySyncStateEvent::RoomEncrypted` to the
`state_events` sync response processor.
- [ ] Introduce modified `Room::decrypt_event` and
`::try_decrypt_room_event`.
- [ ] Introduce testing macro
`assert_let_decrypted_state_event_content`.
- [ ] Add casts and explicit type hints where necessary.

---------

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-27 10:53:55 +01:00
Michael Goldenberg 33c11d08f0 test(indexeddb): add tests for media retention policy related fns
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Michael Goldenberg 9714ac8e10 refactor(indexeddb): add IndexedDB-backed impl for media retention policy fns
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Michael Goldenberg e1d136aa6e refactor(indexeddb): add indexed type to represent media retention policy
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Michael Goldenberg 8018753332 refactor(indexeddb): add primary key to core object store in event cache database
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Michael Goldenberg 61824f866c refactor(indexeddb): delegate media-related queries via media service to EventCacheStoreMedia implementation
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Michael Goldenberg 6919444e98 feat(indexeddb): add MemoryStore-backed impl of EventCacheStoreMedia
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Michael Goldenberg c5097cf07e refactor(indexeddb): remove macros for implementing EventCacheStore
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Michael Goldenberg b77c6c65cc feat(indexeddb): derive Clone for IndexeddbEventCacheStore
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-27 09:56:50 +02:00
Benjamin Bouvier f4ce4356ab refactor(event cache): only process threaded linked chunks if thread support has been globally enabled 2025-08-26 16:25:56 +02:00
Benjamin Bouvier d66733052a feat(event cache): add indexes for finding related events 2025-08-26 16:25:56 +02:00
Benjamin Bouvier 001dadffe1 bench: add a benchmark for finding related events (#5578)
Does what it says on the tin. Split from the performance fix, so we can
get some initial numbers on the CI bench runs too.

Part of investigating
https://github.com/matrix-org/matrix-rust-sdk/issues/5572
2025-08-26 15:57:06 +02:00
Shrey Patel b2387bf3a9 test(search): Add tests for RoomIndex::contains and indexing idempotency 2025-08-26 13:25:49 +02:00
Shrey Patel d43858ecb2 fix(search): Make indexing idempotent 2025-08-26 13:25:49 +02:00
dependabot[bot] 8804966094 chore(deps): bump actions/setup-java from 4 to 5
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 4 to 5.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-26 10:04:28 +02:00
dependabot[bot] a3ee011b61 chore(deps): bump crate-ci/typos from 1.35.4 to 1.35.5
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.35.4 to 1.35.5.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.35.4...v1.35.5)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.35.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-26 10:04:06 +02:00
dependabot[bot] f586172f3e chore(deps): bump actions/upload-pages-artifact from 3 to 4
Bumps [actions/upload-pages-artifact](https://github.com/actions/upload-pages-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/upload-pages-artifact/releases)
- [Commits](https://github.com/actions/upload-pages-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/upload-pages-artifact
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-26 10:03:51 +02:00
Jorge Martín 85d52586b6 fix(media): Use the right Option<Duration> value to get no timeout 2025-08-25 13:50:53 +02:00
Benjamin Bouvier 40d3dd57db tests(threads): add an exhaustive test to check for all notification mode combinations 2025-08-25 10:09:55 +02:00
Skye Elliot 4e2655aa1b feat(sdk): Use clearer fields for Span in SendRawStateEvent 2025-08-22 14:27:05 +01:00
Skye Elliot 41fcebbcb0 chore(sdk): Move ensure_room_encryption_ready to end of file 2025-08-22 14:27:05 +01:00
Skye Elliot 13b86a3f5d tests: Add test_room_encrypted_state_event_send 2025-08-22 14:27:05 +01:00
Skye Elliot dba23b66fa feat(sdk): Use SendStateEvent future in Room send_state methods
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-22 14:27:05 +01:00
Skye Elliot 132d0eb34a feat(sdk): Add SendStateEvent future
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-22 14:27:05 +01:00
Skye Elliot e2e70448ca feat(sdk): Modify Room::send_state_event_raw to return SendRawStateEvent
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-22 14:27:05 +01:00
Skye Elliot adaccbab2c feat(sdk): Add SendRawStateEvent future and deduplicate
Deduplicates common code that would be shared between
SendRawMessageLikeEvent and SendRawStateEvent to a helper method,
`ensure_room_encryption_ready`.

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-22 14:27:05 +01:00
Richard van der Hoff 7a09ca0bbd Merge pull request #5545 from matrix-org/kaylendog/msc3414/json-castable
feat(sdk): Support room key downloading using `JsonCastable<EncryptedEvent>`
2025-08-21 18:59:23 +01:00
Richard van der Hoff fffdd34ebd Merge pull request #5559 from matrix-org/kaylendog/encrypt-poll-sync
This fixes a small issue encountered while developing the integration test for encrypted state events. If the first sync response received from the server after enabling encryption does not contain the m.room.encryption event, the client will report the encryption state as unknown, even if the next sync response does contain the event.

 - [x] Modify Room::enable_encryption_inner to spin on the room encryption state, rather than bailing after the first sync response is received.

Signed-off-by: Skye Elliot
2025-08-21 17:07:22 +01:00
Skye Elliot 24502d2706 fix(sdk): Check correct encryption state for encrypted state events 2025-08-21 15:43:35 +01:00
dragonfly1033 b6433dea27 refactor(sdk): Move index handling to EventCache and use linked_chunk_update_sender.
Remove previous code that got updates in `RoomEventCacheState::post_process_new_events`.
Add new task in `EventCache` that subscribes to `linked_chunk_update_sender` and forwards new events to `client::search::SearchIndex` same as before.

Signed-off-by: Shrey Patel shreyp@element.io
2025-08-21 14:17:45 +00:00
dragonfly1033 385f1a824f feat(multiverse): Add search feature to multiverse 2025-08-21 14:50:11 +01:00
dragonfly1033 dfc0ef8b35 refactor(multiverse): Create generic PopupInput widget 2025-08-21 14:50:11 +01:00
Benjamin Bouvier d2feeaac30 refactor(sdk): avoid an explicit dependency on ruma-common
The `ruma-common` crate is reexported by `ruma`, which is in our
dependency tree anyways. This change makes it so that qrcode, the only
crate that was making use of `ruma-common`, now depends on `ruma`. It
may move it further down the line in the compilation pipeline, but this
is unlikely to affect compile times in a crazy way. The benefit is that
this avoids the burden of having to specify the ruma commit hash twice
in the top-level Cargo.toml, as well as replacing it twice when
overriding it.
2025-08-21 15:42:25 +02:00
Benjamin Bouvier 25a81876a0 tests: allow conversion from EventBuilder into Raw<AnyGlobalAccountDataEvent>
This avoids a few explicit `.into_raw()` calls here and there.
2025-08-21 15:21:14 +02:00
Benjamin Bouvier e388fe6522 tests: streamline the SyncResponseBuilder global account methods
Only keep two: the one that uses the output of the event factory, and
one using custom JSON data.
2025-08-21 15:21:14 +02:00
Benjamin Bouvier ef20342ddf tests: use the new global account data methods a bit more 2025-08-21 15:21:14 +02:00
Benjamin Bouvier e6b1ffba99 tests: add support for the global account PushRules event in the event factory 2025-08-21 15:21:14 +02:00
Benjamin Bouvier 9a3ceb8be6 tests: add support for the global account IgnoredUserList event in the event factory 2025-08-21 15:21:14 +02:00
Benjamin Bouvier faee647c3a tests: get rid of GlobalAccountDataTestEvent::Direct 2025-08-21 15:21:14 +02:00
Benjamin Bouvier 1866143456 tests: add support for the global account Direct event in the event factory 2025-08-21 15:21:14 +02:00
Benjamin Bouvier be8e322ad6 doc(sdk): add comments around the NotificationSettings data structure 2025-08-21 15:21:14 +02:00
Benjamin Bouvier 838f607b32 refactor(benchmark): slightly change the benchmark to make it not use iter_custom
Instead of creating a fresh client every single time, this creates a
single client with a single event cache store, that's cleared between
runs of the benchmark.

So the tradeoff is:
- we don't have to create a new client anymore, which means no more
async setup code, which means we can avoid using `iter_custom`; a
benefit of this is that this can be benchmarked on CI now.
- but we're also measuring the time it takes to clear the database,
which isn't trivial in itself.
2025-08-21 15:19:26 +02:00
Benjamin Bouvier 6965004812 fix(benchmark): make the event cache benchmark compute what it's supposed to 2025-08-21 15:19:26 +02:00
Benjamin Bouvier 8ec23a95d5 fix(event cache): avoid cycle of EventCacheInner with the auto_shrink_linked_chunk_task
The task would stop when the receiver is closed; for the receiver to be
closed, the sender ought to be closed too.

Because the sender lives in `EventCacheInner`, and the task would hold
onto an `EventCacheInner` struct, the sender would never be dropped, so
the full `EventCacheInner` would leak, as a result.
2025-08-21 15:19:26 +02:00
Skye Elliot 7880ec5b01 fix(sdk): Return from poll when encryption state known
Fixes Room::enable_encryption_inner to break out of polling the
encryption state when it becomes known, rather than just encrypted.
2025-08-20 13:56:05 +01:00
Skye Elliot 36428564fc feat(sdk): Poll encryption state on sync event for up to 3 seconds. 2025-08-20 12:45:04 +01:00
Skye Elliot 7adaf7be73 feat(sdk): Rename state encryption methods for improved clarity
Changes `Room::enable_encryption_with_state` to
`Room::enable_encryption_with_encrypted_state_events`, and updates the
respective unit test and testing utilities.

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-20 12:28:03 +02:00
Skye Elliot 7920723bb4 docs(sdk): Update CHANGELOG.md
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-20 12:28:03 +02:00
Skye Elliot b73163aa45 feat(sdk): Add Room::enable_encryption_with_state
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-20 12:28:03 +02:00
Ivan Enderlin feeeb53f19 refactor(sdk): Simplify Client::(joined|invited|left)_rooms.
This patch updates `Client::joined_rooms`, `invited_rooms` and
`left_rooms` to re-use `Client::rooms_filtered`.
2025-08-20 11:27:03 +02:00
Ivan Enderlin 1ac876db98 doc(sdk): Rephrase a couple of comments. 2025-08-20 08:37:27 +02:00
Ivan Enderlin afaf2cc036 test(sdk): Test that local latest event values has priority over remote's.
This patch moves the `test_update_ignores_none_value`
test in a new (correct) test module, and creates the new
`test_local_has_priority_over_remote` test.
2025-08-20 08:37:27 +02:00
Ivan Enderlin 5a3bb0a86d feat(sdk): Ensure the send queue has the priority over the event cache for computing a LatestEventValue. 2025-08-20 08:37:27 +02:00
Ivan Enderlin 2640aa1e23 fix(sdk): Compute the LatestEventValue on SentEvent before removing it from the buffer.
This patch changes the order in which the `LatestEventValue` is removed
from the buffer and re-created in case of a `SentEvent`. Previously,
the value from the buffer was removed before re-creating one, now it's
the opposite.

Why this order? Because once the local event is sent, it's not yet
received by the sync and consequently not stored in the event cache. So
once the local event is sent, it won't show up as a `LatestEventValue`
as it will immediately be replaced by an event from the event cache. By
computing the new value before removing it from the buffer, we ensure
the `LatestEventValue` represents the just sent local event.

See the comment in the code to learn more.
2025-08-20 08:37:27 +02:00
Ivan Enderlin d1a8392ce7 refactor(sdk): Rename LocalIsWedged to LocalCannotBeSent.
This patch renames `LocalIsWedged` to `LocalCannotBeSent` to avoid
confusion with the wedged/unwedged state of the `send_queue`. The
semantics is different in `latest_events`.
2025-08-19 16:35:41 +02:00
Ivan Enderlin 4d14dd3692 doc(sdk): Add a TODO marker for later. 2025-08-19 16:35:41 +02:00
Ivan Enderlin 63defca8af chore(sdk): Add mark_ prefix. 2025-08-19 16:35:41 +02:00
Ivan Enderlin fd83904b4d feat(sdk): Handle replacing a local event by a non-suitable latest event value.
This patch handles the case where a local event is replaced by another
local event which isn't suitable for being a latest event value. In this
case, the previous existing latest event value should be removed from
the buffer.
2025-08-19 16:35:41 +02:00
Ivan Enderlin 9254c38a8d chore(sdk): Log all deserialize errors in latest_events. 2025-08-19 16:35:41 +02:00
Ivan Enderlin 63d9dd5c6e refactor(sdk): Rename find_and_map_any_message… to extract_content_from_any_message_like. 2025-08-19 16:35:41 +02:00
Ivan Enderlin 23dacc329e refactor(sdk): Rename LatestEventKind to LatestEventContent. 2025-08-19 16:35:41 +02:00
Ivan Enderlin 5896a438f5 chore(sdk): Change error! to warn! when channels have been closed.
This patch reduces the level of logs when channels have been closed in
`LatestEvents`' tasks from `error` to `warn`. Indeed, when the `Client`
shutdowns, the channels will be closed, but it's not an error at all.
2025-08-19 16:35:41 +02:00
Ivan Enderlin 31a3d76436 feat(sdk): Introduce LatestEventKind::Redacted.
This patch introduces `LatestEventKind::Redacted` to handle the case
where an event is supposed to be a latest event but has been redacted.
2025-08-19 16:35:41 +02:00
Ivan Enderlin dfaaf323ad test(sdk): Test that a None latest event value is ignored. 2025-08-19 16:35:41 +02:00
Ivan Enderlin 94439d8913 test(sdk): Write tests for LatestEvent and SendQueue. 2025-08-19 16:35:41 +02:00
Ivan Enderlin 9cc29d7c65 feat(sdk): Implement LatestEvent::update_with_send_queue.
This patch implements `LatestEvent::update_with_send_queue`.
It introduces an intermediate type, for the sake of clarity,
`LatestEventValuesForLocalEvents`.

The difficulty here is to keep a buffer of `LatestEventValue`s requested
by the `SendQueue`. Why? Because we want the latest event value, but we
only receive `RoomSendQueueUpdate`s, we can't iterate over local events
in the `SendQueue` like we do for the `EventCache` to re-compute the
latest event if a local event has been cancelled or updated.

A particular care must also be applied when a local event is wedged:
this local event and all its followings must be marked as wedged too,
so that the `LatestEventValue` is `LocalIsWedged`. Same when the local
event is unwedged.
2025-08-19 16:35:41 +02:00
Ivan Enderlin f2fbdfbac2 chore(sdk): Rename and split a couple of types in latest_event.
This patch splits the `LatestEventValue` type into `LatestEventValue`
+ `LatestEventKind`. Basically, all variants in `LatestEventValue` are
moved inside the new `LatestEventKind` enum. `LatestEventValue` keeps
`None`, and see the new `Remote`, `LocalIsSending` and `LocalIsWedged`
variants.

This patch also extracts the message-like handling of `find_and_map`
(now renamed `find_and_map_timeline_event`) into its own function:
`find_and_map_any_message_like_event_content`. This is going to be
handful for the send queue part.
2025-08-19 16:35:41 +02:00
Ivan Enderlin fd34927f61 feat(sdk): compute_latest_events broadcasts the update to LatestEvent.
This patch updates `compute_latest_events` to broadcast a
`RoomSendQueueUpdate` onto `LatestEvent`. It introduces the new
`update_with_send_queue` method.
2025-08-19 16:35:41 +02:00
Ivan Enderlin 0190d3556d chore(sdk): Rename update to update_with_event_cache in latest_events.
This patch renames the `update` methods to `update_with_event_cache`
in the `latest_events` module. It frees the road to introduce
`update_with_send_queue`.
2025-08-19 16:35:41 +02:00
Ivan Enderlin 2d657fe908 feat(sdk): LatestEvents listens to the SendQueue.
This patch updates `LatestEvents` to listen to the updates from the
`SendQueue`. The `listen_to_event_cache_and_send_queue_updates` function
contains the important change. A new `LatestEventQueueUpdate` enum is
added to represent either an update from the event cache, or from the
send queue.

So far, `compute_latest_events` does nothing in particular, apart from
panicking with a `todo!()` when a send queue update is met.
2025-08-19 16:35:41 +02:00
Ivan Enderlin 5e43177d3a chore(sdk): Simplify code in listen_to_event_cache_and_send_queue_updates_task.
This patch removes the intermediate `rooms` variable in a new block. The
read-lock can be used immediately.
2025-08-19 16:35:41 +02:00
Skye Elliot e44b01cbe5 feat(sdk): Support room key downloading using JsonCastable<EncryptedEvent>
Allows `Backups::maybe_download_room_key` to accept any T:
JsonCastable<EncryptedEvent>, which will be required for state events to
trigger fetching the room key.

Implements JsonCastable<EncryptedEvent> for
OriginalSyncStateRoomEncryptedEventContent.

Implements JsonCastable<AnyStateEvent> for RoomEncryptedEventContent.
2025-08-19 14:47:44 +01:00
Michael Goldenberg 4882c98f99 refactor(indexeddb): allow IndexeddbSerializer::hash_key to be unused until event cache store is a default feature
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 4bf0187310 style(indexeddb): format event cache store impl by temporarily removing enclosing macro
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 10ca400d4d docs(indexeddb): correct key docs to express that keys are hashed, not encrypted
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg cc61e123b7 docs(indexeddb): remove references to room where relevant in transaction docs
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 6f23981268 refactor(indexeddb): log linked chunk id rather than room id in handle_linked_chunk_updates
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 859044285a test(indexeddb): use event cache store integration tests from matrix_sdk_base
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 6c1134006e fix(indexeddb): integrate linked chunk id into relevant chunk- and gap-related types and fns
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 6d1cdbc613 fix(indexeddb): integrate linked chunk id into relevant event-related types and fns
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 6160c15103 refactor(indexeddb): re-organize type synonyms in event_cache_store::serializer
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 100cbde526 refactor(indexeddb): use room-based queries in event-related fns that don't use linked chunk ids
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 6ff8a26cca refactor(indexeddb): add room-based index to event object store in preparation for linked chunk id as primary key
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg a1c484fb6e refactor(indexeddb): expose hash_key fn in serializer for keys represented as bytes rather than strings
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg d2ecc77014 feat(linked chunk): derive ser/de traits for OwnedLinkedChunkId
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 2e86fbc234 feat(linked chunk): add display impl for LinkedChunkId
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg 64698eaf1a feat(linked chunk): add trait-based conversions between owned and borrowed linked chunk id
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Michael Goldenberg f180a14c88 feat(linked chunk): expose OwnedLinkedChunkId::as_ref for use in other crates
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-19 14:46:05 +02:00
Benjamin Bouvier bb0d480f24 fix(ci): clean more space in the CI runner for the codecov space
An idea courtesy from the gentle folks at apache/arrow.
2025-08-19 14:25:13 +02:00
Richard van der Hoff 7af1d3ab0e Merge pull request #5539 from matrix-org/kaylendog/msc3414/crypto
feat(crypto): Add support for encrypted state events to `matrix-sdk-crypto`
2025-08-19 10:55:38 +01:00
Skye Elliot 13ee4c8098 tests(crypto): Document introduced tests and helper
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-19 10:17:14 +01:00
dependabot[bot] 7bbd02ca73 chore(deps): bump actions/checkout from 4 to 5
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-19 10:33:03 +02:00
dependabot[bot] e22a7a2ed5 chore(deps): bump bnjbvr/cargo-machete from 0.8.0 to 0.9.1
Bumps [bnjbvr/cargo-machete](https://github.com/bnjbvr/cargo-machete) from 0.8.0 to 0.9.1.
- [Release notes](https://github.com/bnjbvr/cargo-machete/releases)
- [Changelog](https://github.com/bnjbvr/cargo-machete/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bnjbvr/cargo-machete/compare/v0.8.0...v0.9.1)

---
updated-dependencies:
- dependency-name: bnjbvr/cargo-machete
  dependency-version: 0.9.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-19 10:16:04 +02:00
dependabot[bot] 4aad2c6b07 chore(deps): bump crate-ci/typos from 1.35.0 to 1.35.4
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.35.0 to 1.35.4.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.35.0...v1.35.4)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.35.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-19 10:14:26 +02:00
Skye Elliot 960162453c feat(base): Add EncryptionState::StateEncrypted
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-18 17:46:46 +02:00
Benjamin Bouvier 1ea2162012 chore(ci): add a search feature to try out the experimental-search branch in CI 2025-08-18 17:33:34 +02:00
Benjamin Bouvier 1f0151705a fix(search): make the experimental-search feature compile
And simplify the code for parsing in the event cache.
2025-08-18 17:33:34 +02:00
Skye Elliot 84ebbd913c feat: Add naive state key verification to OlmMachine
Modifies `OlmMachine::decrypt_room_event_inner` to call a new method
`OlmMachine::verify_packed_state_key` which, if the event is a state
event, verifies that the original event's state key, when unpacked,
matches the state key and event type in the decrypted event content.

Introduces MegolmError::StateKeyVerificationFailed and
UnableToDecryptReason::StateKeyVerificationFailed which are thrown when
the verification fails.

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-18 15:56:48 +01:00
Skye Elliot 756d50737e feat(crypto): Add state event encryption methods to OlmMachine
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-18 15:56:45 +01:00
Skye Elliot c32877284c feat(crypto): Add GroupSessionManager::encrypt_state
Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-18 15:56:44 +01:00
Skye Elliot 6260811ea5 feat(crypto): Add OutboundGroupSession::encrypt_state
This commit also refactors out what would be common code between
::encrypt and ::encrypt_state to a helper ::encrypt_inner.

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
2025-08-18 15:56:38 +01:00
dragonfly1033 4f0415d4d2 add .envrc to .gitignore
Signed-off-by: dragonfly1033 <42915850+dragonfly1033@users.noreply.github.com>
2025-08-18 15:20:31 +02:00
Benjamin Bouvier b43aac129b chore: address review comments 2025-08-18 15:10:50 +02:00
Benjamin Bouvier c019009d00 refactor(event cache): avoid deserializing the full event content to be sent, for extracting its thread root 2025-08-18 15:10:50 +02:00
Benjamin Bouvier a88d6b37dc feat(event cache): also subscribe to a thread if we've sent a message into it 2025-08-18 15:10:50 +02:00
Benjamin Bouvier 705d6f870e refactor(event cache): move the listening to linked chunk updates to its own function, and introduce a select! at the top level 2025-08-18 15:10:50 +02:00
Benjamin Bouvier 4fc28c4701 feat(multiverse): enable threading support for multiverse with subscriptions 2025-08-18 15:10:50 +02:00
Benjamin Bouvier 64eecd0aee test(event cache): add tests for automatic thread subscriptions 2025-08-18 15:10:50 +02:00
Benjamin Bouvier c25be8b070 feat(event cache): automatically subscribe to threads according to msc4306 semantics 2025-08-18 15:10:50 +02:00
Benjamin Bouvier 1554c9d8fa feat(room): add a new function that will only subscribe to a thread if needed 2025-08-18 15:10:50 +02:00
Benjamin Bouvier d568c07489 feat(event cache): add a way to subscribe to any room's linked chunk updates 2025-08-18 15:10:50 +02:00
dragonfly1033 13c30f6691 feat(sdk): Add creation of indexes and indexing of messages (#5505)
Integrate matrix-sdk-search into matrix-sdk.
When a room is joined, a corresponding index is created.
When a message is received via sync or via a back-pagination, it is
added to the corresponding room's index.

Signed-off-by: Shrey Patel shreyp@element.io
2025-08-18 14:52:09 +02:00
Benjamin Bouvier 0e70a2fdfb test(sdk): add a regression test for the thread relation forwarding for poll start events
This got fixed in Ruma, and the Ruma's bump in the parent commit
includes this fix.
2025-08-18 13:04:35 +02:00
Benjamin Bouvier d70d758861 chore: bump Ruma 2025-08-18 13:04:35 +02:00
fkwp eefa9ff556 added comments including reference to MSCs 2025-08-15 15:58:28 +01:00
fkwp 28a8603f42 Allow new state key string-packing format for widget mode 2025-08-15 15:58:28 +01:00
Skye Elliot ae7f0fe022 feat: Experimental encrypted state feature flag with CI support (#5537)
This PR makes some non-domain-specific changes across multiple crates
that are required for proper testing of features implemented for #5397.

* Adds a `experimental-encrypted-state-events` feature flag across the
SDK.
* Introduces a feature set into xtask to ensure feature-gated tests are
run during CI.
* Minor fix to a test that would otherwise fail with the newly
introduced CI.
2025-08-15 12:54:41 +00:00
Skye Elliot d9f4e7c426 Merge pull request #5511 from kaylendog/kaylendog/room-settings
feat(crypto): Add RoomSettings::encrypt_state_events
2025-08-14 15:51:19 +01:00
Benjamin Bouvier 247ec1dcd2 refactor(event cache): shorten the name of room_event_cache_generic_update
We're in the inner workings of the event cache, so the prefix is
redundant, in the ambient context.
2025-08-14 13:05:57 +02:00
Benjamin Bouvier 558d7b56f9 refactor(event cache): get rid of RoomEventCacheGenericUpdate::Clear
The semantics of this variant are unclear: sometimes a timeline could be
cleared, which would result in a `UpdateTimeline` (and if we looked at
the vector diffs, it would include a `Clear`), but in this case the
`Clear` variant would not be emitted.

It was only emitted in a few adhoc spots, but it was missing the whole
picture. Also, the current observer was only interested in getting *a*
room update with the room id, and didn't react particularly to clears.
So, there's apparently little reason in having this variant, and as a
result we should get rid of it.
2025-08-14 13:05:57 +02:00
dragonfly1033 1201be484a fix!(sdk): Client::sync_once defaults to reuse previous token
Introduces a new `SyncToken` enum for the `SyncSettings::token` field.
The enum has 3 variants: ReusePrevious (default), NoToken, Specific(String).

Some tests were changed to use the old default (NoToken).
2025-08-14 12:14:06 +02:00
Benjamin Bouvier 1ffc014621 chore(tests): make some tests less flaky
When I run these locally, they may now take more than 100ms to run, when
being run in parallel. Increase the timeout duration to 1s.
2025-08-14 09:18:15 +02:00
Benjamin Bouvier 9491757cad chore: check in the correct version of Ruma for ruma-signatures 2025-08-14 09:18:15 +02:00
Kévin Commaille 33df0422e8 Upgrade Ruma: profile response
Handle the changes to the Response of the get_profile endpoint. The
content of the response is private and fields must be accessed with
methods.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-14 08:57:52 +02:00
Kévin Commaille a3a239f999 Upgrade Ruma: revert StrippedState
Handle the previous breaking change that was reverted: `StrippedState`
was removed and `AnyStrippedStateEvent` is used again.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-14 08:57:52 +02:00
Skye Elliot ca8b64e041 feat: Change type of DecryptedRoomEvent::event to Raw<AnyTimelineEvent> (#5512)
- [x] Change `DecryptedRoomEvent::event` to `Raw<AnyTimelineEvent>`
- [x] Update usages to pattern match on `AnyTimelineEvent::MessageLike`
where necessary

---------

Signed-off-by: kaylendog <actuallyori@gmail.com>
2025-08-14 08:53:56 +02:00
Stefan Ceriu 140e751af0 feat(timeline): consider unthreaded read receipts for ReceiptThread::Main timelines when computing timeline items states.
This patch updates the Timeline Controller's `handle_explicit_read_receipts` method to also consider unthreaded read receipts on **threaded** **main** timelines when calculating timeline items states and adds a test for it.

This picks up from #5442 and fixes https://github.com/matrix-org/matrix-rust-sdk/issues/5440
2025-08-14 05:24:20 +00:00
multisme a66b2c5123 feat(test): add a test utils crate to make log initialization possible everywhere
This PR allows `init_tracing_for_test` to be called by any other crate in the sdk

Signed-off-by: multi [multiestunhappydev@gmail.com](mailto:multiestunhappydev@gmail.com)
2025-08-14 05:24:03 +00:00
Copilot 69bef9a76a feat(sdk,ffi): Add server_vendor_info method to matrix-sdk with automatic logging in FFI
Add a new `server_vendor_info` method on the `matrix-sdk` `Client` that calls the `/_matrix/federation/v1/version` endpoint to retrieve the server's software name and version information.

Also add it to the bindings + log it when initializing the logs.
2025-08-14 05:14:25 +00:00
Michael Goldenberg b3c53dd08f test(indexeddb): run time-based integration tests on event cache
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-13 16:00:48 +02:00
Michael Goldenberg c8bffa26a4 test(event-cache-store): make time-based integration tests compatible with wasm targets
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-13 16:00:48 +02:00
Michael Goldenberg b4ef6cef55 refactor(indexeddb): add IndexedDB-backed impl of EventCacheStore::try_take_leased_lock
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-13 16:00:48 +02:00
Michael Goldenberg c6854a5c22 refactor(indexeddb): add support for indexing time-based locks in event cache
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-13 16:00:48 +02:00
Michael Goldenberg fb563953c9 refactor(indexeddb): add object store for tracking time-based lock on event cache
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-13 16:00:48 +02:00
Michael Goldenberg bc0018aecb refactor(indexeddb): add type to represent time-based lock on event cache
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-13 16:00:48 +02:00
Johannes Marbach 12292c5375 feat(ffi): allow specifying thumbnails using UploadSource
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-08-13 15:50:06 +02:00
Johannes Marbach cf9d058265 feat(ffi): allow specifying gallery items using UploadSource
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-08-13 15:30:34 +02:00
Benjamin Bouvier 4da13e1096 refactor!(ffi): use the send queue by default to upload medias
We do consider it stable now, after months of running it in production,
so let's use it by default to simplify the `UploadParameters`.
2025-08-13 15:16:16 +02:00
Benjamin Bouvier 333d4563ce refactor!(ffi): remove legacy progress upload tracking
This can now be achieved by using the send queue's global progress
support, i.e. `Client::enable_send_queue_upload_progress()`.
2025-08-13 15:16:16 +02:00
Andy Balaam 01059ef26c refactor(timeline): Make RoomDataProvider provide Decryptor to simplify redecryption 2025-08-13 12:40:07 +01:00
Kévin Commaille 7724271508 doc(test): Fix method auto-link
Rustdoc doesn't support passing parameters for auto-links.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-13 12:31:22 +01:00
Kévin Commaille 8dfe732cce doc(sdk): Fix method auto-link
Rustdoc doesn't do multi-level auto-link, so we have to provide the link
manually.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-13 12:31:22 +01:00
Kévin Commaille 1cf3477ada feat(crypto): Implement Default for SecretStorageKey
For the new_without_default clippy lint.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-13 12:31:22 +01:00
Kévin Commaille 0a2205f540 refactor(ffi): Remove dead code
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-13 12:31:22 +01:00
Kévin Commaille c586812159 refactor(crypto): Remove dead code
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-13 12:31:22 +01:00
Kévin Commaille c6210cad21 ci: Upgrade the version of Rust nightly
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-13 12:31:22 +01:00
Ivan Enderlin a9ce1c6e58 doc(sdk): Fix CHANGELOG.md entry.
The link for an entry was wrong. It's #5439, not #5442.
2025-08-13 10:08:50 +02:00
Kévin Commaille 1eb8f6ac16 Fix shared history test
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-12 17:25:22 +03:00
Kévin Commaille e0feebdb2b fix(sdk): Support unauthenticated media endpoint in Client::load_or_fetch_max_upload_size
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-12 17:25:22 +03:00
Kévin Commaille 0fee716c1e fix(sdk): Override timeout of media downloads for unauthenticated media endpoints too
There is no reason to treat them differently.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-12 17:25:22 +03:00
Kévin Commaille c41ed8a78a refactor(sdk): Use Ruma support for (un)stable feature flags for authenticated media
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-12 17:25:22 +03:00
Benjamin Bouvier 53f02c9f2d chore: bump Ruma
So as to get some changes for Element Call:
https://github.com/ruma/ruma/pull/2176
2025-08-12 16:06:26 +02:00
Johannes Marbach e2f0b4f3fd feat(ffi): expose media upload progress through EventSendState::NotSentYet
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-08-12 12:57:18 +02:00
Johannes Marbach 0a796cb468 feat(timeline): communicate media upload progress through EventSendState::NotSentYet
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-08-12 12:57:18 +02:00
copilot-swe-agent[bot] e3390c17ec docs: Add changelog entries for LowPriority and NonLowPriority filters
Co-authored-by: pixlwave <6060466+pixlwave@users.noreply.github.com>
2025-08-12 13:17:53 +03:00
Doug c6dc070c31 chore: Refactor non_space.rs filter to space.rs, using new_filter_not in the FFI. 2025-08-12 13:17:53 +03:00
copilot-swe-agent[bot] 486befc7fb feat: Add NonLowPriority to the FFI bindings
Co-authored-by: pixlwave <6060466+pixlwave@users.noreply.github.com>
2025-08-12 13:17:53 +03:00
copilot-swe-agent[bot] 9848d1472e feat: Add LowPriority filter implementation and FFI bindings
Co-authored-by: pixlwave <6060466+pixlwave@users.noreply.github.com>
2025-08-12 13:17:53 +03:00
Damir Jelić 6c944a9b39 Add a changelog entry for the sender data check when accepting historic room keys 2025-08-08 15:56:13 +02:00
Damir Jelić b4b010f9fe fix(crypto): Do a keys query before we accept historic room key bundles 2025-08-08 15:56:13 +02:00
Damir Jelić 536ba518bb feat(crypto): Check sender data before accepting room key bundles 2025-08-08 15:56:13 +02:00
Damir Jelić 917c46b570 chore: Remove a stale TODO comment 2025-08-08 15:56:13 +02:00
Damir Jelić b29886c0df test(crypto): Add a test that we refuse bundles if the sender isn't trusted enough 2025-08-08 15:56:13 +02:00
Damir Jelić 360c2d7f32 refactor(crypto): Turn should_recalculate function into an associated function for SenderData
This allows us to use the function in more places where SenderData is
used.
2025-08-08 15:56:13 +02:00
dragonfly1033 683f0f4027 feat(multiverse): Add room creation to multiverse 2025-08-08 12:33:48 +01:00
Damir Jelić c783ed8a6f Log a special error when try to upload duplicate one-time keys 2025-08-08 10:35:52 +02:00
Damir Jelić 139673810f Remember the public Curve25519 key of the sender of the historic room key bundle 2025-08-08 09:19:19 +02:00
Kévin Commaille 669ebf2408 refactor(base): Don't take room ID in Notification::push_notification_from_event_if
It is already in the `PushConditionRoomCtx`, so we don't need an extra
argument for it.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-07 16:02:56 +02:00
dragonfly1033 992774b8b5 Add the matrix-sdk-search crate
A new crate with a basic API for a creating, populating and searching a
room message index.

Signed-off-by: Shrey Patel shreyp@element.io
2025-08-07 16:01:41 +02:00
Kévin Commaille 9d90a92b4c doc(base): Use different Result type in doc example
`anyhow::Ok(())` doesn't work under WASM because it requires the error
types to be `Send + Sync`.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-07 15:11:30 +02:00
Michael Goldenberg d79975e0e3 refactor(indexeddb): simplify IndexeddbEventCacheStoreTransaction::get_events_by_related_event
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 2e598c0532 refactor(indexeddb): remove unnecessary fn IndexedEventRelationKey::with_related_event_id
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 5a3ef30fdc refactor(indexeddb): remove redundant room id arg on relevant serializer and transaction fns
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 05178ccaf9 refactor(indexeddb): make room id a key component rather than fixed arg to IndexedKey::encode
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 65b9bd20a8 refactor(indexeddb): express IndexedKeyRange::All as IndexedKeyRange::Bound to loosen constraints on various functions
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 35505f9130 refactor(indexeddb): remove room id argument from Indexed::to_indexed
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg a6d630216d refactor(indexeddb): add room id to event_cache_store::types::Gap
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 159c9b4547 refactor(indexeddb): add room id to event_cache_store::types::GenericEvent
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg aead1a4489 refactor(indexeddb): add room id to event_cache_store::types::Chunk
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 7fee1c7fd7 refactor(indexeddb): add traits for constructing prefix key bounds
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg ab9bfb2d61 refactor(indexeddb): add reusable const and static values to construct key component bounds
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg de5f00fd33 refactor(indexeddb): use references in IndexedEventRelationKey::KeyComponents
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg 33c16b2979 refactor(indexeddb): use references in IndexedEventIdKey::KeyComponents
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Michael Goldenberg e9dcdb7176 refactor(indexeddb): add lifetime to IndexedKey::KeyComponents
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-08-07 12:53:32 +02:00
Benjamin Bouvier 0a3fe939c5 refactor(event cache): don't panic when loading a linked chunk's latest event fails
This can happen because of an OS-level error, so let's try to handle it
in a slightly cleaner way. At the moment, it will bubble up and only be
logged, but we might try to find a better way to handle this at the
top-level.
2025-08-07 12:17:15 +02:00
Benjamin Bouvier 37e07ea331 refactor(test): use the matrix mock server in test_notification_client_with_context 2025-08-07 11:59:36 +02:00
Benjamin Bouvier e4e3ff63f5 refactor(notification client): extract the common filtering out of events in a common helper 2025-08-07 11:59:36 +02:00
Benjamin Bouvier 8409e52654 doc(base): tweak some doc comment around notifications 2025-08-07 11:59:36 +02:00
Benjamin Bouvier e8096ee518 refactor(notification client): simplify get_notification_with_sliding_sync 2025-08-07 11:59:36 +02:00
Jonas Platte 6814e70aa4 refactor: Simplify some methods of FailuresCache
Follow-up to #5490.
2025-08-07 10:00:53 +02:00
multisme efa4539a91 refactor(client): have upload_encrypted_file own the Client instance (#5470)
Signed-off-by: multi multiestunhappydev@gmail.com
2025-08-07 09:51:23 +02:00
Jonas Platte 42d2b93489 refactor: Introduce TestResult and use it in a couple random places 2025-08-06 22:21:39 +00:00
Kévin Commaille 872713c4bc Add setting to ignore the timeout sync setting on first sync (#5481)
The `timeout` setting on the `/sync` endpoint is the maximum allowed
time for the server to send its response, because this is a poll-based
API. It means that if there is no new data to show, the server will wait
until the end of `timeout` before returning a response.

It can be an undesirable behavior when starting a client and informing
the user that we are "catching up" while waiting for the first response.

By not setting a `timeout` on the first request to `/sync`, the
homeserver should reply immediately, whether the response is empty or
not.

---------

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
Signed-off-by: Ivan Enderlin <ivan@mnt.io>
Co-authored-by: Ivan Enderlin <ivan@mnt.io>
2025-08-06 16:48:44 +02:00
Kévin Commaille feb22d4370 Move serde functions to module and use #[serde(with = "")]
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-06 16:44:51 +02:00
Kévin Commaille 6520c9b16e Add changelog
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-06 16:44:51 +02:00
Kévin Commaille cd6fe271ba refactor(crypto): Make deprecated sender_key and device_id optional in RoomEncryptedEventContent and RoomKeyRequestContent
They were deprecated in Matrix 1.3 and are now optional.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-06 16:44:51 +02:00
Jonas Platte 5f447bbb17 chore: Fix new clippy lints 2025-08-06 16:38:08 +02:00
Jonas Platte 94e7ddd1ab chore: Upgrade matrix-sdk to edition 2024 and format 2025-08-06 16:38:08 +02:00
Jonas Platte 6ac4a8431d chore: Prepare matrix-sdk-common for edition 2024
Cherry-picked some changes from cargo fix --edition.
2025-08-06 16:38:08 +02:00
Benjamin Bouvier b585963abb test(notification client): check msc4306 behavior in the notification client too 2025-08-06 15:28:43 +02:00
Benjamin Bouvier 5719fde701 feat(client): add a global toggle for enabling thread subscriptions support 2025-08-06 15:28:43 +02:00
Benjamin Bouvier 2914d7a727 feat(threads): provide has_thread_subscription_fn to push condition context 2025-08-06 15:28:43 +02:00
Benjamin Bouvier 0cdec9d912 refactor(threads): flatten the ThreadStatus enum 2025-08-06 15:28:43 +02:00
Benjamin Bouvier d180d49c07 refactor(threads): do not store the unsubscribed state in the DB 2025-08-06 15:28:43 +02:00
Benjamin Bouvier bcee5badae refactor(threads): adapt to Ruma API changes related to async evaluation of push rules 2025-08-06 15:28:43 +02:00
Benjamin Bouvier ebb7059d55 refactor(threads): adapt to Ruma API changes for thread subscriptions 2025-08-06 15:28:43 +02:00
Benjamin Bouvier 8d3b1d3c7e chore: update Ruma 2025-08-06 15:28:43 +02:00
Kévin Commaille 056e90db25 feat(sdk): Use state_after in sync v2 (#5488)
It is supposed to be an improvement over `state`, since it allows the
server to send updates to the state that might not be reflected in the
timeline.

This is also the same behavior as in Simplified Sliding Sync.

This is MSC4222 that was accepted and is about to get merged in the
spec.

---------

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-06 13:42:49 +01:00
Kévin Commaille 787861eb35 fix: Upgrade Ruma
This brings 2 important bug fixes:

- Make deprecated fields of `m.room.encrypted` optional: it seems that there are events without these fields in the wild.
- Fix deserialization of `RedactedRoomJoinRulesEventContent`. This was found by a bug report in Fractal that caused the same error as #3557 when restoring the client. So maybe we could consider that this bug is fixed? It is still possible that there is another deserialization error. 

There is also a breaking change in the format of the `state` field in response to `GET /v3/sync`.
2025-08-05 16:04:34 +02:00
dependabot[bot] f081416baa chore(deps): bump crate-ci/typos from 1.34.0 to 1.35.0
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.34.0 to 1.35.0.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.34.0...v1.35.0)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.35.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-05 10:02:48 +02:00
Jorge Martín 8a6cc7bc22 refactor(sdk): Only log the power levels computing error for joined rooms 2025-08-05 09:54:26 +02:00
Jorge Martín 61258e823f test: Fix and add tests for computing the push conditions requiring the room creation event 2025-08-05 09:54:26 +02:00
Jorge Martín e86aab68b4 fix(sdk): Make sure we log the error when we can't compute the power levels of a room 2025-08-05 09:54:26 +02:00
Jorge Martín 48f1bc0780 fix(notification_client): Add m.room.create to the required sliding sync state
With this missing, power levels couldn't be computed, and some push rules didn't take effect.
2025-08-05 09:54:26 +02:00
Stefan Ceriu 1fe71acbcb change(room_list): request space rooms through sliding sync and expose a room list filter for them (#5479)
This is a breaking change as spaces are now requested through sliding sync and they need to manually be excluded from the room list by using the newly introduced non-space filter.
2025-08-04 16:39:02 +02:00
Kévin Commaille 0e054deb19 fix(sdk): Allow legacy push rules to be missing when changing NotificationSettings
They are being removed from the spec with MSC4210, so we can't error if they are not found.
2025-08-04 13:40:01 +00:00
Doug d2b7dc6116 ffi: Export TimelineDiff as uniffi:Enum to match RoomDirectorySearchEntryUpdate & RoomListEntriesUpdate.
The difference in API shape has been weird for long enough.
2025-08-04 12:01:24 +02:00
Ivan Enderlin 1089a25588 fix(xtask): Use --package instead of -p on cargo ndk.
We use `cargo ndk -p {package_name}`, where `-p` is short for
`--package`. However, `cargo ndk` has introduced the `-p` option (see
https://github.com/bbqsrc/cargo-ndk/commit/c6b93a89a2723ff0fac99b5ac86ae6636a6cf54a),
short for `--platform`. It creates a confusion and the command line
doesn't execute properly. Let's use the long option `--package` to
clarify everything.
2025-08-04 10:41:17 +02:00
Kévin Commaille 3276bc87ad refactor(base): Don't drop whole m.room.create if predecessor is invalid
The `m.room.create` event contains at lot of important information for a
room, like its type (i.e. whether it is a space), its version and its
creator(s) (which are important in room version 12). So ignoring the
event completely might break a room.

Instead what we do here is simply ignore the `predecessor` field if it
is considered invalid, allowing us to access the other fields.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-04 10:09:52 +02:00
Hubert Chathi a4da6ba7c8 Exclude insecure devices on Olm encryption (#5457)
Fixes the encrypting part of
https://github.com/matrix-org/matrix-rust-sdk/issues/4147

Probably easiest to review commit-by-commit

<!-- description of the changes in this PR -->

- [x] Public API changes documented in changelogs (optional)

<!-- Sign-off, if not part of the commits -->
<!-- See CONTRIBUTING.md if you don't know what this is -->
Signed-off-by:
2025-08-04 08:50:32 +01:00
Kévin Commaille 033c6bd6a4 Add changelog
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-01 14:07:28 +02:00
Kévin Commaille b02e1da471 Upgrade Ruma
This brings in a new breaking change from Ruma, because not all events
are stripped in a room's stripped state. For simplicity, this still
considers the events as stripped during deserialization for now, since
this format is compatible with the other possible formats.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-08-01 14:07:28 +02:00
Damir Jelić 5ad477ac96 tests: Rename some more benchmarks 2025-08-01 11:33:08 +02:00
Damir Jelić 975432565d tests: Enable timers for the runtime of the store bench 2025-08-01 11:33:08 +02:00
Damir Jelić 46b0113765 tests: Rename some crypto benchmarks
This is mostly due to codspeed not showing the group name, so we're
repeating this info in the benchmark ID.
2025-08-01 11:33:08 +02:00
Damir Jelić 09eff8c6bd ci: Lower the amount of events we benchmark against on the CI 2025-08-01 11:33:08 +02:00
Damir Jelić 7ee546a3d9 ci: Enable more benchmarks 2025-08-01 11:33:08 +02:00
Benjamin Bouvier b164cd6a51 refactor(timeline): remove a few unused Self in some read-receipt related methods 2025-07-31 14:14:27 +02:00
Benjamin Bouvier 6d95abfb36 refactor(send queue): move the AbstractProgress to the new progress module 2025-07-31 13:04:28 +02:00
Benjamin Bouvier 33f09d6d26 refactor(send queue): move upload progress functionality to its own file 2025-07-31 13:04:28 +02:00
Benjamin Bouvier 8c01e99144 refactor(send queue): misc improvements to media upload progress reporting
Notable changes: don't send a global update whenever a media upload
progress happened, since this doesn't really matter for global
listeners.
2025-07-31 13:04:28 +02:00
Benjamin Bouvier 277cb7ac49 refactor(send queue): rename variables around the thumbnail file size cache 2025-07-31 11:16:48 +02:00
Johannes Marbach fc7124fd1a feat(send_queue): communicate media upload progress in RoomSendQueueUpdate::MediaUpload
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Johannes Marbach 30c0420f83 chore(send_queue): rename RoomSendQueueUpdate::UploadedMedia to MediaUpload to prepare it for communicating upload progress
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Johannes Marbach cb13c345ad feat(sdk): introduce AbstractProgress for tracking media progress in pseudo units
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Johannes Marbach cd26973082 feat(send_queue): enable progress monitoring in RoomSendQueue::handle_request
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Johannes Marbach 0edcdd33b2 chore(send_queue): Make parent_is_thumbnail_upload available outside of unstable-msc4274 to use it during media progress reporting later
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Johannes Marbach c191eb7cd1 feat(send_queue): cache thumbnail sizes to use them in progress reporting later
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Johannes Marbach fa6f270812 chore(send_queue): collect thumbnail-related metadata in a dedicated QueueThumbnailInfo struct for easier extension
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Johannes Marbach d4e96595d9 feat(send_queue): add global setting for sending media progress updates
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-31 11:16:48 +02:00
Jakob Lachermeier 540a11e7a8 fix(sqlite): made open_with_pool public again. 2025-07-31 09:15:47 +02:00
Damir Jelić 92192c549b fix(timeline): Remove UTD items that have been decrypted into unsupported events 2025-07-30 12:46:04 +02:00
Damir Jelić 88360040fb test(timeline): Add some integration tests for the redecryption logic
These tests now fully mock all the end-to-end encryption server
endpoints to test the redecryption and UTD item replacement logic of the
timeline without any manual room key insertions.

We test that the item replacement correctly handles supported event
types as well as unsupported ones.
2025-07-30 12:46:04 +02:00
Damir Jelić 4184e245a4 ci: Attempt to free up even more space for the coverage job 2025-07-30 12:10:12 +02:00
Benjamin Bouvier f37bf2f5d1 feat(store): also delete thread subscriptions when deleting a room in db 2025-07-30 12:07:07 +02:00
Benjamin Bouvier d57d3c4124 feat(sdk): save the unsubscribed status in the store, and use it to return something more precise than unknown when fetching a subscription 2025-07-30 12:07:07 +02:00
Benjamin Bouvier 1a5cb2beb8 feat(stores): allow saving thread subscriptions 2025-07-30 12:07:07 +02:00
Benjamin Bouvier b645c1101f refactor(test): avoid proliferation of builder submethods in the MockClientBuilder
Instead of having one static method duplicating an underlying
`ClientBuilder` method, we can pass the builder directly to a closure,
that will replace it. Call sites are a bit more verbose, but that would
avoid having to add duplicate `MockClientBuilder` methods for each
`ClientBuilder` method.
2025-07-30 11:56:31 +02:00
Robin 8091094bbc refactor(room): Remove methods for sending call notifications
As noted in the changelog entry, the event type they send is outdated, and Client is not actually supposed to be able to join MatrixRTC sessions at this time. A MatrixRTC client implementation which actually participates in sessions should be able to send these notifications without the SDK's help.
2025-07-29 15:04:25 +02:00
Robin feadfde1b5 feat(element-call): Support the sendNotificationType URL parameter
This URL parameter allows us to request Element Call widgets to send a notification when starting a call.
2025-07-29 15:04:25 +02:00
Damir Jelić e2ad07881c Merge pull request #5443 from matrix-org/poljar/ci/benchmarks
Enable benchmarks on the CI
2025-07-28 13:07:00 +02:00
Jorge Martín 1be8b42d03 refactor(ffi): expose privileged_creators_role in the FFI RoomInfo 2025-07-28 12:05:48 +02:00
Jorge Martín 7a5f83f6ec refactor(ffi): expose room_version in the FFI RoomInfo 2025-07-28 12:05:48 +02:00
Jorge Martín 88bb7a366f feat(ffi): enable unstable-hydra feature for the SDK bindings 2025-07-28 11:42:21 +02:00
Benjamin Bouvier 7d9bf56581 feat(ffi): add support for MSC4036 thread subscriptions 2025-07-28 10:39:38 +02:00
Benjamin Bouvier 770f65ede0 feat(multiverse): add support for subscribing/unsubscribing/showing the current sub status 2025-07-28 10:39:38 +02:00
Benjamin Bouvier 1f33e0f4d1 test(threads): add test for the thread subscription endpoints 2025-07-28 10:39:38 +02:00
Benjamin Bouvier 117f76102d test(threads): add mocks for the thread subscription endpoint 2025-07-28 10:39:38 +02:00
Benjamin Bouvier fd04ebfaba feat(sdk): add support for threads subscription CRUD (msc4306)
This doesn't store the subscriptions locally, nor does it implement the
automatic thread subscription.
2025-07-28 10:39:38 +02:00
Benjamin Bouvier afe9f7a979 chore: upgrade ruma for msc4306 2025-07-28 10:39:38 +02:00
Benjamin Bouvier 27a002c8e2 chore: add changelog entry for the breaking change in RelationalLinkedChunk::items 2025-07-28 10:34:56 +02:00
Benjamin Bouvier b8ab0972b3 fix(event cache store): return events from all linked chunks in a room, in find_event and find_event_with_relations of the memory store 2025-07-28 10:34:56 +02:00
Benjamin Bouvier d3419ea4ac test(event cache store): add tests for a thread's vs a room's linked chunk id 2025-07-28 10:34:56 +02:00
Benjamin Bouvier 019adb9a56 feat(common): implement the thread variants for LinkedChunkId and OwnedLinkedChunkId 2025-07-28 10:34:56 +02:00
Kévin Commaille ca89700dfe refactor(ffi): Fix clippy lint
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-25 17:55:31 +02:00
Kévin Commaille a0c87cfe4f Add changelog
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-25 17:36:19 +02:00
Kévin Commaille 9ddc892aa0 fix(sdk): Support event types with variable suffix for event handlers
Previously they would just not work as we were trying to match a full
event type with a prefix.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-25 17:36:19 +02:00
Kévin Commaille 0a7ac18d9f refactor: Add IsPrefix = False bound on StaticEventContent bounds
Since those APIs only support a full event type, not an event type prefix.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-25 17:36:19 +02:00
Robin d8b6966c0a Allow Element Call to send call notifications
For clients which integrate Element Call: Currently matrix-rust-sdk is responsible for sending the call notification event when joining MatrixRTC sessions, but this is planned to be changed soon. As of the upcoming Element Call 0.14.0 release, it will request the capability to send call notifications itself, and we should auto-approve this capability.
2025-07-25 09:20:39 +03:00
Damir Jelić d40f04e32c chore: Remove the criterion function in the benchmarks
It's now equivalent to Criterion::default().
2025-07-24 17:11:03 +02:00
Damir Jelić d8294a0788 Fix the compilation of the crypto bench 2025-07-24 17:09:59 +02:00
Damir Jelić 06a4476e7f ci: Disable a benchmark that panics on the CI 2025-07-24 16:48:28 +02:00
Andy Balaam def1fedea3 feat(crypto): Refuse to decrypt to-device messages from unverified devices (when in exclude insecure mode) 2025-07-24 15:08:13 +01:00
Andy Balaam d061e7a5b2 refactor(tests): Pass decryption_settings in to send_and_receive_encrypted_to_device_test_helper
To allow passing in different values in future tests.
2025-07-24 15:08:13 +01:00
Andy Balaam f4619c91d3 refactor(tests): Re-use send_and_receive_encrypted_to_device_test_helper in 2 more tests 2025-07-24 15:08:13 +01:00
Andy Balaam 227f6eab85 refactor(tests): Take a reference to content in send_and_receive_encrypted_to_device_test_helper
This will allow us to re-use it in more tests.
2025-07-24 15:08:13 +01:00
Andy Balaam 16d7c3c094 refactor(crypto): Extract a method to check for to-device events from dehydrated devices 2025-07-24 15:08:13 +01:00
Andy Balaam c238a0edb8 refactor(crypto): Pass DecryptionSettings in to OlmMachine::decrypt_to_device_event
This will be used in the next commit, but it was very noisy, so I
separated it out into this commit to make the next one easier to read.
2025-07-24 15:08:13 +01:00
Damir Jelić 06bf487512 chore: Attempt to get rid of a crash on CI where the runtime isn't used for a drop 2025-07-24 15:40:41 +02:00
Damir Jelić c636ec63f4 chore: Inherit the release profile for the bench profile 2025-07-24 15:07:48 +02:00
Damir Jelić ffe239d620 Actually respect the benchmarks matrix on CI 2025-07-24 14:40:14 +02:00
dragonfly1033 822b709107 feat(sdk): Leaving a room now leaves its predecessors as well
Signed-off-by: Shrey Patel shreyp@element.io
2025-07-24 13:56:05 +02:00
Damir Jelić d75d7973b2 ci: Enable benchmarks on the CI 2025-07-24 13:37:45 +02:00
Damir Jelić cfe3adce48 chore: Bump criterion 2025-07-24 13:37:45 +02:00
Damir Jelić b478ae65f7 tests: Remove pprof 2025-07-24 13:37:45 +02:00
Michael Goldenberg ada68e1114 feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::find_event_relations
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-23 18:03:06 +02:00
Michael Goldenberg c9137f0cad fix(indexeddb): Updates::PushItems performs an update if any provided item already exists
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-23 18:03:06 +02:00
Michael Goldenberg 4e0dab959a feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::save_event
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-23 18:03:06 +02:00
Michael Goldenberg e862ded147 feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::find_event
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-23 18:03:06 +02:00
Michael Goldenberg 5cb033ad91 feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::filter_duplicated_events
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-23 18:03:06 +02:00
Kévin Commaille 0e622cc5a1 Upgrade Ruma (phase 3)
This upgrade introduces support for room version 12[1].

[1]: https://matrix.org/blog/2025/07/security-predisclosure/)

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-23 14:32:05 +00:00
Jorge Martín 6d562eff2f fix: Restore the previous behaviour for calculating the timeout for syncs 2025-07-23 15:55:31 +02:00
Jorge Martín af2e15e02f refactor(ffi): Add the default read_timeout value to the FFI layer 2025-07-23 15:55:31 +02:00
Jorge Martín 79aa5aaf16 refactor: Remove the default timeout when downloading media, rely on read_timeout instead
Users with poor network connectivity complained their downloads were cancelled for no good reason after 30s before (the default `timeout` value).
2025-07-23 15:55:31 +02:00
Jorge Martín 0833ffdef2 refactor: Add RequestConfig::read_timeout to cancel network connections that have been stale for longer than the specified timeout 2025-07-23 15:55:31 +02:00
Jorge Martín 16f7239215 refactor: Make RequestConfig::timeout optional
This allows us to remove the default timeout on a per-request basis
2025-07-23 15:55:31 +02:00
Doug da946e51dd ffi: Update Client::get_url to return raw data and to throw on HTTP errors
Client::get_url is there for SDK consumers to be able to use the
existing HTTP stack (configuration and all) however in practice it was a
bit weird:
- Responses came back as strings limiting the types of resource that
could be fetched (as well as requiring the string to be converted back
to data before handed to a JSON decoder).
- HTTP errors weren't being raised and instead you would find the (e.g.
404) error response in the Ok case.

This patch fixes both of these issues.
2025-07-23 15:24:49 +02:00
Benjamin Bouvier cba711dbdf feat(timeline): add support for sending sticker/polls in thread automatically too 2025-07-23 15:05:23 +02:00
Benjamin Bouvier e87e9331c1 feat!(timeline): infer the reply type automatically when sending a media gallery 2025-07-23 15:05:23 +02:00
Benjamin Bouvier 6e9fc70d13 refactor(timeline): homogeneize naming of replied_to vs in_reply_to 2025-07-23 15:05:23 +02:00
Benjamin Bouvier e2148e46bc feat!(timeline): infer the reply type automatically when sending an attachment 2025-07-23 15:05:23 +02:00
Benjamin Bouvier d1163b75bf feat!(timeline): Timeline::send_reply() automatically includes the thread relationship too 2025-07-23 15:05:23 +02:00
Benjamin Bouvier 5ae7d0f60f feat(timeline): Timeline::send() automatically includes the thread relationship for thread foci 2025-07-23 15:05:23 +02:00
Benjamin Bouvier 6f067d5510 doc(event cache): add a code comment indicating why room updates processing isn't happening concurrently 2025-07-23 11:21:09 +02:00
Benjamin Bouvier d6fe654814 bench: add a benchmark for measuring the time it takes to handle a sync update in the event cache 2025-07-23 11:21:09 +02:00
Benjamin Bouvier 2710510786 refactor(base): use let chains where the comment said to do so \o/ 2025-07-23 09:57:50 +02:00
Benjamin Bouvier 35a8528712 chore(base): clippy fixes 2025-07-23 09:57:50 +02:00
Benjamin Bouvier f9735c75d3 chore(base): rustfmt 2024 edition 2025-07-23 09:57:50 +02:00
Benjamin Bouvier 15e6b81835 chore(base): upgrade matrix-rust-sdk-base to edition 2024 2025-07-23 09:57:50 +02:00
Damir Jelić bcb4ab4b10 contrib: Set our check command to check instead of clippy
Clippy is a bit too heavy to be used as the check on save command in
this repo.

Let's set a better default.
2025-07-22 15:20:37 +02:00
Kévin Commaille 4931c0749e Upgrade Ruma again
This patch updates our `Raw` API usage since the newly added `JsonCastable` that disallows Raw casts that are known to fail deserialization. 

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-22 12:59:26 +00:00
Kévin Commaille 37626b5ad9 Bump Ruma
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-22 14:00:53 +02:00
Benjamin Bouvier d19616da03 chore!: bump the MSRV to 1.88
let-chains ftw
2025-07-22 12:15:33 +02:00
Ivan Enderlin 7c8f870d16 Revert "fix(sdk): Disable OrderTracker for the moment."
This reverts commit c5f2460e02.
2025-07-22 10:24:27 +02:00
Benjamin Bouvier b482ccd318 feat(sqlite): make sqlite's implementation of load_all_chunks_metadata even faster
See the updated code comment.
2025-07-21 17:41:06 +02:00
Ivan Enderlin 165ec9db1b bench: Add a benchmark for EventCacheStore::load_all_chunks_metadata. 2025-07-21 10:31:44 +02:00
Ivan Enderlin 6f42210d6a feat(sqlite): Improve throughput of load_all_chunks_metadata by 1140%.
This patch changes the query used by
`SqliteEventCacheStore::load_all_chunks_metadata`. It was the cause of
severe slowness. The new query improves the throughput by +1140% and the
time by -91.916%. The benchmark will follow in the next patch.

Metrics for 10'000 events (with 1 gap every 80 events).

- Before:
  - throughput: 20.686 Kelem/s,
  - time: 483.43 ms.
- After:
  - throughput: 253.52 Kelem/s,
  - time: 39.478 ms.

This query will visit all chunks of a linked chunk with ID
`hashed_linked_chunk_id`. For each chunk, it collects its ID
(`ChunkIdentifier`), previous chunk, next chunk, and number of
events (`num_events`). If it's a gap, `num_events` is equal to 0,
otherwise it counts the number of events in `event_chunks` where
`event_chunks.chunk_id = linked_chunks.id`.

Why not using a `(LEFT) JOIN` + `COUNT`? Because for gaps, the entire
`event_chunks` will be traversed every time. It's extremely inefficient.
To speed that up, we could use an `INDEX` but it will consume more
storage space. Finally, traversing an `INDEX` boils down to traverse a
B-tree, which is O(log n), whilst this `CASE` approach is O(1). This
solution is nice trade-off and offers great performance.
2025-07-21 10:31:44 +02:00
Kévin Commaille 6125580275 feat: Add Account::fetch_account_data_static
It uses the statically-known type from the `StaticEventContent`
implementation to call `fetch_account_data()`.

This is the equivalent of `Account::account_data()` but for fetching
from the server. It avoids the need to cast to the proper type after.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-18 16:01:07 +02:00
Kévin Commaille 8b3e295429 refactor(test): Use EventBuilder::into_raw_timeline rather than into_event
We need the full event so its better to build it an cast it to a sync
event than the opposite.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-18 16:01:07 +02:00
Kévin Commaille 1e568efbb5 refactor: Remove unnecessary Raw casting
The types are already correct so there is no need for casting.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-18 16:01:07 +02:00
Andy Balaam f89ced3ded task(sliding_sync): Avoid logging the entire sliding sync response at the DEBUG level
Signed-off-by: Damir Jelić <poljar@termina.org.uk>
Co-authored-by: Damir Jelić <poljar@termina.org.uk>
Co-authored-by: Jonas Platte <jplatte@matrix.org>
2025-07-18 13:18:04 +00:00
Damir Jelić a5fbcf1491 Merge pull request #5322 from matrix-org/poljar/shared-history/out-of-order
feat(sdk): Add a tasks that listens for historic room keys if they arrive out of order
2025-07-17 16:52:13 +02:00
Yorusaka Miyabi 8923e58ee3 feat(ffi): Expose legacy SSO support infomation
Currently Element X can't distinguish the cases where a homeserver only
supports legacy SSO without OIDC (and password login isn't avaliable),
and other server unreachable scenarios.

This patch exposes legacy SSO support infomation so that Element X side
can give a dedicated error message when it encounters a homeserver that
can only support legacy SSO.

Signed-off-by: Yorusaka Miyabi <23130178+ShadowRZ@users.noreply.github.com>
2025-07-17 16:42:27 +02:00
Damir Jelić f14994baa9 test(sdk): Test if we accept historic room key bundles arriving out of order 2025-07-17 16:39:31 +02:00
Damir Jelić d42d0f3e17 test(sdk): Add a bunch more useful mock helpers 2025-07-17 16:39:17 +02:00
Damir Jelić e4849d5cab test(sdk): Don't expect a default access token in a bunch of methods
The mocks can be configured to expect a default access token separately,
this seems to have been a copy/paste error.
2025-07-17 16:39:17 +02:00
Damir Jelić 65aec7ee7f test(sdk): Add a method for two test clients to exchange E2EE identities 2025-07-17 16:39:17 +02:00
Damir Jelić a6868386d0 test(sdk): Allow the test client to enable shared history 2025-07-17 16:39:17 +02:00
Damir Jelić b3c1ca1577 Use the invite details when deciding if we should accept a bundle 2025-07-17 16:39:17 +02:00
Damir Jelić ce66ee4a16 test(sdk): Test the conditions under which we accept a historic room key bundle 2025-07-17 13:41:30 +02:00
Damir Jelić 2bbf6fc711 feat(sdk): Add a tasks that listens for historic room keys if they arrive out of order
Historic room key bundles are uploaded as an encrypted file to the media
repo and the key to decrypt the file is sent as a to-device message to
the recipient device.

In the nominal case, the invite and this to-device message should arrive
at the same time and accepting the invite would download and import the
bundle.

If the to-device message arrives after the invite has already been
accepted we would never download and import the bundle.

To mitigate this problem, this patch introduces a task that listens for
bundles that arrive. If the bundle is for a room that we have joined we
will consider importing the bundle.
2025-07-17 13:41:30 +02:00
Kévin Commaille 1a9e5b904b Move changelog entry to the top
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-17 12:42:05 +02:00
Kévin Commaille 4c43b06445 Add changelogs
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-17 12:42:05 +02:00
Kévin Commaille 49a0765880 refactor(base): Remove the event_id field of PredecessorRoom
It is going away in MSC4291, which should be accepted next week.
Removing it now makes sure that no one uses it.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-17 12:42:05 +02:00
Florian 39cf8b325d Allow requesting additional scopes for OAuth2 authorization code flow
For custom integrations it might be necessary to allow the SDK to
request additional scopes for the OAuth2 authorization code flow.
Currently, only the MSC2967 client API and client device scopes are
requested statically.


Signed-off-by: fl0lli <github@fl0lli.de>
2025-07-16 10:23:02 +02:00
Jonas Platte bb67150d6b chore: Upgrade matrix-sdk-store-encryption to Rust Edition 2024 2025-07-16 09:36:10 +02:00
Michael Goldenberg 471e3c340c refactor(indexeddb): add timers to all EventCacheStore functions for easy performance tracking
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-15 16:02:10 +02:00
Michael Goldenberg 74972d8db7 feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::load_all_chunks_metadata
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-15 16:02:10 +02:00
Michael Goldenberg 03a76fbaf5 feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::clear_all_linked_chunks
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-15 16:02:10 +02:00
Michael Goldenberg 392a1ef47b feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::load_previous_chunk
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-15 16:02:10 +02:00
Ivan Enderlin c5f2460e02 fix(sdk): Disable OrderTracker for the moment.
This patch removes the use of `OrderTracker` because the
implementation of `EventCacheStore::load_all_chunks_metadata` for
`SqliteEventCacheStore` is the cause of severe slownesses (up to 100s
for some account).

We are going to undo this patch once the problem has been solved.
2025-07-15 12:17:28 +02:00
fl0lli 8ad785a117 docs(ffi): move entry for device_id change of url_for_oidc to top
Signed-off-by: fl0lli <github@fl0lli.de>
2025-07-15 10:14:17 +02:00
fl0lli a5b936d0b6 docs(ffi): add breaking change entry for Client::url_for_oidc
Signed-off-by: fl0lli <github@fl0lli.de>
2025-07-15 10:14:17 +02:00
fl0lli 1a0544c8eb chore(ffi): formatting
Signed-off-by: fl0lli <github@fl0lli.de>
2025-07-15 10:14:17 +02:00
fl0lli 232c23e8df feat(ffi): allow setting existing device id for Client.url_for_oidc
Signed-off-by: fl0lli <github@fl0lli.de>
2025-07-15 10:14:17 +02:00
Jonas Platte 7d9d5bf3b4 refactor: Use if-let chain 2025-07-15 08:41:44 +02:00
Jonas Platte ea076b3d76 chore: Upgrade testing crates to Rust Edition 2024 2025-07-15 08:41:44 +02:00
Jonas Platte 8aa6f97f7c chore: Upgrade benchmarks to Rust Edition 2024 2025-07-15 08:39:27 +02:00
Jonas Platte 679aa07115 chore(ui): Upgrade to Rust edition 2024 2025-07-14 19:50:36 +02:00
Jonas Platte 0c66d8a53f refactor(ui): Cherry-pick some edition-fix changes
Automated with `cargo fix --edition -p matrix-sdk-ui`, reverting
unnecessary changes.
2025-07-14 19:50:36 +02:00
Michael Goldenberg 25ed7eef2b doc(indexeddb): add explanation of error types in EventCacheStore::load_last_chunk
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-14 18:46:20 +02:00
Michael Goldenberg a399840dff refactor(indexeddb): separate transaction and event cache error conversions
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-14 18:46:20 +02:00
Michael Goldenberg 8d4e7f0478 test(indexeddb): add IndexedDB-specific integration tests for loading last chunk
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-14 18:46:20 +02:00
Michael Goldenberg 3bd93130c5 feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::load_last_chunk
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-14 18:46:20 +02:00
Michael Goldenberg 153618b77c refactor(indexeddb): add helper fns for EventCacheStore::load_last_chunk
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-14 18:46:20 +02:00
Kévin Commaille dd871ef9ac refactor(base): Store RoomPowerLevels in RoomMember
Avoids to carry around the event content only to convert it when we
want to use it. Avoids also to carry around the room creator when we
might not need it.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-14 18:04:33 +02:00
Kévin Commaille 8a29f17d1d refactor(base): Call Room::power_levels instead of loading event from the store
To reduce code duplication.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-14 18:04:33 +02:00
Kévin Commaille fab520ab33 refactor(base): Add methods on StateChanges to get a member or power level event
To reduce duplication.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-14 18:04:33 +02:00
Ivan Enderlin 435553c3d1 feat(sdk): Add more logs in generate_sync_request. 2025-07-14 17:48:07 +02:00
Ivan Enderlin 610ecd218c feat(sdk): Log the time spent waiting on the position lock. 2025-07-14 17:48:07 +02:00
Kévin Commaille fa300d1f33 refactor(tests): Prefer EventBuilder::into_raw to into_raw_(sync/timeline) then Raw::cast
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-14 17:46:02 +02:00
Ivan Enderlin af2a483158 feat(sdk): Add debug! log when updating the sliding sync pos. 2025-07-14 16:52:36 +02:00
Ivan Enderlin 753b0d8584 doc(sdk): Update doc of SlidingSyncPositionMarkers::pos.
With `SlidingSync::share_pos`, the `pos` can be persisted. This comment
is outdated.
2025-07-14 16:40:06 +02:00
Ivan Enderlin 36713adbdb feat(sdk): Add more logs around the sync_lock and response_processor in SlidingSync. 2025-07-14 14:58:09 +02:00
Ivan Enderlin d73a02c608 feat(sqlite): Add more timer! logs in each EventCacheStore methods.
This patch adds `timer!` logs in each method from `EventCacheStore` for
`SqliteEventCacheStore`. It will help to know the execution duration of
each of these methods.
2025-07-14 10:34:17 +02:00
Ivan Enderlin f73199b472 feat(sqlite): Instrument SqliteEventCacheStore::open_with_config. 2025-07-14 10:34:17 +02:00
Ivan Enderlin 420d373144 feat(sqlite): Add #[instrument] around all SqliteEventCacheStore methods. 2025-07-14 10:34:17 +02:00
Ivan Enderlin a79e9130e6 feat(sqlite): Add timer! tracings in read and write's SqliteEventCacheStore. 2025-07-14 10:34:17 +02:00
Ivan Enderlin 355b5327f8 refator(common): Rename TracingTimer::new_debug.
This patch renames `TracingTiming::new_debug` to `new`. The
documentation claims it sets the log level to `debug` while the `level`
is actually an argument of the constructor. It's then wrong, and the
constructor must be renamed.
2025-07-14 10:34:17 +02:00
Ivan Enderlin fa77852001 feat(common): TracingTimer uses the Debug impl of Duration.
This changes the `TracingTimer` message to use the `Debug` impl of
`Duration` instead of displaying it as milliseconds. It can help spotting
seconds without counting all the digits.
2025-07-14 10:34:17 +02:00
Ivan Enderlin 7b73311de5 feat(sqlite): Add logs around read and write. 2025-07-14 10:34:17 +02:00
Ivan Enderlin f03934bc4f feat(sqlite): SqliteEventCacheStore has 1 write connection.
Until now, `SqliteEventCacheStore` manages a pool of connections. A
connection is fetched from this pool and operations are executed on it,
regardless whether these are read operations or write operations.

We are seeing more and more _database is busy_ errors. We believe this
is because too many write operations are executed concurrently.

The solution to solve this is to use multiple connections for read
operations, and a single connection for write operations. That way,
concurrent writings are no longer a thing, and we hope it will reduce
the number of _database is busy_ errors to zero. That's our guess.

This patch does that. When the pool of connections is created, a
connection is elected as the `write_connection`. To get a connection for
read operations, one has to use the new `SqliteEventCacheStore::read`
method (it replaces the `acquire` method). To get a connection for
write operations, one has to use the new `SQliteEventCacheStore::write`
method. It returns a `OwnedMutexGuard` from an async `Mutex`. All
callers that want to do write operations on this store have to wait
their turn, this `Mutex` is fair, and the first to wait on the lock is
the first that will take the lock (FIFO). It guarantees the execution
ordering the code expects.

The rest of the patch updates all spots where `acquire` was used and
replaces them by `read()` or `write()`. A particular care was made to
see if other places are using `SqliteEventCacheStore::pool` directly. No
place remains except in `read()` and `write()`.
2025-07-14 10:34:17 +02:00
Ivan Enderlin 014ee98fb7 feat(sqlite): SqliteStoreConfig::pool_size sets a minimum to 2.
This patch updates `SqliteStoreConfig::pool_size` to be at least 2. We
need 2 connections: one for write operations, one for read operations.
This behaviour is coming in the next patches.
2025-07-14 10:34:17 +02:00
Ivan Enderlin fbcf9fce7c feat(sdk): Add more logs in EventCache.
This patch adds more logs inside `EventCache` around the
`multiple_room_updates_lock` and around the `listen_task`, just to be
sure if everything is listened and works as expected.
2025-07-14 09:24:38 +02:00
Damir Jelić 6de403276a feat(base): Remember the inviter if we accept an invite 2025-07-12 10:57:48 +02:00
Richard van der Hoff 6209bc942c indexeddb: Remove incorrect line from changelog 2025-07-11 16:35:50 +02:00
Doug edd371b570 ffi: Refactor ClientBuilder::build_with_qr_code into Client::login_with_qr_code
The FFI's API now matches the SDK and allows for checks to be made on the Client before logging in.
2025-07-11 15:56:46 +02:00
dragonfly1033 817f32e15b test(sdk): added configurable login response builders for mock login endpoint. 2025-07-11 14:14:24 +02:00
dragonfly1033 30eb12ed2d test(sdk): change test_login_username_refresh_token to use MatrixMockServer 2025-07-11 14:14:24 +02:00
Damir Jelić 900697bc3b chore: Add a missing changelog entry for PR #5250 2025-07-10 17:23:21 +02:00
Damir Jelić 18b169ca7e chore: Release matrix-sdk version 0.13.0 2025-07-10 15:15:04 +02:00
Damir Jelić b9ce4059fb refactor(sqlite): Move the transaction in find_event_relations into a function 2025-07-10 14:23:10 +02:00
Damir Jelić e8dcb5d250 chore: Add a changelog entry for the fix for GHSA-275g-g844-73jh
Co-authored-by: Denis Kasak <dkasak@termina.org.uk>
Signed-off-by: Damir Jelić <poljar@termina.org.uk>
2025-07-10 13:55:02 +02:00
Damir Jelić d0c01006e4 fix(sqlite): Fix a SQL injection issue in the find_event_relations function
The SQLite implementation for the
EventCache::find_event_with_relations() the relation type list isn't
inserted using SQL placeholders.

The relation types are inserted manually using a format!() call. The
usage of the format!() call can lead to SQL injection if a
RelationType::Custom variant is used which contains SQL expressions.

This patch modifies the, query logic which retrieves the related events,
to use two separate queries which use SQL placeholders to insert all
the dynamic variables.

Security-Impact: Moderate
CVE: CVE-2025-53549
GitHub-Advisory: GHSA-275g-g844-73jh
2025-07-10 13:55:02 +02:00
Damir Jelić dc98bf7633 test: Add a test for GHSA-275g-g844-73jh 2025-07-10 13:55:02 +02:00
Doug ae57156252 ffi: Add reload_tracing_file_writer() to reconfigure the RollingFileAppender. 2025-07-10 13:21:42 +02:00
Doug 3b09c60e20 ffi: Wrap the tracing text layers inside a reload layer.
The generics have been removed from text_layers() to make this possible.

---------

Co-authored-by: Damir Jelić <poljar@termina.org.uk>
2025-07-10 13:21:42 +02:00
Ivan Enderlin fcdb63dcbe feat(ui): Add RoomListService::new_with_share_pos.
This patch adds the new `RoomListService::new_with_share_pos`
constructor. It decides whether the `share_pos` feature of sliding sync
should be enabled or not.

`SyncServiceBuilder` gains a new `with_share_pos` method to configure
the way the `RoomListService` is built.

The FFI bindings are updated accordingly.
2025-07-10 11:52:31 +02:00
Nico Steinle a095872083 fix(examples): Remove a duplicate comment from the examples
Signed-off-by: Nico Steinle <Nico-Steinle@t-online.de>
2025-07-09 18:42:22 +02:00
Denis Kasak d68895f24a Clarify project structure and status of internal crates (#5377)
Signed-off-by: Denis Kasak <dkasak@termina.org.uk>
Co-authored-by: Damir Jelić <poljar@termina.org.uk>
2025-07-09 14:47:38 +00:00
Michael Goldenberg ab81388018 test(indexeddb): add event cache store integration tests
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg c5436ed73e test(indexeddb): add IndexedDB-specific integration tests
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg 2e7721b36c feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::load_all_chunks
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg a514019d7c refactor(indexeddb): add helper fns for EventCacheStore::load_all_chunks
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg 2f8f39795f feat(indexeddb): add IndexedDB-backed impl for EventCacheStore::handle_linked_chunk_updates
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg b1ef15c346 refactor(indexeddb): add helper fns for EventCacheStore::handle_linked_chunk_updates
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg 829b6a7624 feat(indexeddb): add indexeddb event cache store impl (backed by memory store)
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg 7b2cd8e434 feat(indexeddb): add debug impl to serializers and event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg d567a45bee feat(indexeddb): add error type for communicating errors outside of module
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg 9c08cd8973 feat(indexeddb): add type for building IndexeddbEventCacheStore
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Michael Goldenberg e0ceef33f8 feat(indexeddb): add top-level type for implementing EventCacheStore
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-07-09 15:35:31 +02:00
Ivan Enderlin 72d133260c test(sdk): Test SendQueue::subscribe.
This patch updates the `assert_update` macro in the send queue test
suites to test that `SendQueue::subscribe` provides the same data that
`RoomSendQueue::subscribe`. It ensures `SendQueueUpdate` won't miss
an update.
2025-07-09 14:03:03 +02:00
Ivan Enderlin 91e0c76a2f feat(sdk): Introduce SendQueue::subscribe.
To get updates from the `SendQueue`, one needs to use
`RoomSendQueue::subscribe`, it emits `RoomSendQueueUpdate`s. However, if
one wants to receive updates for all rooms managed by the `SendQueue`,
instead of subscribing to all `RoomSendQueue` individually, this
patch introduces a new `SendQueue::subscribe` method, which emits
`SendQueueUpdate`s. It's basically a wrapper around
`RoomSendQueueUpdate` by adding an `OwnedRoomId`.
2025-07-09 14:03:03 +02:00
Ivan Enderlin 7fac1d246d doc(sdk): Update the CHANGELOG.md. 2025-07-09 12:43:09 +02:00
Ivan Enderlin 6762e70880 chore(sdk): Rename variants of RoomEventCacheGenericUpdate.
This patch renames variants of `RoomEventCacheGenericUpdate`:

- `TimelineUpdated` becomes `UpdateTimeline`,
- `Cleared` becomes `Clear`.

It matches the rest of the codebase where we use _verb_ + _subject_.
2025-07-09 12:43:09 +02:00
Ivan Enderlin 6b93f6698b feat(sdk): Add RoomEventCacheGenericUpdate::Cleared.
This patch adds the `RoomEventCacheGenericUpdate::Cleared` variant. It's
helpful to know when a room has been cleared.
2025-07-09 12:43:09 +02:00
Benjamin Bouvier c92a89d571 chore(sqlite): reorder methods and add doc comment for encode_key
This reorders methods so that they're grouped in "dual" pairs
(encode/decode, serialize/deserialize). Also adds a doc comment to
`encode_key`, as I've wondered in the past what it did.
2025-07-09 12:37:34 +02:00
Benjamin Bouvier 684f228e70 refactor(sqlite): share implementations of the encode/decode/serialize/deserialize sqlite store helpers 2025-07-09 12:37:34 +02:00
Ivan Enderlin 0f9faad48a doc(ffi,ui): Update the CHANGELOG.mds. 2025-07-09 12:31:22 +02:00
Ivan Enderlin d7550ec645 feat(ui): RoomListService::subscribe_to_rooms calls LatestEvents::listen_to_room.
This patch updates `RoomListService::subscribe_to_rooms` to call
`LatestEvents::listen_to_room` automatically. This method becomes async,
which propagates to a couple of callers.

The idea is that when one is interested by a specific room, a
subscription will be applied. This is an opportunity to also “activate”
the computation of the `LatestEvent` for this specific room, so that the
user doesn't have to do that manually (except if room subscription is
never used).
2025-07-09 12:31:22 +02:00
Ivan Enderlin ea5645869e feat(sdk): Add the request_duration log field in HttpClient::send_request.
This patch adds a new log field, named `request_duration` in
`HttpClient::send_request`. It helps to know how much time the request
took to be executed.
2025-07-09 12:19:34 +02:00
Ivan Enderlin 8eed17bbfd doc(sdk): Fix a typo in SlidingSyncInner::network_timeout. 2025-07-09 11:27:53 +02:00
Benjamin Bouvier 40c08335ee feat(multiverse): add support for read receipts 2025-07-09 11:05:09 +02:00
Benjamin Bouvier ae5ec0fa26 test(timeline): add a test for the initial filling of threaded read receipts 2025-07-09 11:05:09 +02:00
Benjamin Bouvier 880f754f32 test(timeline): add test for sending threaded read receipts 2025-07-09 11:05:09 +02:00
Benjamin Bouvier 4d23b6490d test(timeline): add test for read receipts updates received from sync 2025-07-09 11:05:09 +02:00
Benjamin Bouvier e0e531c737 test(timeline): add test for latest_user_read_receipt for a threaded-timeline 2025-07-09 11:05:09 +02:00
Benjamin Bouvier 82926d6f08 test(timeline): allow setting the timeline focus in TestTimeline 2025-07-09 11:05:09 +02:00
Benjamin Bouvier f45c9aa3a7 feat(timeline): support threaded read receipts 2025-07-09 11:05:09 +02:00
Benjamin Bouvier 7966dd0544 fix(timeline): when a threaded timeline has no read receipts, don't unset the unread flag 2025-07-09 11:05:09 +02:00
Kévin Commaille 54e6a7d8d1 Upgrade Ruma
This is a bugfix for the `compat-lax-room-create-deser` and
`compat-lax-room-topic-deser` features, which didn't work with events
in the wild.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-09 08:43:12 +02:00
Jonas Platte 995ec618df chore: Upgrade xtask and uniffi-bindgen to Rust edition 2024 2025-07-09 08:41:41 +02:00
Jonas Platte f9864b7ef4 refactor(ui): Use named return types over RPITs
… in private methods.
2025-07-09 08:38:38 +02:00
Jonas Platte d23eae262e refactor(ui): Inline a variable 2025-07-09 08:38:38 +02:00
Tobias Fella 52090bb199 docs(crypto): Remove wrong statement about encryption keys for OlmMachine::with_store
When using this function, whether encryption keys are dropped depends on the crypto store implementation used.
2025-07-09 08:32:31 +02:00
Valere 40e3cd3c22 changelog: add changelog for sending e2ee to-device with widgets 2025-07-08 15:40:05 +02:00
Ivan Enderlin a58a74eaa7 feat(sdk): LatestEventValue::None overwrites previous value.
This patch removes an optimisation that was considering
`LatestEventValue::None` as a value that should no overwrite the
previous value if any. This is a mistake: if the event cache is cleared,
it won't be possible to calculate a new value, and the previous value
must be overwritten.
2025-07-08 14:47:43 +02:00
Ivan Enderlin 1c549a3ca1 test(sdk): Test LatestEventValue is being updated. 2025-07-08 14:47:43 +02:00
Ivan Enderlin a7bef8870f feat(sdk): LatestEventValue implements Default. 2025-07-08 14:47:43 +02:00
Ivan Enderlin 5e946108fe feat(sdk): LatestEventValue represents all kind of suitable latest events.
This patch adds new variants to `LatestEventValue` that represent
all the possible suitable latest events. It's heavily inspired by
`matrix_sdk_base::latest_event::PossibleLatestEvent`. It uses the
new `find_and_map` method to find a suitable `TimelineEvent` and to
map it into a `LatestEventValue`. This method is heavily inspired by
`matrix_sdk_base::latest_value::is_suitable_for_latest_event`.

To be able to provide the `power_levels` to `find_and_map`, a
`WeakClient` is required by `LatestEvents::new`. It flows up to a
`WeakRoom` in `RoomLatestEvents`, used to create or to update the
`LatestEventValue`.

A particular care is applied to re-compute the `power_levels` only when
necessary and once **per room** (and not per latest event value).
Fetching the `power_levels` requires an access to the storage, it's
not anodyne.
2025-07-08 14:47:43 +02:00
Ivan Enderlin 34ccd26ee6 refactor(sdk): Rename RoomEventCache::rfind_event_in_memory_by to rfind_map_event_in_memory_by.
This patch changes `RoomEventCache::rfind_event_in_memory_by` to `rfind_map…`.
2025-07-08 14:47:43 +02:00
Ivan Enderlin 3eeb046e62 feat(skd): compute_latest_events calls the new LatestEvent::update method. 2025-07-08 14:47:43 +02:00
Ivan Enderlin 6f84a44a1c feat(sdk): Create LatestEventsError. 2025-07-08 14:47:43 +02:00
Ivan Enderlin cf16978b15 feat(sdk): RegisteredRooms gets a clone of EventCache. 2025-07-08 14:47:43 +02:00
Ivan Enderlin 6a30a802bb chore(sdk): Use std::fmt to simplify the code. 2025-07-08 14:47:43 +02:00
Benjamin Bouvier db477a84bf chore(tests): make new threads discovery deterministic 2025-07-08 10:20:30 +02:00
Benjamin Bouvier 96fbbd3cd8 fix(timeline): when reloading a fresh timeline, also reload the related events 2025-07-08 10:20:30 +02:00
Benjamin Bouvier bbbcec5963 chore(tests): make the tests independent to races with respect to initial values 2025-07-08 10:20:30 +02:00
Benjamin Bouvier df98b71836 fix(event cache): don't remove duplicated paginated events, if there's no new events 2025-07-08 10:20:30 +02:00
Benjamin Bouvier 0d901e4a86 fix(timeline): correctly update a thread root after a gappy sync 2025-07-08 10:20:30 +02:00
Benjamin Bouvier 9d7afaaa1c feat(timeline): clear a thread if a user has been ignored/unignored 2025-07-08 10:20:30 +02:00
Benjamin Bouvier 2fc616645f chore(tests): split the event cache integration test module into smaller files 2025-07-08 10:20:30 +02:00
Benjamin Bouvier b8f6ab066d test(timeline): add a test for local echo filtering in a threaded timeline 2025-07-08 10:20:30 +02:00
Benjamin Bouvier bb7e6cb562 fix(timeline): use the timeline handle to send a new reaction
This is more precise than using the event timeline item kind: indeed,
when the event for which we want to add a reaction is a local echo that
has been sent, it is still marked as a local echo, but the send queue
will not know about it, and thus will not be able to add the reaction
immediately, leading to a silent failure.

The `TimelineItemHandle` was made to help with this kind of situation:
in this case, it will return `TimelineItemHandle::Remote`, even though
the item is a local echo that has been sent; that way we can use the
event id, and correctly send a (remote) reaciton event immediately.

The following commit includes a regression test.
2025-07-08 10:20:30 +02:00
Benjamin Bouvier 3e81514d07 test(timeline): add a test that a related event comes to a threaded timeline 2025-07-08 10:20:30 +02:00
Benjamin Bouvier bfcf47743e chore(tests): add comments explaining what the timeline thread tests do 2025-07-08 10:20:30 +02:00
Kévin Commaille 69448cca61 Add changelog
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-08 09:25:26 +02:00
Kévin Commaille 5daf2922b7 refactor(sdk): Use SupportedVersions to cache the response of the /versions endpoint
Using this type will be mandatory in the next breaking release of Ruma,
that will gain support for recognizing unstable features. Besides, it
allows to cache the supported versions and features in a single
CachedValue, which makes more sense than separately because we always
get both at the same time in production.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-08 09:25:26 +02:00
Benjamin Bouvier c81a56c22b fix(doc): add a missing parameter to BaseClient::new() in a doctest 2025-07-07 16:18:45 +02:00
Benjamin Bouvier f891bd13cb chore(base): add changelog entry for the new parameter in BaseClient::new() 2025-07-07 16:18:45 +02:00
Benjamin Bouvier a50a570fc1 doc(ffi): update an oudated method doc comment 2025-07-07 16:18:45 +02:00
Damir Jelić ec112ca32d test(base): Test that we set the joined at timestamp 2025-07-07 12:36:23 +02:00
Damir Jelić 15fdf1e86e feat(base): Remember when a user explicitly accepted an invite 2025-07-07 12:36:23 +02:00
Damir Jelić 3d6d798ca3 docs(base): Document the room_joined() method a bit better 2025-07-07 12:36:23 +02:00
Benjamin Bouvier 935ffa5aea chore(multiverse): paginate fewer events, to better test the behavior of pagination 2025-07-07 11:40:18 +02:00
Benjamin Bouvier 1c19e7477c fix(event cache): when some thread events came from sync, don't consider we've reached the start if we haven't seen the root yet 2025-07-07 11:40:18 +02:00
Benjamin Bouvier 6a1576a085 refactor(timeline): make use of the threaded event cache in the timeline 2025-07-07 11:40:18 +02:00
Benjamin Bouvier a1f028c54a feat(event cache): add a linked chunk per thread and add some useful primitives 2025-07-07 11:40:18 +02:00
Kévin Commaille f2576e80ec Upgrade Ruma to latest release
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-07 11:08:44 +02:00
Ivan Enderlin e8f705d76f doc: Fix markup in README.md
This patch fixes the markup in the `README.md` file. Links were broken because of the mix of HTML and Markdown. Plus, the HTML markup was kind of incorrect. Plus, too much `<br />`, most of them were “collapsed” automatically.

Signed-off-by: Ivan Enderlin <ivan@mnt.io>
2025-07-07 10:17:14 +02:00
Kévin Commaille 049993d37e test(sdk): Port sliding-sync tests to MatrixMockServer and MockClientBuilder
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-07 09:42:47 +02:00
Kévin Commaille 14366e85b1 test(sdk): Port sliding-sync tests to MatrixMockServer and MockClientBuilder
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-07 09:42:47 +02:00
Kévin Commaille 849d705cd1 refactor(sdk): Port client tests to MatrixMockServer and MockClientBuilder
Because it's such a nicer API!

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-07 09:42:47 +02:00
Kévin Commaille d4adc81fe0 test(sdk): Allow to override the server versions and request config of MockClientBuilder
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-07 09:42:47 +02:00
Kévin Commaille 577a8feb12 refactor(sdk): Expose directly the URI of MatrixMockServer
Since there are several places that use it.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-07 09:42:47 +02:00
Kévin Commaille 7fb3d216f6 refactor(sdk): Take an Option<&str> in MockClientBuilder::new()
Usually tests that don't construct it via MockMatrixServer don't care
about the homeserver URL, so this allows to provide a default URL for
them.

Also we don't force to allocate a string when the inner API actually
uses a borrowed string.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-07 09:42:47 +02:00
Jonas Platte 07808b4301 refactor: Enable extra code style clippy lints 2025-07-05 21:20:34 +02:00
Kévin Commaille f9e7d16347 Upgrade Ruma
It seems that some `m.room.topic` events in the wild have the wrong
format for the `m.topic` field. Since this field was stabilized recently
in Ruma, deserializing these events now fails. We added a feature to
ignore this field if its deserialization fails.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-04 20:51:57 +02:00
Kévin Commaille c98b2a1b3f refactor(test): Change the bound on EventBuilder to StaticEventContent
The `EventContent` trait is gone in Ruma so this will ease the upgrade
to the next breaking release.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-04 12:13:22 +03:00
Stefan Ceriu b44a1e46c4 feat(base): ignore threaded messages when computing room read receipts and client wide threads feature flag
With the UI crate now sending threaded read receipts we need to start considering them when computing unread counts. As a first step before the participation model, threaded messages will be ignored when computing room unread counts.
2025-07-04 11:42:35 +03:00
Stefan Ceriu f17c3c5af4 feat(ui): send (un)threaded read receipts based on the current timeline instance's focus kind.
This patch moves away from always sending unthreaded read receipts to checking the timeline's focus and `hide_threaded_events` associated values to see whether `ReceiptThread::Main` or `ReceiptThread::Thread` should be used.
2025-07-04 11:42:35 +03:00
Kévin Commaille 5448192ea4 Upgrade Ruma
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-07-04 09:53:29 +02:00
Neil Johnson 74800e20b4 Update README to make Element sponsorship explicit 2025-07-03 18:06:18 +02:00
Benjamin Bouvier 8157193aef chore(ffi): adjust to uniffi-bindgen-go's expectations for types 2025-07-03 17:14:56 +02:00
Benjamin Bouvier 679c99aa76 refactor(notification): remove BatchNotificationFetchingResult abstraction
It's a hashmap!
2025-07-03 17:14:56 +02:00
Benjamin Bouvier 6fa76e4b12 refactor(notification): remove generic parameter in BatchNotificationFetchingResult 2025-07-03 17:14:56 +02:00
Benjamin Bouvier 8b33806496 refactor(notification): have NotificationClient::get_notifications also return statuses 2025-07-03 17:14:56 +02:00
Benjamin Bouvier 3d114aea50 refactor(notification): random tweaks here and there 2025-07-03 17:14:56 +02:00
Benjamin Bouvier 72dcf5ed46 refactor(ffi): return some error info when a single notification couldn't be obtained 2025-07-03 17:14:56 +02:00
Benjamin Bouvier 58748bec3a chore(ffi): tweak alias names in the FFI layer
It doesn't make sense to name a thing "Matrix" when it comes from the
core SDK crate.

Also adjust a now slightly-incorrect doc comment for `get_notification`.
2025-07-03 17:14:56 +02:00
Benjamin Bouvier f0b6225e40 feat(notifications): provide the NotificationStatus as the return type when getting notifications
This is more explicit for these API's users, which can decide to do
different things based on whether an event has been ignored, or filtered
out.
2025-07-03 17:14:56 +02:00
Benjamin Bouvier 17a58684f6 refactor(notification client): reduce indent again, and make use of Option::is_some_and 2025-07-03 17:14:56 +02:00
Benjamin Bouvier f8c468d6fa refactor(notification client): reduce indent in get_notifications_in_sliding_sync
No functional changes, only reducing indent.
2025-07-03 17:14:56 +02:00
Benjamin Bouvier 39d1ed9bc6 chore: exclude the room id / event id from the data to be sent to sentry
These are not included in Element's main privacy policy, and may
constitute PII (because the homeserver may include the name of some
user). We keep the information as separate log lines, so that
rageshakes/manual reports still include those.
2025-07-03 16:07:46 +02:00
Benjamin Bouvier 3d1d1c8f6d feat(state store): send deserialization errors to sentry \o/ 2025-07-03 16:07:46 +02:00
Benjamin Bouvier 5ad958722f feat(state store): include serde json error path when failing to deserialize in the state store 2025-07-03 16:07:46 +02:00
Benjamin Bouvier bedcbfd7ff fix(event cache): don't return an error when a linked chunk is empty
The metadata loading shouldn't cause an error to be displayed, when the
linked chunk is empty; this can happen for new rooms we've never
visited.

Spotted while investigating some failures in a rageshake.
2025-07-03 14:34:27 +02:00
Benjamin Bouvier 743dec9a65 chore(docs): fix a doc comment referring to the wrong type 2025-07-02 15:47:59 +02:00
Ivan Enderlin f1a2093cfc fix(ui): Avoid calling TimelineEvent::raw() twice.
This patch replaces two successive calls to `TimelineEvent::raw()` by a
single one.
2025-07-02 15:45:29 +02:00
Ivan Enderlin 8057991aee fix(sdk): Don't call event.raw() twice.
This patch replaces a second call to `event.raw()` by re-using the
`raw_event` variable.
2025-07-02 15:45:29 +02:00
Ivan Enderlin d45ef567d4 test(sdk): Add a new test for RoomEventCache::rfind_event_in_memory_by. 2025-07-02 14:44:21 +02:00
Ivan Enderlin 42ee967b46 feat(sdk): Add RoomEventCache::rfind_event_in_memory_by.
This patch introduces a new method named
`RoomEventCache::rfind_event_in_memory_by` to look for an in-memory
event, starting from the most recent event, by applying a predicate
closure on each event.
2025-07-02 14:44:21 +02:00
Ivan Enderlin 4c7575bc9e refactor(sdk): Rename RoomEventCache::event_with_relations to find_event_with_relations.
This patch renames the `RoomEventCache::event_with_relations` method to
`find_event_with_relations` for the sake of clarity, also to match the
other method names, and to match the Rust standard library namings.
2025-07-02 14:44:21 +02:00
Ivan Enderlin 5e927f8109 refactor(sdk): Rename RoomEventCache::event to RoomEventCache::find_event.
This patch renames the `RoomEventCache::event` method to `find_event` to
clarify what it does, and to match the Rust standard library namings.
2025-07-02 14:44:21 +02:00
Ivan Enderlin f91ee36245 doc(sdk): Fix a typo in the documentation. 2025-07-02 14:44:21 +02:00
Benjamin Bouvier 0f8fc53019 chore(ci): use the dev profile when building the swift bindings (#5328)
The swift bindings aren't getting tested (they don't run) in CI anymore,
so building with the reldbg profile (that's a workaround to make it run
and not crash in production) doesn't provide more value than building in
debug mode, while taking much longer to build.

Let's use the default dev profile for this; we have to specify it
manually, because the default for the xtask command is to use the
`reldbg` profile otherwise.

This requires a fix for the dev profile, that consists in being able to
set the iOS deployment target, and set it to a high value in CI
settings. Production builds *don't* have to set it, though.
2025-07-02 14:20:53 +02:00
Benjamin Bouvier be3af5e0d4 refactor(event cache): push down absence of gap handling in back-paginations
This will be useful to do for threaded paginations too.
2025-07-02 12:43:42 +02:00
Benjamin Bouvier 38bbdf0547 doc(event cache): tweak outdated comment 2025-07-02 12:43:42 +02:00
Benjamin Bouvier b188a157af refactor(event cache): inline most uses of EventLinkedChunk::push_events
The only remaining uses outside the `EventLinkedChunk` are in tests of
deduplication, so keep the method as a test-only method for now.
2025-07-02 12:43:42 +02:00
Benjamin Bouvier 9ccbac0c0e refactor(event cache): inline and remove from public API remove_empty_chunk_at 2025-07-02 12:43:42 +02:00
Benjamin Bouvier 137fc9cfbb refactor(event cache): remove EventLinkedChunk::push_gap from the public API
it's only used internally (and in tests), and it's not doing much, so we
can inline it as call sites instead.
2025-07-02 12:43:42 +02:00
Benjamin Bouvier 40a4c9a7e1 refactor(event cache): move pushing the live events into its own method in EventLinkedChunk 2025-07-02 12:43:42 +02:00
Benjamin Bouvier ad358955fd refactor(linked chunk): simplify remove_item_at 2025-07-02 12:43:42 +02:00
Benjamin Bouvier 0ee89c86ab refactor(event cache): remove methods that are plain private wrappers
These two methods could be only made private now, since they're only
used in `finish_back_pagination` (and in tests). But they only call
inside other methods of the underlying linked chunk without any extra
value, so they can be inlined instead. This reduces the public API and
removes tests for other APIs that were tested some place else.
2025-07-02 12:43:42 +02:00
Benjamin Bouvier 216f0df945 refactor(linked chunk): invert the position of insert_items_at parameters
Same logic as `replace_gap_at`.
2025-07-02 12:43:42 +02:00
Benjamin Bouvier 129e9e173e refactor(event cache): move finishing a network paginations in a EventLinkedChunk method 2025-07-02 12:43:42 +02:00
Benjamin Bouvier f7df0ebf97 refactor(event cache): change order of parameters in replace_gap
"Replace *this* gap with *these* events" read more natural to me than
"replace with *these* events *this* gap".
2025-07-02 12:43:42 +02:00
Benjamin Bouvier 2f78701374 refactor(event cache): move order of parameters in filter_duplicate_events 2025-07-02 12:43:42 +02:00
Benjamin Bouvier 872bded711 refactor(event cache): rename room_event names to linked_chunk or room_linked_chunk where it makes sense 2025-07-02 12:43:42 +02:00
Benjamin Bouvier 5196298e5f refactor(event cache): rename RoomEvents to EventLinkedChunk 2025-07-02 12:43:42 +02:00
Johannes Marbach 308526a6bc feat(ffi): expose timestamp and identifier on EmbeddedEventDetails
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-02 12:38:53 +02:00
Johannes Marbach 12f94a3fd2 feat(ui): expose timestamp and identifier on EmbeddedEvent
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-07-02 12:38:53 +02:00
Benjamin Bouvier 3c873262c7 fix(event cache): disable order assertions entirely
Until we figure out some panics in production this has caused.
2025-07-02 12:18:29 +02:00
Benjamin Bouvier 9689c4a40a feat(ffi): add a new log pack for the notification client 2025-07-02 10:52:55 +02:00
Benjamin Bouvier 57e7ae488e chore(ui): tweak the notification client logs 2025-07-02 10:52:55 +02:00
Jade Ellis a9ffe5fd72 chore: Update rusqlite 2025-07-01 21:25:15 +02:00
Damir Jelić 59c29801e5 refactor: Remove some useless cfg guards
The whole module is behind a e2e-encryption feature guard, so those
individual ones in the module are not useful.
2025-07-01 14:32:53 +02:00
Ivan Enderlin 0a822c1a06 fix(sdk): EventCache::for_room returns an error when room isn't found.
This patch fixes `EventCache::for_room` to return an error when the room
isn't found. Additionally, it also returns an error when the `Client`
(actually the `WeakClient`) is dropped.

These errors were “hidden” behind the room version logic because of
the fallback. The code has been rewritten in a way it makes it harder to
do it again.
2025-07-01 14:31:01 +02:00
Valere Fedronic 4b5e1c6676 feat(widget): Add support for the widget to send encrypted to-device messages
This patch adds support for widgets to send encrypted to-device messages as described in MSC3819.

MSC3819: https://github.com/matrix-org/matrix-spec-proposals/pull/3819
2025-07-01 14:13:31 +02:00
Benjamin Bouvier ecb9d4d2e8 refactor(timeline): remove fields from TimelineFocusKind that are used only to init the focus 2025-07-01 14:06:57 +02:00
Benjamin Bouvier 9ade32fcd0 refactor(timeline): remove generic from a few function signatures by using plain bools 2025-07-01 14:06:57 +02:00
Benjamin Bouvier 8b4a01ea54 refactor(timeline): pass TimelineSettings immediately when creating a Timeline 2025-07-01 14:06:57 +02:00
Benjamin Bouvier d5d5b9ee01 refactor(timeline): move the crypto tasks spawning to decryption_retry_task too
This will make it easier to move all the code around, when needs be.
2025-07-01 14:06:57 +02:00
Benjamin Bouvier a3dd594c9e refactor(timeline): move the crypto drop handles to their own data structure
And put it in the `decryption_retry_task`, so it can be moved
altogether, later, to the event cache or some place else.
2025-07-01 14:06:57 +02:00
Benjamin Bouvier 98c331466e doc(timeline): beef up comments for the long-lived tasks 2025-07-01 14:06:57 +02:00
Benjamin Bouvier e8877fd987 refactor(timeline): move long-lived tasks to a new tasks mod
Only code motion.
2025-07-01 14:06:57 +02:00
Benjamin Bouvier babf16f15a refactor(timeline): use the num_events parameter for a thread back-pagination
And not the initial `num_events` parameter used for the initial
pagination.
2025-07-01 14:06:57 +02:00
Benjamin Bouvier 000419cdf3 refactor(timeline): rename TimelineFocusData to TimelineFocusKind 2025-07-01 14:06:57 +02:00
Benjamin Bouvier 89d661ca8c refactor(timeline): get rid of TimelineFocusKind \o/ 2025-07-01 14:06:57 +02:00
Benjamin Bouvier 1624d798ee refactor(timeline): replace remaining uses of TimelineFocusKind with TimelineFocusData 2025-07-01 14:06:57 +02:00
Benjamin Bouvier 726218000a refactor(timeline): add TimelineFocusKind's fields to TimelineFocusData
This will make it possible to get rid of `TimelineFocusKind`!
2025-07-01 14:06:57 +02:00
Benjamin Bouvier 08dcb267b3 refactor(timeline): use the TimelineFocusData when processing relations 2025-07-01 14:06:57 +02:00
Benjamin Bouvier da0a32b088 refactor(timeline): use the TimelineFocusData to update the skip count 2025-07-01 14:06:57 +02:00
Benjamin Bouvier e22a833057 refactor(timeline): add a TimelineFocusData to TimelineState and TimelineStateTransaction 2025-07-01 14:06:57 +02:00
Benjamin Bouvier 8aba664578 refactor(timeline): get rid of internal locking for TimelineFocusData
Turns out it's not needed, because all the internal data structures
already use inner mutability patterns.
2025-07-01 14:06:57 +02:00
Benjamin Bouvier e117a3d22f fix(sdk): use a cfg guard instead of if cfg! to avoid build failures on !test && !debug_assertions builds 2025-07-01 12:11:09 +02:00
Andy Balaam c2f50fd8a5 doc(crypto): Attempt to explain what handle_to_device_event does and make all types explicit 2025-07-01 11:25:03 +02:00
Ivan Enderlin dc90c77c7d feat(sdk): Introduce the LatestEvents API.
This patch is the first part of the new `LatestEvents` API. It contains
the “framework”, i.e. the structure, tasks, logic to make it work, but
no latest events are computed for the moment.

The Latest Events API provides a lazy, reactive and efficient way to
compute the latest event for a room or a thread.

The latest event represents the last displayable and relevant event
a room or a thread has been received. It is usually displayed in a
_summary_, e.g. below the room title in a room list.

The entry point is `LatestEvents`. It is preferable to get a reference
to it from `Client::latest_events`, which already plugs everything to
build it. `LatestEvents` is using the `EventCache` and the `SendQueue`
to respectively get known remote events (i.e. synced from the server),
or local events (i.e. ones being sent).

\## Laziness

`LatestEvents` is lazy, it means that, despites `LatestEvents`
is listening to all `EventCache` or `SendQueue` updates, it will
only do something if one is expected to get the latest event for a
particular room or a particular thread. Concretely, it means that until
`LatestEvents::listen_to_room` is called for a particular room, no
latest event will ever be computed for that room (and similarly with
`LatestEvents::listen_to_thread`).

If one is no longer interested to get the latest event for a
particular room or thread, the `LatestEvents::forget_room` and
`LatestEvents::forget_thread` methods must be used.

\## Reactive

`LatestEvents` is designed to be reactive. Use
`LatestEvents::listen_and_subscribe_to_room` (same for thread) to get
a `Subscriber`.
2025-07-01 10:52:32 +02:00
Ivan Enderlin 6c9038eb4f refactor(sdk,common): Move JoinHandleExt inside matrix-sdk-common.
This patch moves the `JoinHandleExt` trait and the
`AbortOnDrop` type from `matrix_sdk::sliding_sync::utils` into
`matrix_sdk_common::executor`. This is going to be useful for other
modules.
2025-07-01 10:52:32 +02:00
dependabot[bot] 2b9b4cc589 chore(deps): bump crate-ci/typos from 1.33.1 to 1.34.0
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.33.1 to 1.34.0.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.33.1...v1.34.0)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.34.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-01 08:32:45 +03:00
Ivan Enderlin dd0336ee72 test(ui): Update test_sync_indicator and make it non-flaky.
This patch updates `test_sync_indicator` since the `SyncIndicator`
is shown for the `SettingUp` state. Also, this patch makes this
test non-flaky entirely by changing the `sync::mpsc::channel` to a
`sync::Barrier`.
2025-06-30 16:55:17 +02:00
Ivan Enderlin 0095912091 doc(ui): Update the documentation to be in-sync with the code. 2025-06-30 16:55:17 +02:00
Ivan Enderlin e6774a34da feat(ui): Show the sync indicator when RoomListService is in SettingUp state.
Since `RoomListService` uses a persistent `pos` for sliding sync, the
`SyncIndicator` no longer shows its face except if the sliding sync
session doesn't exist or has expired.

This patch changes that by extending the `Show` from `Init` to
`SettingUp`.
2025-06-30 16:55:17 +02:00
Kévin Commaille 8ad52e34ea refactor: Don't use AnyMessageLikeEventContent with the event factory
When we upgrade Ruma, the `EventContent` bound on `EventBuilder` will be
changed to `StaticEventContent`, which is not implemented by the
`Any*EventContent` enums.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-30 16:44:14 +02:00
Ivan Enderlin 60a7bf0c3f doc(sdk): Fix a typo in the documentation of EventCacheDropHandles.
This patch fix a typo in the documentation of `EventCacheDropHandles`:
`EventCache` starts the tasks, not `RoomEventCache`.
2025-06-30 16:41:40 +02:00
Benjamin Bouvier 8b31d8f6a3 test(event cache): add an integration test for the ordering of relations 2025-06-30 16:10:49 +02:00
Benjamin Bouvier e21dd763e8 feat(event cache): return related events sorted by their position in the linked chunk 2025-06-30 16:10:49 +02:00
Benjamin Bouvier 31df84f5a1 feat(event cache): return the event's positions in find_event_relations 2025-06-30 16:10:49 +02:00
Benjamin Bouvier e68bdf8460 refactor(linked chunk): shortcut if there's no events at the top of MemoryStore::filter_duplicate_events
And remove useless comments.
2025-06-30 16:10:49 +02:00
Benjamin Bouvier 6ca1f16f48 refactor(linked chunk): make events iteration order deterministic in the relational linked chunk 2025-06-30 16:10:49 +02:00
Benjamin Bouvier 8c5d878172 refactor(linked chunk): simplify API of RelationalLinkedChunk::items()
One must now specify the target linked chunk; both callers would filter
out items based on this after the fact, which is a bit overkill since
most items would thus be filtered out on the sinking end.
2025-06-30 16:10:49 +02:00
Benjamin Bouvier d6239d614a refactor(test): reflect that unordered events can come, well, unordered 2025-06-30 16:10:49 +02:00
Benjamin Bouvier 5af084c8c9 refactor(test): don't make test_filter_duplicated_event rely on the position in the duplicate set 2025-06-30 16:10:49 +02:00
Benjamin Bouvier dc450ac25a refactor(linked chunk): rejigger the relational linked chunk to include the position of items 2025-06-30 16:10:49 +02:00
Benjamin Bouvier cf375dd753 refactor(linked chunk): don't try to find events or related events in any linked chunk, only the room one 2025-06-30 16:10:49 +02:00
Benjamin Bouvier ff935df136 refactor(linked chunk): don't nest internal methods 2025-06-30 16:10:49 +02:00
Jonas Richard Richter 0d080935cf chore(changelog): add pull request reference for NotificationItem room topic addition 2025-06-30 11:26:17 +01:00
Jonas Richard Richter 4d140d8155 feat(notification): add room topic to NotificationItem and NotificationRoomInfo structs 2025-06-30 11:26:17 +01:00
Benjamin Bouvier cef1f8c5cb chore(event cache): address review comments 2025-06-30 11:09:11 +02:00
Benjamin Bouvier 6a054d6c74 refactor(event cache): use the linked chunk metadata to construct the OrderTracker 2025-06-30 11:09:11 +02:00
Benjamin Bouvier 1f89efb88d feat(event cache store): add a method to return the chunks' metadata 2025-06-30 11:09:11 +02:00
Benjamin Bouvier e83c09e425 refactor(event cache): regroup lazy-loading methods in the same impl block 2025-06-30 11:09:11 +02:00
Benjamin Bouvier a85dac1f52 feat(event cache): introduce an OrderTracker for each room tracked by the event cache
The one hardship is that lazy-loading updates must NOT affect the order
tracker, otherwise its internal state will be incorrect (disynchronized
from the store) and thus return incorrect values upon shrink/lazy-load.

In this specific case, some updates must be ignored, the same way we do
it for the store using `let _ = store_updates().take()` in a few places.

The author considered that a right place where to flush the pending
updates was at the same time we flushed the updates-as-vector-diffs,
since they would be observable at the same time.
2025-06-30 11:09:11 +02:00
Benjamin Bouvier a0bc9aafcf feat(linked chunk): introduce an OrderTracker to keep track of the ordering of the current items
This is a new data structure that will help figuring out a local,
absolute ordering for events in the current linked chunk. It's designed
to work even if the linked chunk is being lazily loaded, and it provides
a few high-level primitives that make it possible to work nicely with
the event cache.
2025-06-30 11:09:11 +02:00
Benjamin Bouvier 8217f967d4 doc(linked chunk): explain briefly what the reattaching/detaching flags are doing 2025-06-30 11:09:11 +02:00
Benjamin Bouvier 47c9585606 refactor(linked chunk): generalize UpdateToVectorDiff to handle different accumulators
In the next patch, we're going to introduce another user of
`UpdatesToVectorDiff` which doesn't require accumulating the
`VectorDiff` updates; so as to make it optional, let's generalize the
algorithm with a trait, that carries the same semantics.

No changes in functionality.
2025-06-30 11:09:11 +02:00
Benjamin Bouvier 20e09531fb refactor(sdk): move the common pagination types to the paginators root mod 2025-06-30 10:48:27 +02:00
Benjamin Bouvier d92b33f959 refactor(sdk): move the ThreadedEventsLoader into the sdk's paginators module
A bit of code motion, sprinkling a new interface here, adjusting
expectations in the timeline, and we're all set 👌
2025-06-30 10:48:27 +02:00
Benjamin Bouvier a74bcfab8f refactor(sdk): move the room Paginator outside of the event cache
It doesn't belong there anymore, because it's not used within the event
cache itself. It's used in the timeline, and I think it's nice to keep
it available for external users as well, so it now lives in its own
`matrix-sdk/src/paginators` module. Next step is to move the thread
loader in there as well.
2025-06-30 10:48:27 +02:00
Benjamin Bouvier 6dcc744b48 refactor(event cache): remove unused impl of PaginableRoom for WeakRoom 2025-06-30 10:48:27 +02:00
Benjamin Bouvier 9d1c296657 doc(ffi): fix incorrect reference to a function that's been renamed 2025-06-30 10:48:27 +02:00
Damir Jelić 3c7683ea53 chore(sdk): Add a missing dot 2025-06-30 09:53:47 +02:00
Jonas Platte cd03a58083 refactor(examples): Use if-let chains in oauth_cli 2025-06-29 20:58:05 +02:00
Jonas Platte 4a1249fa96 chore(examples): Upgrade to Rust edition 2024 2025-06-29 20:58:05 +02:00
Kévin Commaille 06732ca71a refactor(common): Use a constant for the room version to use as a fallback
It avoids using different versions in several places for consistency. It
also allows to be able to change it in a single place when needed.

This also bumps the fallback to v11 everywhere, since it is the default
version for new rooms since Matrix 1.14 and it has the sanest redaction
rules.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-29 16:59:37 +02:00
Jonas Platte 115c7578d4 refactor(multiverse): Rewrite condition for readability 2025-06-29 09:42:27 +02:00
Jonas Platte 9f3e7debb1 refactor(multiverse): Use let chains 2025-06-29 09:42:27 +02:00
Jonas Platte 58d2ae4c39 chore(multiverse): Upgrade to Rust edition 2024 2025-06-29 09:42:27 +02:00
Kévin Commaille 8a847a99d4 ci: Bump the version of Rust nightly
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-28 09:47:28 +02:00
Jonas Platte 3d642356c6 refactor: Clean up formatting in many places
Process:
- set style_edition to 2024 in .rustfmt.toml
- run `cargo fmt`
- undo .rustfmt.toml change
- run `cargo fmt` again
- manually rewrap some strings
2025-06-27 19:54:13 +02:00
Kévin Commaille b4b0f3a203 refactor(sdk): Remove fallback support for the /auth_issuer endpoint
The `/auth_metadata` endpoint has been supported by Synapse for 6 months
now so there shouldn't be any homeserver that still depend exclusively
on it. This endpoint is also part of Matrix 1.15.

Support for this endpoint has been removed from Ruma so this is
necessary before an upgrade of the dependency.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-27 17:24:30 +00:00
Kévin Commaille ca99977207 ui: Inline format! args
Detected by lint clippy::uninlined_format_args.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-27 19:04:00 +02:00
Kévin Commaille dd02274883 base: Avoid clone in test
Detected by lint clippy::cloned_ref_to_slice_refs.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-27 19:04:00 +02:00
Kévin Commaille ad2e3a3b8f common: Put UpdatesSubscriber behind test cfg
Since it is only used in tests, it is now detected as dead code.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-27 19:04:00 +02:00
Kévin Commaille 96119f9a30 crypto: Use Ord implementation of SequenceNumber for its PartialOrd implementation
Detected by lint clippy::non_canonical_partial_ord_impl.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-27 19:04:00 +02:00
Damir Jelić 737e06b581 Add a missing changelog entry for PR 5177 2025-06-27 14:54:21 +02:00
Richard van der Hoff 4ecd599c15 fix(sdk): correctly import e2ee history in join_room_by_id (#5284)
It turns out that downstream clients can and do call
`Client::join_room_by_id()` rather than `Room::join`, so we need to do
the room key history import in the lower-level method.

---------

Signed-off-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
Co-authored-by: Benjamin Bouvier <benjamin@bouvier.cc>
2025-06-27 12:29:01 +01:00
Doug c6521a8aaf ffi: Remove the ElementWellKnown struct and related function. 2025-06-27 12:00:33 +02:00
Benjamin Bouvier 4046a59786 refactor(event cache): make filter_duplicate_events operate on a linked chunk id 2025-06-26 16:23:39 +02:00
Benjamin Bouvier d931cd0ea7 refactor(event cache): include non_empty_all_duplicates in the DeduplicationOutcome 2025-06-26 16:23:39 +02:00
Benjamin Bouvier a14488617e refactor(common): don't parse the full bundled latest thread event, but only its type
The previous code would parse the entire bundled event, only to look at
its type indirectly. We can do better than this, and only look at the
type instead. This brings a few benefits:

- it is faster, as we don't have to deserialize the entire event
- while the spec seems to indicate that the latest thread event has a
  `room_id`, it seems that, under some circumstances, it does not, as
  indicated by some rageshakes. As such, not parsing as `AnyMessageLike`
  (which mandates a room id) makes it more robust to the absence of a
  room id in there, marking more events as latest events.
2025-06-26 15:33:26 +02:00
Jorge Martín 1de51614f1 fix: Add m.room.avatar to the required state
This works around the issue with removed avatars not being explicitly flagged by sliding sync until https://github.com/element-hq/synapse/issues/18598 is fixed
2025-06-26 14:21:00 +02:00
Robin 6cc98ee9f7 feat(widget): Allow Element Call to learn the room name
The latest mobile designs for Element Call have it displaying the room name in an "app bar". So the Element Call widget will soon start requesting the capability to learn the room name, and the SDK should auto-approve this capability.
2025-06-26 13:28:34 +02:00
Damir Jelić 3a98d46bfa feat: Add a stream to listen for historic room key bundles 2025-06-26 13:22:24 +02:00
Damir Jelić 1558858bde chore: Add a TODO item reminding us that we should zeroize room key bundle contents 2025-06-26 13:22:24 +02:00
Damir Jelić e4d2f62d48 docs: Document the store/types module properly 2025-06-26 12:11:16 +02:00
Benjamin Bouvier 70f48be582 refactor(sliding sync): avoid an unwrap by inlining a function into its one caller 2025-06-26 12:08:43 +02:00
Ivan Enderlin 836c643769 doc(indexeddb): Add documentation about IndexedKeyBounds and IndexedKeyComponentBounds. 2025-06-25 16:17:34 +02:00
Michael Goldenberg a48099d5ac refactor(indexeddb): add function to transaction type for clearing all data from an object store in IndexedDB
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 09d8be7b4c doc(indexeddb): add docs to transaction type where they are missing
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 03b8cabc22 refactor(indexeddb): add functions to transaction type for deleting data from IndexedDB
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 07372c475c refactor(indexeddb): add functions to transaction type for adding data to IndexedDB
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg a00e4089e8 refactor(indexeddb): add functions to transaction type for getting data out of IndexedDB
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 1a24b21d42 refactor(indexeddb): add type to represent IndexedDB transactions specific to event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg f51496fa0f refactor(indexeddb): track corresponding index for type in IndexedKey trait
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg c6ce9c560b refactor(indexeddb): track corresponding object store for type in Indexed trait
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 60af16ada8 refactor(indexeddb): add function for encoding key range from key component range
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 159fb73b0a refactor(indexeddb): join key range encoding functions using indexed key range enum
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 0fa0f2329d refactor(indexeddb): add enum for representing ranges over indexed keys
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 3b64d18c99 refactor(indexeddb): move key component bounds into a separate trait
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg f67fd87e57 refactor(indexeddb): rename IndexedKeyBounds fn's so they are consistent
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg 5e64da660c refactor(indexeddb): add default impls for IndexedKeyBounds::{encode_lower, encode_upper}
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg d152ce13a0 refactor(indexddb): add fn's to IndexedKeyBounds to get bounds of key components
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Michael Goldenberg d021020ee6 refactor(indexeddb): use generic type rather than dynamic type in serializer error
This prevents us from having to add type constraints on the dynamic type
and instead only having to specify the type constraint at the call site.

Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-25 16:17:34 +02:00
Timo 7e5f22ba9e feat(widgets) Add backwards compatibility hide_header for element-call url query parameter 2025-06-25 16:12:28 +03:00
Timo 6bc6ea4e72 feat(widgets): Update the widget url parameters to use the new header property (was hideHeader which is now deprecated) 2025-06-25 16:12:28 +03:00
Timo 585ae29868 refactor(uniffi): make the sdk widget config struct derive uniffi.
This allows to not duplicate the struct in the uniffi crate.
2025-06-25 16:12:28 +03:00
Benjamin Bouvier 3919c2a89a feat(ffi): also disable the send queues when clearing caches
And beef up the doc comment.
2025-06-25 14:32:25 +02:00
Benjamin Bouvier 7c85e7aa4f feat(room list service): allow to manually expire sessions
This can be used to invalidate the persisted state on disk related to
the sliding sync positions. It's useful to do so when clearing up all
the caches, since the sliding sync `pos`itions are stored in the crypto
store (to benefit from the cross-process lock).
2025-06-25 14:32:25 +02:00
Benjamin Bouvier 4b845e17c8 feat(sliding sync): also empty the list caches when expiring a session 2025-06-25 14:32:25 +02:00
Benjamin Bouvier 394124cda5 refactor(sliding sync): rename invalidate_cached_list to remove_cached_list 2025-06-25 14:32:25 +02:00
Benjamin Bouvier bbf9bf2c0b feat(room list service): skip the initial state when an initial pos is set 2025-06-25 14:32:25 +02:00
Benjamin Bouvier 67327a0365 doc(sliding sync): remove dubious doc comment
It speaks of a time where the `storage_key` was optional, and it's also
a private field, so it's doubly confusing.
2025-06-25 14:32:25 +02:00
Benjamin Bouvier 5e40426b99 refactor(sliding sync): don't eagerly reload sliding sync state if it's unused 2025-06-25 14:32:25 +02:00
Ivan Enderlin 0f264cac6e feat(ui): RoomListService re-enables share_pos. 2025-06-25 14:32:25 +02:00
Andy Balaam 3c1d0b37e5 refactor(crypto): Provide a specific error type for to-device events from dehydrated devices
This will get more usage soon, when we add a variant for events with
unverified senders.
2025-06-25 12:05:14 +01:00
Stefan Ceriu 62231878cc fix(ffi): make RoomInfo power levels optional as they can be missing depending on the required state
The `m.room.power_levels` state event is not part of the room list required state and computing the RoomInfo would fail in that case.
2025-06-25 12:41:33 +03:00
Benjamin Bouvier 22c99f30f3 chore(sdk): fill in the pull request numbers in changelogs
Signed-off-by: Benjamin Bouvier <benjamin@bouvier.cc>
2025-06-25 10:32:01 +02:00
Benjamin Bouvier a7efff9849 chore: add changelog entries 😅 2025-06-25 10:32:01 +02:00
Benjamin Bouvier bc9192f818 refactor!(sdk): make the join_rule and related getters optional
The join rule state event can be missing from a room state. In this
case, it's an API footgun to return a default value; instead, we should
return none and let the caller decide what to do with missing
information.
2025-06-25 10:32:01 +02:00
Richard van der Hoff 0722ed9d8f Indexeddb: support for received room key bundles
Add a new store to keep track of the information we have received about room
key bundles.
2025-06-25 10:26:11 +02:00
Valere Fedronic 1aa933cfd6 widgets: Filter out crypto related fields of raw decrypted to-device
Ensure that only sender/type/content are exposed to the widgets, and not the crypto-related fields.
2025-06-24 16:04:52 +02:00
Ivan Enderlin e0ab16f979 chore(sdk): Address feedback. 2025-06-24 15:14:57 +02:00
Ivan Enderlin a9c999af72 doc(sdk): Precise when the side-effect of RoomEventCacheSubscriber happens. 2025-06-24 15:14:57 +02:00
Ivan Enderlin 8156413132 feat(sdk): Introduce RoomEventCacheGenericUpdate, one channel to get update of all rooms.
`RoomEventCache::subscribe` is nice to subscribe to every update
happening inside a room in the event cache. However, the returned
`RoomEventCacheSubscriber` has side-effects when dropped (see
auto-shrink to save memory space). In some situation, this is pretty
annoying. for example, if one wants to listen to multiple room updates,
all the room event cache subscribers must be kept in memory, thus
breaking the side-effects. This isn't always the desired output. In
addition, listening to multiple channels/subscribers at the same is
quite complex, as it implies non-trivial async runtime efforts or
complex future types.

To solve this problem, this patch introduces a new
`EventCache::subscribe_to_room_generic_updates` method, which returns a
single `Receiver<RoomEventCacheGenericUpdate>`.

First off, it hides the details of `RoomEventCacheUpdate` (returned by
`RoomEventCacheSubscriber`), which might be desired, but particularly
lighter because events aren't part of the payload.

Second, one no longer needs to subscribe to all rooms. Only one channel
can be listened to get updates for all rooms. It reduces the complexity
on the caller side, plus `Receiver<RoomEventCacheGenericUpdate>` doesn't
have any side-effect.

This patch tests this feature in 4 situations:

1. when a room is created/loaded empty,
2. when a room is loaded and is not empty because data exists in the storage,
3. when a room receives data from the sync,
4. when a room receives data from the pagination.
2025-06-24 15:14:57 +02:00
Ivan Enderlin e551efec8d doc(sdk): Fix comment of RoomEventCacheState::handle_sync.
This patch fixes a comment about `RoomEventCacheState::handle_sync`
returned values.
2025-06-24 15:14:57 +02:00
Benjamin Bouvier 877a7d678f fix(notification client): request the join rules so as to be able to compute them 2025-06-24 14:34:54 +02:00
Daniel Salinas 457af2a2f8 feat(wasm): Remove network config features from ffi ClientBuilder for Wasm (#5248)
<!-- description of the changes in this PR -->
Features to configure UserAgent, Proxy, Disabling SSL, and additional
certificates are not available on Wasm platforms. We remove these
configuration options from the FFI layer, while preserving them on
non-Wasm platforms.

- [ ] Public API changes documented in changelogs (optional)

<!-- Sign-off, if not part of the commits -->
<!-- See CONTRIBUTING.md if you don't know what this is -->
Signed-off-by: Daniel Salinas

---------

Co-authored-by: Daniel Salinas <danielsalinas@Daniels-MacBook-Pro-2.local>
2025-06-24 14:22:43 +02:00
Andy Balaam 7b38c442c7 refactor(crypto): Hold a DecryptionSettings in base Client
Previously, we held a TrustRequirement inside Client, and had to wrap it
in a DecryptionSettings manually a couple of times.

It feels more right to hold on to a DecryptionSettings directly. If
there were ever some additional settings, most likely we would need them
all here.

If I haven't screwed it up, this should not affect behaviour in any way.
2025-06-24 12:36:31 +01:00
Benjamin Bouvier 201b818cc8 fix(timeline): take into account the skip count when computing the pagination status
The pagination status was only mapped onto the "global" state, that is, the state of the event cache pagination.

Now, consider the following case, where two timeline instances are live:

- the first one could have backpaginated all the items back to the start of the room
- the second one is created later. Because of the initial value for the skip count, it will only return a subset of event items (~20).

However, listening to the pagination status for the second timeline would incorrectly state that the timeline was entirely paginated (because it returned the "global" pagination status). As such, an observer might think that there are no more items in the timeline, while a subsequent pagination would adjust the skip count and return more items.

This fixes it by combining the global pagination state with the local timeline state (aka the skip count value). If the skip count is positive (meaning, we could set it to 0 later and thus returning more events), we pretend we haven't reached the start of the timeline. This way, an observer can call pagination later, which may adjust the skip count and "return" more items.
2025-06-24 09:41:04 +00:00
Daniel Salinas 1f98e0cd19 Run cargo fmt 2025-06-23 18:51:51 +03:00
Daniel Salinas 21c59c95c4 Avoid using of tokio::time:sleep which does not work on Wasm
We already have a wrapped sleep in matrix-sdk-base, so use that.
2025-06-23 18:51:51 +03:00
Andy Balaam 4025c11e73 refactor(crypto): Simplify the code that ignores to-device messages from dehydrated devices 2025-06-23 16:24:41 +01:00
Stefan Ceriu dc6130562a feat(ffi): add simpler methods for checking own user permissions
This is so that the final client no longer needs to go through the string to user_id conversion and error handling step before retrieving permissions.
2025-06-23 18:04:59 +03:00
Stefan Ceriu d1a14f895e chore(ffi): move user_power_levels outside the RoomInfo and into the newly introduced RoomPowerLevels.
`RoomPowerLevels` already holds an inner version of the power levels and has access to everything needed to compute the user to level map.
This way the async fetching only happens once and the mapping only on request.
2025-06-23 18:04:59 +03:00
Stefan Ceriu b680705d15 feat(ffi): expose the RoomPowerLevels on the RoomInfo directly.
Currently, clients have to make async requests to `Room::get_power_levels` from multiple places throughout the app in order to correctly configure the various UI components and again, on randomly decided events, to keep them up to date.
This patch starts publishing the power levels directly on the `RoomInfo` and allows them to be handled (and updated!) through the normal `subscribe_to_room_info_updates` mechanism.
2025-06-23 18:04:59 +03:00
Stefan Ceriu 2b1ee853fc chore(ffi): move RoomInfo to the room module 2025-06-23 18:04:59 +03:00
Ivan Enderlin ef137730cb doc(sdk): Add #5269 to the CHANGELOG.md. 2025-06-23 15:45:28 +02:00
Ivan Enderlin 45caaffb26 refactor(sdk): Rename RoomEventCacheListener to RoomEventCacheSubscriber.
This patch removes a name ambiguity around _listener_ vs. _subscriber_.
Both terms are used to talk about `RoomEventCacheListener`. We usually
use the term _subscriber_ for the type being returned by a `subscribe`
method. The code refers to this sometimes as listener, sometimes
as subscriber, sometimes both in the same sentence, which can be very
confusing! This patch solves this by using the _subscriber_ term only.
2025-06-23 15:45:28 +02:00
Ivan Enderlin 50c3217353 doc(sdk): Document the side-effect of RoomEventCacheListener. 2025-06-23 15:45:28 +02:00
Ivan Enderlin b5dafd9798 chore(sdk): Rename variables.
This patch renames `tx` and `rx` to `auto_shrink_sender` and
`auto_shrink_receiver` to clarify the code.
2025-06-23 15:45:28 +02:00
Ivan Enderlin 5a39fd051b chore(sdk): Rename a variable.
This patch renames a variable to match the `EventCacheDropHandles`
field's name.
2025-06-23 15:45:28 +02:00
Andy Balaam ff52cf36dd refactor(crypto): Rename raw_event to processed_event to reflect its changed state 2025-06-23 11:34:59 +02:00
Daniel Salinas 25d217cc6f Address timeline panic to avoid resume_unwind on Wasm 2025-06-23 10:06:04 +02:00
Jonas Platte 2116ad82df refactor: Move comments with visual indentation
Visual indentation was removed from rustfmt's style defaults in the 2024
edition of the style rules.
2025-06-23 09:37:45 +02:00
Jonas Platte fe4109cb9a refactor: Remove {self} imports
They are only semantically different if a macro of the same name exists,
in which case the foo::{self} import only imports foo-the-module, not
foo-the-macro.
2025-06-23 09:37:45 +02:00
Jonas Platte 41f107e5ba refactor: Remove useless comment
This comment was added in the very first commit for matrix-sdk-ffi and I
have no recollection of what was meant there.
2025-06-23 09:37:45 +02:00
Daniel Salinas ab699a90f1 Adjust platform init on Wasm to avoid tokio environment
The multi-threaded tokio environment does not work in Wasm.
console_error_panic_hook turns rust panics into JS console statements
2025-06-23 09:47:08 +03:00
Daniel Salinas ddee7f8ccd feat(wasm): Small fixes for imports in ffi timeline (#5263)
Adjust some imports to use our shims to support Wasm.

Signed-off-by: Daniel Salinas
2025-06-20 22:22:15 +02:00
Daniel Salinas 2ab5ab527b refactor(wasm): Remove special Send/Sync behavior for Wasm on a crypto-store error (#5265)
Not necessary it turns out

Signed-off-by: Daniel Salinas
2025-06-20 22:18:32 +02:00
Daniel Salinas 53e3b90436 feat(wasm): Mark CapabilitiesProvider::acquire_capabilities as SendOutsideWasm (#5262)
Correct an accidental recent addition of a `Send` trait instead of
`SendOutsideWasm`

Signed-off-by: Daniel Salinas
2025-06-20 21:58:11 +02:00
Daniel Salinas 08e1d3876b Reorganize QRCode related functionality into its own file
We have a working implementation of the additional forms of QR Code login
of MSC4108. This commit moves the existing code into its own file
to make future updates easier to follow.
2025-06-20 14:24:28 +01:00
Richard van der Hoff c3179ea5ed Merge pull request #5260 from matrix-org/rav/join_room_logging
sdk: add logging to `Room::join()`
2025-06-20 12:12:05 +01:00
Daniel Salinas 9676daee5a feat(wasm): Remove MediaFileHandle from ffi on Wasm platforms (#5249)
Remove the MediaFileHandle concept from the matrix-sdk-ffi crate on Wasm
platforms. File handles are not supported in the browser.

Signed-off-by: Daniel Salinas
2025-06-19 18:55:23 +02:00
Daniel Salinas 798cece4a2 feat(wasm): Add lib to matrix-sdk-ffi target (#5242)
The uniffi tool for generating JS/Wasm bindings utilizes rust as its
intermediate language.

As a result, the 'target' uniffi annotated library needs to be marked as
a 'lib' so that the generated rust code can utilize it to generate the
Wasm create + typescript bindings.

Signed-off-by: Daniel Salinas
2025-06-19 18:16:16 +02:00
Doug 06b387101b chore: Fix changelogs after rebase 2025-06-19 17:40:04 +02:00
Doug 675963ec4b chore: Make the RTC foci crash fix type-safe. 2025-06-19 17:40:04 +02:00
Doug d30dae3322 fix: Handle a crash accessing the RTC foci when the well-known was None. 2025-06-19 17:40:04 +02:00
Doug bdb640a126 ffi: Expose a check for LiveKit RTC support. 2025-06-19 17:40:04 +02:00
Doug ea28234d95 sdk: Cache the client well-known file and add Client::rtc_foci which uses it. 2025-06-19 17:40:04 +02:00
Doug c74295c604 chore: Refactor ServerCapabilities into ServerInfo.
It has nothing to do with /capabilities so is confusing. We can use this new struct to combine the well-known response into a single cache too.
2025-06-19 17:40:04 +02:00
Michael Goldenberg ec30e7b85c docs(indexeddb): add license to event_cache_store::types file
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg fd17c28ebb refactor(indexeddb): add convenience functions for (de)serializing Indexed types
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg 841131f127 refactor(indexeddb): add indexing trait impls for gap
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg a22d592bf1 refactor(indexeddb): add chunk identifier into gap type
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg 1a32aa59a6 refactor(indexeddb): add indexing trait impls for event
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg a99df7e1d8 refactor(indexeddb): add indexing trait impls for chunk
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg 3e37f9d0ad refactor(indexeddb): expose current version and keys used in event cache store database 2025-06-19 17:26:30 +02:00
Michael Goldenberg 2689e2d25a refactor(indexeddb): add trait for constructing key bounds for indexed types in event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg 2cfba4cd9b refactor(indexeddb): add trait for encoding keys for indexed types in event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Michael Goldenberg 1bce2af93c refactor(indexeddb): add trait for converting between high-level types and indexed types in event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-19 17:26:30 +02:00
Stefan Ceriu 47c8df0ef8 chore(ffi): move the room power levels to their own file and restructure the code 2025-06-19 17:55:48 +03:00
Stefan Ceriu 9f32dfe9a0 change(ffi): expose the full RoomPowerLevels object and move corresponding methods to it.
This patch expands on the already existent `RoomPowerLevels` record (which it renames to `RoomPowerLevelsValues` to work around uniffi not exposing public fields) and nests them inside a new exported object that also provides methods for retrieving the actions that an user can take, methods moved from the room object.
This reduces the amount of async calls the clients need to make, simplifies the API and groups the code better together.
2025-06-19 17:55:48 +03:00
Daniel Salinas 040fd6c736 Run cargo fmt 2025-06-19 16:16:59 +02:00
Daniel Salinas 4dac175db0 Back to other phrasing to make CI run 2025-06-19 16:16:59 +02:00
Daniel Salinas 5faf97cf99 Rework phrasing to make CI run 2025-06-19 16:16:59 +02:00
Daniel Salinas 7236b80b3b Adjust language to make CI do something 2025-06-19 16:16:59 +02:00
Daniel Salinas 79b0941687 Remove lib 2025-06-19 16:16:59 +02:00
Daniel Salinas ad001e475f Update bindings/matrix-sdk-ffi/Cargo.toml
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 16:16:59 +02:00
Daniel Salinas 5106d55be9 Update bindings/matrix-sdk-ffi/Cargo.toml
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 16:16:59 +02:00
Daniel Salinas 9771b99395 Update bindings/matrix-sdk-ffi/Cargo.toml
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 16:16:59 +02:00
Daniel Salinas 2c287e706f Update bindings/matrix-sdk-ffi/Cargo.toml
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 16:16:59 +02:00
Daniel Salinas fffff783d4 Spell check 2025-06-19 16:16:59 +02:00
Daniel Salinas b047bd0dc6 Add refactor flag 2025-06-19 16:16:59 +02:00
Daniel Salinas 28b3b6aedf Update bindings/matrix-sdk-ffi/CHANGELOG.md
Co-authored-by: Damir Jelić <poljar@termina.org.uk>
Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 16:16:59 +02:00
Daniel Salinas 171974a44b Add note about bundled-sqlite 2025-06-19 16:16:59 +02:00
Daniel Salinas f53302a7a0 Code review feedback, improved documentation 2025-06-19 16:16:59 +02:00
Daniel Salinas dd709682d7 Update bindings/matrix-sdk-ffi/Cargo.toml
Co-authored-by: Damir Jelić <poljar@termina.org.uk>
Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 16:16:59 +02:00
Daniel Salinas 991e0cd395 Update bindings/matrix-sdk-ffi/Cargo.toml
Co-authored-by: Damir Jelić <poljar@termina.org.uk>
Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 16:16:59 +02:00
Daniel Salinas abcc05f889 Change matrix-sdk-ffi to rely on features over platform targets
The system of platform targets was already quite messy, and becoming
even worse as we start preparing for Wasm support. Switch to features
instead to make this easier to work with.
2025-06-19 16:16:59 +02:00
Daniel Salinas f3e636ea42 fix(wasm): Fix unwrap error on Wasm platforms caused by UInt::MAX conversions (#5240)
UInt::MAX.try_into().unwrap() was causing errors on Wasm platforms, due
to the result being unrepresentable.

This `unwrap_or` was also always being calculated regardless, so I think
using `usize::MAX` is preferable on all platforms.

Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
2025-06-19 13:56:50 +00:00
Daniel Salinas 1d47507faa refactor(wasm) Remove some unnecessary wasm32 differentiations (#5256)
Some of these Box<dyn Error + Send + Sync> are okay, but a few are
problematic.

Confirmed this still compiles fine on the fully working wasm tree.

Signed-off-by: Daniel Salinas
2025-06-19 13:28:04 +00:00
Damir Jelić cc7f6243c6 ci: Make the text output for our coverage xtask the default 2025-06-19 13:57:58 +02:00
Jonas Platte e7e9d5b746 refactor: Use native async fn in traits for widget::CapabilitiesProvider (#5135)
The main thing left now are the store traits, unsure how to deal with
those. `dynosaur` + `trait_variant` are kind of the modern replacement
for `async_trait`, but (a) `trait_variant` seemed to generate invalid
code here when I tried it and (b) even with that fixed I think the error
type erasure is going to present some extra problems. Maybe it's fine to
just keep the current solution for the store traits for now.

Signed-off-by: Jonas Platte <jplatte+matrix@posteo.de>
2025-06-19 11:47:36 +00:00
Andy Balaam b4146caac8 refactor(crypto): Extract a method for handling encrypted to-device events 2025-06-19 11:22:11 +01:00
Damir Jelić 1cb51f49be ci: Store successful test results in the JUnit file as well
This is useful to detect which tests might be the slowest.
2025-06-19 11:14:51 +02:00
Damir Jelić fea0e0d373 ci: Use the correct token to upload JUnit reports 2025-06-19 10:26:43 +02:00
Damir Jelić 72911c66ad ci: Upload the JUnit reports to codecov as well 2025-06-19 09:50:16 +02:00
Damir Jelić dc047854d4 ci: Use a separate cache prefix for the coverage workflow 2025-06-19 09:50:16 +02:00
Damir Jelić f51a008921 ci: Attempt to free up some space on the container for the coverage workflow 2025-06-19 09:50:16 +02:00
Damir Jelić 3c5bcce217 ci: Use llvm-cov for coverage reports
This patch switches from tarpaulin to llvm-cov for our coverage reports.
llvm-cov can use cargo-nextest to run the tests which means that we can
tolerate flaky tests for coverage just like do for the rest of our CI
run.

We can also start using JUnit reports to track flaky tests.
2025-06-19 09:50:16 +02:00
Damir Jelić 422fd19d10 ci: Add an xtask subcommand for coverage reports
This command uses llvm-cov which we are planning to switch to.
2025-06-19 09:50:16 +02:00
Damir Jelić 0ea07e11e9 ci: Add a CI specific profile for nextest 2025-06-19 09:50:16 +02:00
Damir Jelić 059a6fa573 test: Make some tests less flaky by increasing timeouts 2025-06-19 09:50:16 +02:00
Daniel Salinas 07656c2e26 Correct use to propagate error with additional text 2025-06-19 09:42:43 +02:00
Daniel Salinas 940325574b Address use of errors and panic::resume_unwind for wasm targets 2025-06-19 09:42:43 +02:00
Damir Jelić 9f8824b9a5 ci: Use a tag for the changed-files github action 2025-06-17 16:13:39 +02:00
Valere Fedronic cd141c5b84 feat(widget): Receive custom to-device messages in widgets in e2ee rooms
Proper support for receiving to-device messages for widgets.

If the widget is in an e2ee room, clear to-device traffic will be excluded. Also filter out internal to-device messages that widgets should not be aware off.
2025-06-17 16:00:44 +02:00
dependabot[bot] 9596aa0830 chore(deps): bump qmaru/wasm-pack-action from 0.5.0 to 0.5.1
Bumps [qmaru/wasm-pack-action](https://github.com/qmaru/wasm-pack-action) from 0.5.0 to 0.5.1.
- [Release notes](https://github.com/qmaru/wasm-pack-action/releases)
- [Commits](https://github.com/qmaru/wasm-pack-action/compare/v0.5.0...v0.5.1)

---
updated-dependencies:
- dependency-name: qmaru/wasm-pack-action
  dependency-version: 0.5.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-17 13:56:43 +02:00
Benjamin Bouvier 11424ce443 chore(ffi): add the SDK commit hash to sentry as the release version 2025-06-16 16:44:48 +02:00
Benjamin Bouvier cd4ec90b38 chore(timeline): report day divider invariant violations to sentry
On this date (heh), the date divider reports include the following
information:

- initial timeline items in a shortened format,
- operations to apply,
- final timeline items in the same shortened format,
- errors

The shortened format includes:

- either, for events: "[event id]: server timestamp"
- or for date divider: "--- date divider timestamp"

As such, they don't include any personal information.

The initial timeline items state and set of operations to apply
constitutes a fully enclosed test case, so it's nice to report it to
Sentry, so we can reuse it almost as is (we'd only need to randomize the
event IDs) and fix it in a subsequent commit.
2025-06-16 16:44:48 +02:00
Benjamin Bouvier 4680354abd fix(timeline): remove development tracing log in the pinned events loader 2025-06-16 14:25:30 +02:00
Damir Jelić 145d6c5782 refactor(multiverse): Use a paragraph to render an individual read receipt 2025-06-16 12:54:40 +02:00
Damir Jelić a955af61e1 refactor(multiverse): Simplify the selected read receipt rendering
This patch simplifies the selected read receipt rendering by the fact
that we can simply fetch the selected timeline item instead of the event
ID and then do a search for the selected item.

Co-authored-by: Benjamin Bouvier <benjamin@bouvier.cc>
Signed-off-by: Damir Jelić <poljar@termina.org.uk>
2025-06-16 12:54:40 +02:00
Damir Jelić 2a78b5b67a chore: Fix a clippy lint 2025-06-16 12:54:40 +02:00
Damir Jelić 9d29c36531 feat(multiverse): Only render read receipts for a single event if one is selected 2025-06-16 12:54:40 +02:00
Damir Jelić ed9c7d90b4 feat(multiverse): Allow event selection even if the details view is open 2025-06-16 12:54:40 +02:00
Damir Jelić 2af23d052c feat(multiverse): Show the selected event in the read receipts view 2025-06-16 12:54:40 +02:00
Damir Jelić fb80e06839 feat(multiverse): Show read receipts for individual messages 2025-06-16 12:54:40 +02:00
Daniel Salinas b8f9cba5e7 Wasm corrections for ffi's error file
Add a From to handle RequestVerificationError to avoid anyhow
Stop using SystemTime directly
2025-06-16 09:14:54 +02:00
Daniel Salinas d119b01322 Add AbortHandle as well 2025-06-16 09:09:28 +02:00
Daniel Salinas 85833c74ba Update JoinHandle as well 2025-06-16 09:09:28 +02:00
Daniel Salinas 5b20136a50 Stop using tokio::runtime::Handle directly
Use our platform aware export from matrix-sdk-common instead
2025-06-16 09:09:28 +02:00
Ivan Enderlin 362ca2bd59 doc(base): Remove ambiguities around inline comments. 2025-06-13 14:52:15 +02:00
Ivan Enderlin 0a9a849826 fix(base): Ignore invalid state events instead of throwing an error.
This patch changes the strategy of `check_room_upgrades`.
Instead of checking all state events in `StateChanges` and
throwing an error in case of an invalid state, this patch updates
`state_events::sync::dispatch` to filter out invalid state events
(specifically `m.room.create` and `m.room.tombstone`), and log the
error. That way, the sync doesn't stop and the app can continue working
smoothly.

So `check_room_upgrades` is splited into two functions:
`is_create_event_valid` and `is_tombstone_event_valid`. It's no longer
necessary to detect mergers or splitters because those are _soft
errors_, however loops are still critical errors (hence the fact
the state events aren't stored nor saved nor applied, and that a log
is emitted).

Note: `check_room_upgrades` has been reverted in a previous commit,
that's why it doesn't appear in this diff.
2025-06-13 14:52:15 +02:00
Valere Fedronic 7126fc8a29 feat(crypto): Emmit EncryptionInfo with event handlers for to-device messages as well 2025-06-13 14:31:22 +02:00
Stefan Ceriu f4e612ca9e feat: add thread support to the room message draft facilities
This patch adds optional thread root event id parameters to the drafting functions exposed on the room level
allowing unfinished messages to be managed for the main room as well as any inner thread.

Internally it uses the room id or a tuple of the room id and the thread as keys for the various backing stores.
2025-06-13 14:41:10 +03:00
Richard van der Hoff 6ab11a0323 Merge pull request #5219 from matrix-org/rav/megolm_sender_verification_main
crypto: new `VerificationLevel::MismatchedSender`
2025-06-12 12:44:47 +01:00
Stefan Ceriu 76626db613 chore(ffi): expose ThreadSummary num_replies on the ffi layer. 2025-06-12 14:26:40 +03:00
Benjamin Bouvier bcea1d32e6 refactor(multiverse): use a log line instead of a status message for showing intent to open a thread view 2025-06-12 13:25:08 +02:00
Benjamin Bouvier 346f11319c refactor(multiverse): move the opening of a threaded timeline to its own function 2025-06-12 13:25:08 +02:00
Benjamin Bouvier 937b223627 chore(multiverse): add missing help lines for the new functionalities 2025-06-12 13:25:08 +02:00
Benjamin Bouvier 000d8514f6 refactor(multiverse): store the selected room in the TimelineKind::Room field 2025-06-12 13:25:08 +02:00
Benjamin Bouvier 72692b7b33 feat(multiverse): add basic support for threads 2025-06-12 13:25:08 +02:00
Benjamin Bouvier 0f84d482b9 refactor(multiverse): inline send_message_impl into its own caller
Also don't clear the input if the timeline wasn't found yet.
2025-06-12 13:25:08 +02:00
Benjamin Bouvier c609150a3e refactor(multiverse): introduce RoomView::get_selected_timeline() 2025-06-12 13:25:08 +02:00
Benjamin Bouvier 2f46a6c8a0 refactor(multiverse): use Client to get a Room object by room id 2025-06-12 13:25:08 +02:00
Benjamin Bouvier 7bdddc9d35 refactor(multiverse): misc tiny changes
Notably, avoid holding a lock if it's not going to be used later.
2025-06-12 13:25:08 +02:00
Stefan Ceriu 5113f114a7 fix(ui): forward live events to threaded timelines, the same as live ones
- drop `is_live` and `is_pinned_events` and use the timeline focus directly at the decision point.
2025-06-12 12:57:10 +03:00
Stefan Ceriu 9d96d6ead2 feat(ffi): add support for sending locations as replies or within threads 2025-06-12 12:57:10 +03:00
Daniel Salinas c340a7187a feat(wasm): Fix cargo runtime on Wasm platforms (#5220)
When file was
[moved](https://github.com/matrix-org/matrix-rust-sdk/commit/2a140770a02cbeeaedc8c4dec90de9135aebc679)
it looks like an update was missed, since wasm is not in the CI yet.

Signed-off-by: Daniel Salinas
2025-06-11 22:07:54 +02:00
Richard van der Hoff 0aece695dc crypto: update changelog 2025-06-11 17:15:44 +01:00
Richard van der Hoff b2210292bf crypto: Add a test for spoofed sender, with TrustRequirement::CrossSigned 2025-06-11 17:06:44 +01:00
Richard van der Hoff f0ab6cb1a4 crypto: use a dedicated VerificationLevel if we know the sender of an event is spoofed 2025-06-11 17:06:44 +01:00
Richard van der Hoff c2eeca3f33 crypto: add some instrumentation to get_room_event_encryption_info
It helps to know which event we're getting the encryption info for.
2025-06-11 16:51:51 +01:00
Benjamin Bouvier cc974dd3c9 refactor(event cache): use Event instead of TimelineEvent more evenly 2025-06-11 17:04:15 +02:00
Benjamin Bouvier 8b2a8e7265 refactor(event cache): move the timeline-event-diffs sending back into the callers 2025-06-11 17:04:15 +02:00
Benjamin Bouvier 7cad237dc6 refactor(event cache): reduce indent in maybe_apply_new_redaction 2025-06-11 17:04:15 +02:00
Benjamin Bouvier 72a3972303 refactor(event cache): simplify mutating the RoomEvents in RoomEventCacheStore
No more generic function parameter! Having a separate function for
post-processing is simple enough.
2025-06-11 17:04:15 +02:00
Benjamin Bouvier 2e590e2f67 refactor(event cache): only mark that we've waited for an initial previous-batch token after a sync
It doesn't make sense to do it after a back-pagination, since a
back-pagination does require a previous-batch token in the first place,
meaning that if we did paginate, then we did wait for a previous-batch
token beforehand.
2025-06-11 17:04:15 +02:00
Benjamin Bouvier 224e437a78 refactor(event cache): simplify handling of previous-batch token in handle_backpagination too 2025-06-11 17:04:15 +02:00
Benjamin Bouvier 8a9cae4af3 refactor(event cache): have even fewer methods return timelinediff updates 2025-06-11 17:04:15 +02:00
Benjamin Bouvier 22a15f1342 refactor(event cache): remove code comment that doesn't make sense anymore 2025-06-11 17:04:15 +02:00
Benjamin Bouvier 3ab4584dfe refactor(event cache): have fewer methods return timelinediff updates 2025-06-11 17:04:15 +02:00
Benjamin Bouvier a3238cdadf refactor(event cache): remove indent in RoomEventCacheState::handle_sync 2025-06-11 17:04:15 +02:00
Benjamin Bouvier a884b2c696 refactor(event cache): move handling of a backpagination in RoomEventCacheState 2025-06-11 17:04:15 +02:00
Benjamin Bouvier ec0d7b4311 refactor(event cache): move handling of a sync in RoomEventCacheState 2025-06-11 17:04:15 +02:00
Benjamin Bouvier e8c2d27c9e refactor(event cache): slightly tweak logic around prev-batch token suppression 2025-06-11 17:04:15 +02:00
Benjamin Bouvier bff600a937 refactor(event cache): make deduplication entirely stateless
Having a small data structure to hold the room id and store isn't that
useful, after all.
2025-06-11 17:04:15 +02:00
Michael Goldenberg 404a982503 refactor(indexeddb): support querying by next chunk index, even when next chunk does not exist
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg e904a98735 refactor(indexeddb): re-type IndexedEventPositionIndex as usize as IndexedDB supports numeric keys
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg b55e79fdac refactor(indexeddb): re-type IndexedChunkId as u64 as IndexedDB supports numeric keys
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 717116cc05 refactor(indexeddb): re-type IndexedRoomId and IndexedEventId as String for compatibility with SafeEncode
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 0ad4df2031 refactor(indexeddb): remove extraneous room id field from event in event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 891e9813b1 refactor(indexeddb): re-type next/previous chunk fields as chunk identifiers rather than entire chunks
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 19b21fdd49 fix(indexeddb): enforce type rather than variant distinction between in-band/out-of-band events
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 307fa355ad refactor(indexeddb): add internal types that support encryption and indexing in event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 351053fef5 refactor(indexeddb): add internal types that support encryption and indexing in event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 8c735c602a refactor(indexeddb): add internal types for event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 7ffc390cea feat(indexeddb): put event cache store module behind feature flag
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Michael Goldenberg 05b67df6e2 feat(indexeddb): add initial database migrations for event cache store
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-06-11 16:09:33 +02:00
Denis Kasak f3f3d968b5 Merge pull request #5214 from matrix-org/update-changelog-main
Update changelog main
2025-06-11 12:18:22 +02:00
Denis Kasak bde1d4a353 Merge branch 'release-0.11' 2025-06-11 12:01:48 +02:00
Denis Kasak 4f6ddcd072 Merge pull request #5213 from matrix-org/update-changelog-sec-ref
chore: Add CVE-2025-48937 reference to the CHANGELOG
2025-06-11 11:36:16 +02:00
Denis Kasak b99188dd59 chore: Add CVE-2025-48937 reference to the CHANGELOG
Signed-off-by: Denis Kasak <dkasak@termina.org.uk>
2025-06-11 11:27:36 +02:00
homersimpsons e2fee14ced 📝 Fix changelog links
Signed-off-by: homersimpsons <guillaume.alabre@gmail.com>
2025-06-11 10:32:33 +02:00
Benjamin Bouvier 9fca8f0007 refactor(timeline): include the bundled item owner in edit aggregation metadata 2025-06-10 15:52:00 +02:00
Benjamin Bouvier ca0fc3cf6d fix(timeline): correctly use the bundled event id when handling replacements 2025-06-10 15:52:00 +02:00
Benjamin Bouvier 378f50d8b5 fix(ci): bump the timeout values for test_subscribe_to_knock_requests
They were exceedingly low, especially in the context of code coverage
which can be quite slow.
2025-06-10 14:42:27 +02:00
Damir Jelić 485bb0790e refactor: Move the store caches into the caches module 2025-06-10 13:53:09 +02:00
Damir Jelić 0e9ce0271e refactor: Create a store/types submodule 2025-06-10 13:53:09 +02:00
Damir Jelić c0294d5e33 refactor: Use the EVENT_TYPE constant to deserialize AnyDecryptedToDeviceEvent 2025-06-10 13:53:09 +02:00
Damir Jelić b41efb063e chore: Release matrix-sdk version 0.12.0 2025-06-10 13:33:01 +02:00
Damir Jelić 23db199262 Merge branch 'release-0.11' 2025-06-10 12:51:59 +02:00
Damir Jelić 76d1f8bd18 chore: Fix a PR link in the changelog file 2025-06-10 12:37:32 +02:00
Damir Jelić 550f4c5fde Update crates/matrix-sdk-crypto/CHANGELOG.md
Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
Signed-off-by: Damir Jelić <poljar@termina.org.uk>
2025-06-10 12:37:32 +02:00
Damir Jelić b3f07f4587 chore: Release matrix-sdk version 0.11.1 2025-06-10 12:37:32 +02:00
Damir Jelić 56980745b4 chore: Add a changelog entry for GHSA-x958-rvg6-956w 2025-06-10 12:37:32 +02:00
Richard van der Hoff 13c1d20482 fix(crypto): Check the sender of an event matches owner of session
Having decrypted an event with a given megolm session, we need to check that
the owner of that session actually matches the sender of an event, otherwise
there is a danger of the sender being spoofed to make it look like it was sent
by another user.

Security-Impact: High
CVE: CVE-2025-48937
GitHub-Advisory: GHSA-x958-rvg6-956w
2025-06-10 12:07:10 +02:00
Richard van der Hoff 7f3e144cb3 refactor (crypto): clarify some comments 2025-06-10 12:07:10 +02:00
Richard van der Hoff fe8bd2fdf3 refactor(crypto): Break get_or_update_verification_state in two
Split this into `get_room_event_verification_state` and
`get_or_update_sender_data`, which I think is a bit clearer.
2025-06-10 12:07:10 +02:00
Benjamin Bouvier 7cdfb0d1c0 chore(sqlite): revert the busy_timeout pragmas
Internal Sentry reports tell us that enabling the busy_timeout seems to
have *increased* the number of "database is busy" errors, instead of
lowering those. As a result, we're going to disable the pragmas in all
the places where we enabled it before, and observe how the number of
"database is busy" errors evolves.
2025-06-10 11:13:28 +02:00
Benjamin Bouvier d8652d27f8 feat(sdk): forbid ignoring the current user 2025-06-10 10:50:34 +02:00
Damir Jelić aa67148247 refactor(xtask): Use a helper to append options for the release tasks 2025-06-10 09:47:42 +02:00
Damir Jelić 769fcdb1fb feat: Support releasing a specific package 2025-06-10 09:47:42 +02:00
Damir Jelić 0f4afb32f7 refactor(xtask): Use a helper to append options for the release tasks 2025-06-10 09:34:56 +02:00
Damir Jelić 398787253d feat: Support releasing a specific package 2025-06-10 09:34:56 +02:00
Benjamin Bouvier 7a6e29c347 feat(ui): don't mark each thread reply as an actual reply to the previous message, in threaded timelines
This correctly handles the reply fallback behavior:

- the behavior isn't changed for a live timeline,
- when a timeline is thread-focused, we will extract the `replied_to`
field if and only if the thread relation is *not* marked as behaving in
a fallback manner.

This makes it possible to distinguish actual in-thread replies.
2025-06-10 09:03:30 +02:00
Damir Jelić 6e628781c0 release: Add a changelog entry for the tracing-attributes issue 2025-06-09 20:29:09 +02:00
VerdeQuar a75a2b4113 fix(crypto): Remove wildcard enum variant import
Signed-off-by: VerdeQuar <verdequar@gmail.com>
2025-06-09 20:29:09 +02:00
Damir Jelić 216e878231 Revert "feat(base): Detecting invalid states in room upgrades."
This reverts commit c7f6190cff.
2025-06-09 18:08:03 +02:00
Damir Jelić e54b20fa68 Revert "doc(base): Improve documentation. "
This reverts commit 8e3ad22d92.
2025-06-09 18:08:03 +02:00
Damir Jelić a120057ec3 Revert "fix(base): Revisit check_tombstone entirely."
This reverts commit 0478037b57.
2025-06-09 18:08:03 +02:00
dependabot[bot] 737bda44a2 chore(deps): bump crate-ci/typos from 1.32.0 to 1.33.1
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.32.0 to 1.33.1.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.32.0...v1.33.1)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.33.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-09 17:45:37 +02:00
Benjamin Bouvier df65c94974 chore(ui): apply review comments 2025-06-09 16:59:32 +02:00
Stefan Ceriu 39ee5112b4 chore(ui): add timeline threaded filtering tests 2025-06-09 16:59:32 +02:00
Stefan Ceriu 96afdeffad feat(ui): add TimelineFocus associated values for defining whether threaded events should be hidden on those particular timeline instances. 2025-06-09 16:59:32 +02:00
Stefan Ceriu 669d91e7e9 feat(ui): add thread based filtering for local event items 2025-06-09 16:59:32 +02:00
Stefan Ceriu dcec53ba00 feat(ui): filter threaded remote events based on the timeline focus and extracted relations 2025-06-09 16:59:32 +02:00
Stefan Ceriu 9d9ce4a68b chore(ui): remove relation processing when dealing with EmbeddedEvents 2025-06-09 16:59:32 +02:00
Stefan Ceriu dc24365ddf chore(ui): move event based relation handling to TimelineMetadata and out of the TimelineAction 2025-06-09 16:59:32 +02:00
Stefan Ceriu ba53390547 chore(ui): move timeline item relation handling from the TimelineAction to the TimelineMetadata 2025-06-09 16:59:32 +02:00
Stefan Ceriu c860e7fca7 fix(ui): load up reactions to threaded messages 2025-06-09 16:59:32 +02:00
Benjamin Bouvier ebcb74a86d refactor!(event cache): introduce LinkedChunkId in the backends (#5182)
In a "soon" future, threads have their own linked chunk. All our code
has been written with the fact that a linked chunk belong to *a room* in
mind, so it needs some biggish update. Fortunately, most of the changes
are mechanical, so they should be rather easy to review.

Part of #4869, namely #5122.
2025-06-09 13:26:46 +00:00
Jonas Platte 65bb20c965 refactor: Clean up tracing and formatting macro uses (#5192)
Signed-off-by: Jonas Platte <jplatte+matrix@posteo.de>
2025-06-09 12:15:59 +02:00
VerdeQuar bdda4abf56 fix(crypto): Remove wildcard enum variant import
Signed-off-by: VerdeQuar <verdequar@gmail.com>
2025-06-07 14:55:27 +02:00
Jorge Martín 47e81818bc test: Add extra test for the active call state
Also, adapt the other tests to the new return type
2025-06-06 15:02:17 +02:00
Jorge Martín fe015b7eda refactor: Expose the new return type of Client::send_call_notifications_if_needed in the FFI layer 2025-06-06 15:02:17 +02:00
Jorge Martín baf6824bc4 refactor: Add extra logs to Client::send_call_notifications_if_needed
Also make it return `Result<bool>` instead of `Result<()>` so we can check if the event was sent.
2025-06-06 15:02:17 +02:00
Jorge Martín c1ce92bf48 refactor(ffi): Use Client::room_info_notable_update_receiver instead of RoomUpdates
This allows us to also react to local changes that would take several extra seconds to be received in a new sync response.
2025-06-06 13:18:49 +02:00
Benjamin Bouvier 4eb7e0c845 feat(timeline): insert the timeline start item just after creating a live timeline
This is even better, as we don't need to look at the live pagination
status to know whether we've reached the start of the timeline or not.
2025-06-06 12:57:39 +02:00
Benjamin Bouvier 766ff3f8e9 test(timeline): add a test for the mysterious missing timeline start case 2025-06-06 12:57:39 +02:00
Benjamin Bouvier a855f1df2c fix(timeline): add the timeline start of the current pagination state too 2025-06-06 12:57:39 +02:00
Ivan Enderlin 0478037b57 fix(base): Revisit check_tombstone entirely.
This patch renames `check_tombstone` to `check_room_upgrades`.
Then it rewrites it **entirely** to remove all false-positives and
false-negatives. More importantly, the room versions are no longer
involved: they can't be compared or ordered, they must be treated as
opaque values.

This new version of `check_room_upgrades` does a first path to check
predecessor-successor consistency. Then it does a second version to
detect loops. This new algorithm is robust to absent `m.room.create`
events. Making them mandatory is left to another patch.

More tests are added, especially to ensure that `m.room.create` cannot
be overwritten, and to ensure loops or inconsistent predecessors and
successors are correctly detected.
2025-06-06 12:54:45 +02:00
Benjamin Bouvier caa07a8007 refactor(sdk): regroup bundled thread extraction in TimelineEvent ctors 2025-06-06 13:34:12 +03:00
Benjamin Bouvier 93f2c61447 feat(event cache): store a bundled thread's latest TimelineEvent if provided 2025-06-06 13:34:12 +03:00
Benjamin Bouvier c8a5c43232 feat(common): temporarily store a bundled thread's latest TimelineEvent 2025-06-06 13:34:12 +03:00
Benjamin Bouvier 2aeb1a0353 refactor(sdk): rename TimelineEvent::new to from_plaintext 2025-06-06 13:34:12 +03:00
Benjamin Bouvier a1ad772642 refactor(sdk): rename TimelineEvent::new_utd_event to from_utd 2025-06-06 13:34:12 +03:00
Benjamin Bouvier b8f850b6f2 refactor(sdk): make it clearer that Context isn't mutated in a few processor helpers
It isn't mutated by the function, so there's no need to pass a mutable
reference here.
2025-06-06 13:34:12 +03:00
Benjamin Bouvier c6ed2d1963 refactor(sdk): compute push actions before creating a decrypted TimelineEvent
This reduces the number of callers to `set_push_actions()`, which should
be minimally used.
2025-06-06 13:34:12 +03:00
Benjamin Bouvier c48a2d68d1 refactor(base): streamline the verification processor 2025-06-06 13:34:12 +03:00
Benjamin Bouvier 5a1909aab9 refactor(sdk): get rid of the implicit conversion from DecryptedEvent to TimelineEvent 2025-06-06 13:34:12 +03:00
Benjamin Bouvier fc81178504 refactor(sdk): make TimelineEvent::push_actions private
And add getters and setters. It makes it clear who are the external
readers/writers of the push actions, and it makes it impossible to
create a `TimelineEvent` out of thin air (since it now has a private
field).
2025-06-06 13:34:12 +03:00
Daniel Salinas d3f63e91d5 Enable subscribe_to_send_progress for Wasm 2025-06-06 10:08:04 +02:00
Benjamin Bouvier 70705f4e9d chore(ci): exclude some crate from codecov testing
There's been many segfaults happening in tests, while running the test
coverage for this specific crate. An issue has been opened on
cargo-tarpaulin's repository:

https://github.com/xd009642/tarpaulin/issues/1749

Until this is fixed or worked around, we'll disable coverage testing for
this specific crate.
2025-06-06 09:28:55 +02:00
Benjamin Bouvier 8c66e0ba2f chore(ci): remove unused SLIDING_SYNC_PROXY_URL env variable 2025-06-06 09:28:55 +02:00
Benjamin Bouvier f5e0c6f004 chore(ci): exclude multiverse from the codecov reports 2025-06-06 09:28:55 +02:00
Jonas Platte 2a140770a0 fix: Move runtime module from matrix-sdk-common to matrix-sdk-ffi (#5184)
This module only builds on non-wasm with the patched async-compat from
the workspace Cargo.toml's patch section, and it is only used by the ffi
crate. It is currently breaking the use of the SDK as a git dependency,
and would prevent the publishing of matrix-sdk-common (unless using
--no-verify, but then that would just break all users of the newly
published crates.io version).

This bug was introduced in
https://github.com/matrix-org/matrix-rust-sdk/pull/5089.

Signed-off-by: Jonas Platte <jplatte+matrix@posteo.de>
2025-06-05 19:30:15 +00:00
Jorge Martín becbb63ad7 feat(ffi): Subscribe to a room's RoomInfo through Client
This helps in the case we want to observe the membership state changes - or some other info - for a room that's still not known so we can't just use `Client::get_room` to fetch it.
2025-06-05 16:49:39 +02:00
Damir Jelić 34d3cd496b feat(multiverse): Show thread roots even if we can't find the latest message 2025-06-05 16:29:54 +02:00
Damir Jelić 1f9c3394c5 refactor(multiverse): Split out the timeline item formatting logic 2025-06-05 16:29:54 +02:00
Damir Jelić 005f002747 feat(multiverse): Start to render threads 2025-06-05 16:29:54 +02:00
Damir Jelić 80b8a6d8cc feat(multiverse): Allow timeline items to be selected 2025-06-05 16:29:54 +02:00
Valere f7265c39e0 cleanup: Reuse existing server.mock_sync instead of custom function 2025-06-05 14:29:50 +02:00
Valere 4468c36b14 review: extend existing MatrixMockServer instead of creating another 2025-06-05 14:29:50 +02:00
Valere 25841c787e refactor(test): Extract common crypto mock server helper 2025-06-05 14:29:50 +02:00
Damir Jelić 9461ef3a5a chore: Fix a typo in the cargo-deny file 2025-06-05 11:11:40 +02:00
Johannes Marbach b8ae210e4a feat(ffi): Add reply_params to GalleryUploadParameters (#5173)
Looks like I forgot adding this in
https://github.com/matrix-org/matrix-rust-sdk/pull/5163, sorry.
Everything below the FFI layer was already prepared for replies.

Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-06-05 10:07:32 +01:00
Daniel Salinas a3225e5cd7 feat(wasm): Wasm equivalent of get_runtime_handle and corresponding tokio types (#5089)
Adds a Wasm equivalent of the get_runtime_handle method provided by
tokio, as well as Handle/Runtime types that can be used on either Wasm
or non-Wasm platforms interchangeably.

Dependent on https://github.com/matrix-org/matrix-rust-sdk/pull/5088
<!-- description of the changes in this PR -->

- [ ] Public API changes documented in changelogs (optional)

<!-- Sign-off, if not part of the commits -->
<!-- See CONTRIBUTING.md if you don't know what this is -->
Signed-off-by: Daniel Salinas

---------

Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
Co-authored-by: Daniel Salinas <danielsalinas@Daniels-MacBook-Pro-2.local>
Co-authored-by: Daniel Salinas <danielsalinas@daniels-mbp-2.myfiosgateway.com>
Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
Co-authored-by: Ivan Enderlin <ivan@mnt.io>
2025-06-05 08:07:01 +02:00
Daniel Salinas 0777e6e08a feat(wasm): Enable subscribe_to_send_progress on wasm platforms (#5170) 2025-06-04 18:13:47 +02:00
Daniel Salinas 8b2088fd61 feat(wasm): Eliminate some unecessary wasm removals from matrix-sdk crate (#5169) 2025-06-04 18:13:27 +02:00
Johannes Marbach d38f409351 feat(ffi): Expose method for sending galleries (#5163)
Addendum to https://github.com/matrix-org/matrix-rust-sdk/pull/5125 to
allow sending galleries from the FFI crate. This is the final PR for
galleries (apart from possible enhancements to report the upload status
in https://github.com/matrix-org/matrix-rust-sdk/pull/5008).

This is somewhat lengthy again, apologies. Most of the changes are just
wrappers and type mapping, however. So I was hoping that it's relatively
straightforward to review in bulk. Happy to try and elaborate on the
changes or break them up into smaller commits if that helps, however.

---------

Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-06-04 16:41:03 +02:00
Daniel Salinas 58b8a2560c feat(wasm): Comprehensive Send+Sync bound improvements for Wasm compatibility (#5082)
This commit systematically replaces Send+Sync trait bounds throughout
the matrix-rust-sdk codebase to enable Wasm compatibility while
maintaining thread safety on native targets.

Key changes:
- Use SendOutsideWasm/SyncOutsideWasm traits instead of Send/Sync for
trait bounds
- Apply conditional compilation for error types and trait objects
- Update FFI trait definitions to use Wasm-compatible bounds
- Fix event handler and type alias definitions for cross-platform
compatibility
- Maintain existing functionality while enabling WebAssembly target
support

The SendOutsideWasm/SyncOutsideWasm traits are empty on Wasm (allowing
all types) and alias to Send/Sync on native targets, ensuring zero-cost
abstraction.

Files updated:
- All FFI bindings (30+ trait definitions)
- Core SDK error types and type aliases
- Event handler infrastructure
- Store and crypto abstractions
- UI service filters and sorters
- Timeline and authentication modules

<!-- description of the changes in this PR -->

- [ ] Public API changes documented in changelogs (optional)

<!-- Sign-off, if not part of the commits -->
<!-- See CONTRIBUTING.md if you don't know what this is -->
Signed-off-by: Daniel Salinas

---------

Signed-off-by: Daniel Salinas <zzorba@users.noreply.github.com>
Co-authored-by: Daniel Salinas <danielsalinas@Daniels-MacBook-Pro-2.local>
Co-authored-by: Daniel Salinas <danielsalinas@daniels-mbp-2.myfiosgateway.com>
2025-06-04 15:59:37 +02:00
Daniel Salinas edb7a0f433 Add Wasm platform aware test to export proc-macro 2025-06-04 12:32:33 +02:00
Valere Fedronic 0f73ffde68 feat(crypto): Add the EncryptionInfo to the Decrypted ProcessedToDeviceEvent variant
The `ProcessedToDeviceEvent::Decrypted` variant now also have an
`EncryptionInfo` field.

The enum variant  changed from `Decrypted(Raw<AnyToDeviceEvent>)` to `Decrypted {
raw: Raw<AnyToDeviceEvent>, encryption_info: EncryptionInfo) }`
2025-06-04 11:54:38 +02:00
Daniel Salinas d3be744244 feat(wasm): Remove direct use of tokio::spawn in favor of matrix-sdk-common (#5159)
Mechanical move from tokio::spawn to matrix_sdk_common::executor::spawn
that has support for Wasm platforms. On non-Wasm, this shim defaults to
tokio::spawn.
2025-06-03 12:22:53 -04:00
Andy Balaam ca63d60068 doc(crypto): Add missing word 'verify' in 'verify_device' docs 2025-06-03 17:04:48 +02:00
Damir Jelić 8cc3b0fa33 refactor(multiverse): Add a common method to execute commands on rooms 2025-06-03 16:46:17 +02:00
Damir Jelić bf201e317e feat(multiverse): Add a /leave command 2025-06-03 16:46:17 +02:00
Benjamin Bouvier fe11fda832 refactor(timeline): extract the method to fetch a latest thread reply as an item
Do the ~~~loco~~ code motion 🎶
2025-06-03 16:28:25 +02:00
Benjamin Bouvier 281faa7a0b refactor(ffi): simplify From<TimelineDetails<Profile>> for ProfileDetails 2025-06-03 16:28:25 +02:00
Benjamin Bouvier 7962253ebd refactor(timeline): only use the publicly exposed content/sender/sender_profile on EmbeddedEvent 2025-06-03 16:28:25 +02:00
Benjamin Bouvier dd14df086e refactor(ffi): simplify FFI layer and use only EmbeddedEventDetails there for both thread latest event + replied-to event item 2025-06-03 16:28:25 +02:00
Benjamin Bouvier c426138971 refactor(timeline): rename RepliedToEvent to EmbeddedEvent and reuse it for the thread summary 2025-06-03 16:28:25 +02:00
Benjamin Bouvier ff4b7a8acc feat(event cache): add basic support for the latest event in the thread summary 2025-06-03 16:28:25 +02:00
Benjamin Bouvier a152f9c074 refactor(event cache): remove one caller of with_events_mut
The actual code useful in `with_events_mut` and used in that function
was to propagate the changes to the store and propagating diffs to
observers. It often striked me as hacky to use this method to do that,
so instead I'm proposing here to inline the useful bits. That way,
`with_events_mut` is now clearly called only in two cases: after a sync,
or after a successful network back-pagination.
2025-06-03 16:28:25 +02:00
Benjamin Bouvier 50be8a158c refactor(event cache): only send a thread summary update when a thread has changed 2025-06-03 16:28:25 +02:00
Benjamin Bouvier aa291079d0 feat(event cache): include the reply count in the ThreadSummary 2025-06-03 16:28:25 +02:00
Benjamin Bouvier 672bb9f460 feat: add the busy timeout pragma to the event cache store acquire() method too
It will tell us if this is sufficient to avoid locking the event cache
store database, now that we have some proof that this is happening in
the wild.
2025-06-03 16:17:36 +02:00
Kévin Commaille 9a75007535 Upgrade Ruma
Use the newly released version.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-06-03 15:52:15 +02:00
Johannes Marbach ee06965d2e feat(timeline): Expose method to send galleries in matrix-sdk-ui (#5125)
This was broken out of
https://github.com/matrix-org/matrix-rust-sdk/pull/4838 and is a step
towards implementing
https://github.com/matrix-org/matrix-spec-proposals/pull/4274. Building
upon https://github.com/matrix-org/matrix-rust-sdk/pull/4977, a new
method `Timeline::send_gallery` in matrix-sdk-ui for sending galleries.

- [x] Public API changes documented in changelogs (optional)

---------

Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-06-03 15:24:02 +02:00
Ivan Enderlin 8e3ad22d92 doc(base): Improve documentation.
This patch improves an inline documentation.

Co-authored-by: Stefan Ceriu <stefan.ceriu@gmail.com>
Signed-off-by: Ivan Enderlin <ivan@mnt.io>
2025-06-03 15:04:26 +02:00
Ivan Enderlin c7f6190cff feat(base): Detecting invalid states in room upgrades.
This patch adds the `check_tombstone` response processor to
detect invalid state with room upgrades. One can check the new
`InconsistentTombstonedRooms` error to learn more about the detected
patterns.
2025-06-03 15:04:26 +02:00
Ivan Enderlin 5ccb1c6fa8 fix(base): Fix the Debug implementation of RoomUpdates.
The field of `RoomUpdates` has been renamed, but the `Debug`
implementation does not reflect that change. This patch fixes that.
2025-06-03 15:04:26 +02:00
Ivan Enderlin b77a02662d feat(base): Add RoomUpdates::iter_all_room_ids.
This patch adds the `RoomUpdates::iter_all_room_ids` method, to iterate
over all IDs of rooms that have received an update.
2025-06-03 15:04:26 +02:00
Damir Jelić 13306be4ed fix(multiverse): Wait for the join task to finish before switching the view 2025-06-03 14:07:37 +02:00
Yousef Moazzam 491f81c376 test: remove unnecessary image info field values 2025-06-03 13:19:34 +02:00
Yousef Moazzam 703c01004c test: remove unnecessary server timestamp field on sticker event 2025-06-03 13:19:34 +02:00
Yousef Moazzam b1d34763d4 test: create timeline event with EventBuilder method 2025-06-03 13:19:34 +02:00
Yousef Moazzam c4aa200f19 test: create sticker event with EventFactory 2025-06-03 13:19:34 +02:00
Yousef Moazzam a099879563 test: add reply thread relation method to sticker event builder 2025-06-03 13:19:34 +02:00
Yousef Moazzam b6569762db test: add sticker event method to EventFactory 2025-06-03 13:19:34 +02:00
Jorge Martín edabb2362b refactor: revert some method removals in SendRequest 2025-06-03 12:59:00 +02:00
Jorge Martín 8a5d4f0d82 test: Increase delay to fix code coverage failure 2025-06-03 12:59:00 +02:00
Jorge Martín 12aed8dc67 test: fix tests after adding the media config check 2025-06-03 12:59:00 +02:00
Jorge Martín 7d03d4ce0d feat(ffi): Add Client::get_max_media_upload_size function
This allows the clients to know the max upload size for a media file and try to compress if it's too large for the homeserver.
2025-06-03 12:59:00 +02:00
Jorge Martín 2680dc65fd fix(sdk): check max_upload_size before attempting to upload any media 2025-06-03 12:59:00 +02:00
Richard van der Hoff a1e2eed467 sdk: Add ClientBuilder::with_enable_share_history_on_invite (#5141)
Replace `experimental-share-history-on-invite` feature flag with a
runtime flag on the `Client`.
2025-06-03 11:36:48 +01:00
Benjamin Bouvier 5600ce7a77 fix(event cache): after adding a thread summary in memory, also save the result in the store 2025-06-03 12:22:21 +02:00
Benjamin Bouvier f28a2b1cc3 fix(event cache): after redacting an in-memory event, also save the result in the store 2025-06-03 12:22:21 +02:00
Benjamin Bouvier 1a07ec22b8 test(event cache): move tests which require the cross process lock under a different test mod
This avoids a few `use` statements within the test functions themselves,
and helps finding out which tests are integration tests.
2025-06-03 12:22:21 +02:00
dependabot[bot] 7b8671d82c chore(deps): bump tj-actions/changed-files
Bumps [tj-actions/changed-files](https://github.com/tj-actions/changed-files) from c6634ca281a9fc05b03bee224ba00910cb78ab6e to 115870536a85eaf050e369291c7895748ff12aea.
- [Release notes](https://github.com/tj-actions/changed-files/releases)
- [Changelog](https://github.com/tj-actions/changed-files/blob/main/HISTORY.md)
- [Commits](https://github.com/tj-actions/changed-files/compare/c6634ca281a9fc05b03bee224ba00910cb78ab6e...115870536a85eaf050e369291c7895748ff12aea)

---
updated-dependencies:
- dependency-name: tj-actions/changed-files
  dependency-version: 115870536a85eaf050e369291c7895748ff12aea
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-03 11:17:12 +02:00
Daniel Salinas 0f877a3e80 feat(wasm): Replace async_trait with wasm aware cfg conditional 2025-06-02 23:07:05 +02:00
Daniel Salinas c6e55c1a36 Mechanical move from target_arch="wasm32" to target_family="wasm" 2025-06-02 17:27:34 +02:00
Benjamin Bouvier 40648f6998 chore: formatting, clippy and review comments 2025-06-02 16:24:25 +02:00
Benjamin Bouvier 58b46813d6 feat(event cache): when we see a thread reply, add a thread summary to the thread root 2025-06-02 16:24:25 +02:00
Benjamin Bouvier f2a90cb921 test: use helpers to create a bundled edit and thread summary 2025-06-02 16:24:25 +02:00
Benjamin Bouvier efda26ef6f feat(timeline): forward the TimelineEvent::thread_summary to timeline items
Right now, we're not passing the latest event yet, but we could improve
that later!
2025-06-02 16:24:25 +02:00
Benjamin Bouvier 433209ca9b feat(common): always extract a bundled thread summary when creating or deserializing a timeline event 2025-06-02 16:24:25 +02:00
Benjamin Bouvier 1680891982 feat(common): add helper to extract a bundled thread summary 2025-06-02 16:24:25 +02:00
Benjamin Bouvier 3c965ed56e feat(common): add a ThreadSummary field to TimelineEvent
It can be either known to be there or not there, or in an unknown state,
hence a tiny enum making this very explicit.
2025-06-02 16:24:25 +02:00
Benjamin Bouvier 0bb2c44254 feat(common): don't serialize push actions if there's none
If the vec of actions is defined (Some) but empty, then it means we
could determine there are no push actions. It is a slight optimization
to not serialize them, in this case; otherwise, this can result in many
serialized empty action vector, in the event cache's persistent storage.
2025-06-02 16:24:25 +02:00
Benjamin Bouvier 23cdcaf5c8 feat(common): add helpers to extract only the thread root from a raw event 2025-06-02 16:24:25 +02:00
Benjamin Bouvier ebc7396334 refactor(sdk): remove unused TimelineEvent ctor
It was intended for test purposes, but it seems it's unused, so let's
get rid of it.
2025-06-02 16:24:25 +02:00
Benjamin Bouvier c7234b6f13 doc: make the self type clearer in doc comment of TimelineEvent 2025-06-02 16:24:25 +02:00
Richard van der Hoff 56be9dec59 multiverse: expand user names when inviting (#5146)
When the user does an `/invite`, if the target user doesn't start with
an `@`, try expanding it as a user on the local server.

This makes it much easier when repeatedly testing inviting!
2025-06-02 14:41:20 +01:00
Richard van der Hoff 2fa6a98052 multiverse: write logs to session dir (#5145)
Rather than always writing the logs to `/tmp`, write them to the session
directory. The session directory defaults to `/tmp` so by default this
will do the same as before, but if you override the session path on the
commandline, the logs will get stored alongside the stores and caches.

This is particularly useful when running two instances of multiverse,
and you want them to put their logs in different places.
2025-06-02 14:41:11 +01:00
Yousef Moazzam f03407fdb9 test: remove unnecessary server timestamp fields on events 2025-06-02 14:59:23 +02:00
Yousef Moazzam fd4fd3c4f9 test: add timeline events in bulk to room builder 2025-06-02 14:59:23 +02:00
Yousef Moazzam a9513e6f73 test: remove import of unused sync_timeline_event! macro in timeline subscribe test module 2025-06-02 14:59:23 +02:00
Yousef Moazzam 5f0bcef5ce test: create events with EventFactory in profile updates test 2025-06-02 14:59:23 +02:00
Yousef Moazzam 96049f41a5 test: create events with EventFactory in event filter test 2025-06-02 14:59:23 +02:00
Daniel Salinas ba8998623e Fix annotations on comments for new StreamExt
Hook up use of new extension in matrix-sdk-ffi crate
2025-06-02 12:26:52 +02:00
Daniel Salinas d6bf3019f9 StreamExt that supports wasm platforms
The .boxed() method requires a Send trait that makes it
unusable on Wasm platforms. This re-exports the existing StreamExt,
while providing a new extension for the wasm family of targets.
2025-06-02 12:26:52 +02:00
Damir Jelić ef037631a1 refactor(crypto): Simplify the checking of device keys when decrypting Olm events 2025-05-30 15:45:27 +02:00
Damir Jelić 42ade32bea feat(sdk): Fallback to the device keys in the Olm event for room key bundles
This makes it possible to correctly accept a historic room key bundle if
we previously didn't know about the device of the sender of the bundle.
2025-05-30 15:45:27 +02:00
Damir Jelić 37d7e26929 feat(sdk): Ensure that we have all the devices of a user we invite
This makes it possible to correctly share a historic room key bundle with the
invited user without sharing another room with the user.
2025-05-30 15:45:27 +02:00
Robin e51dceb399 refactor(widget): Improve wording of ApiVersion docs 2025-05-30 15:32:35 +02:00
Robin cee0129225 feat(widget): Distinguish room state and timeline events
This is an implementation of an update to MSC2762 (https://github.com/matrix-org/matrix-spec-proposals/pull/4237). It changes the widget driver to split state updates out into an `update_state` action and use the `send_event` action exclusively for forwarding timeline events. Accordingly, `read_events` now always reads from /messages, never the state store.
2025-05-30 15:32:35 +02:00
Robin ef36665d7d doc(widget): Note that capability renegotiation is unimplemented 2025-05-30 15:32:35 +02:00
Robin e45e357841 refactor(widget): Extract method for processing requested capabilities 2025-05-30 15:32:35 +02:00
Robin 6657501ef4 refactor(widget): Extract method for acquire capabilities response 2025-05-30 15:32:35 +02:00
Robin 69e8f1e86c refactor(widget): Extract method for message-like event reading response 2025-05-30 15:32:35 +02:00
Robin e613fc269f refactor(widget): Remove 'Matrix' from some identifiers
Just making these a bit less verbose and more consistent with surrounding identifiers.
2025-05-30 15:32:35 +02:00
Robin 5c7566c6c9 refactor(widget): Allow state events to be converted to filter inputs
So that when I need to do this (in later commits) I don't have to cast.
2025-05-30 15:32:35 +02:00
Robin aba0adf18d refactor(tests): Move some JSON into static items
I want to use this JSON in multiple tests.
2025-05-30 15:32:35 +02:00
Robin 2c8e71e560 refactor(tests): Allow converting EventBuilder to state 2025-05-30 15:32:35 +02:00
Robin 6f683d3cde refactor(tests): Accept more types for sync builder state events
Refactoring the test event implementation to use the From trait rather than ad-hoc methods along the way.
2025-05-30 15:32:35 +02:00
Jonas Platte 9242d1869a refactor: Use native async fn in traits for BackingStore 2025-05-30 10:48:06 +02:00
Daniel Salinas 59d632fd45 feat(wasm): Improve wasm join handle to implement more tokio methods (#5088)
This change adds support for the abort/abort_handle/is_finished methods
onto the JoinHandle shim for Wasm targets.

Signed-off-by: Daniel Salinas
2025-05-29 14:22:38 +00:00
Richard van der Hoff c55652d327 crypto: changelog fixes (#5136)
Put one change in the right place in the changelog, and add missing PR
links.
2025-05-29 14:22:00 +01:00
Jonas Platte 0220689964 refactor: Wrap EncryptionInfo in Arc
It's >100 bytes large and often optional, so it makes sense to put it
on the heap to reduce the size of structs with such optional fields,
and the stack size of functions with such optional parameters.
It's also cloned in a couple places in the UI crate, so it probably
makes sense to just always refcount it.

This started as a clippy suggestion to box PendingEdit inside
AggregationKind::Edit.
2025-05-29 14:08:10 +02:00
Jonas Platte d8969db30a refactor: Increase readability of WidgetMachine::process
Based on a clippy suggestion.
2025-05-29 13:19:59 +02:00
Jonas Platte 8eec683793 refactor: Use inline format arguments more
Automated with cargo clippy --fix --workspace --all-targets.
2025-05-29 13:19:59 +02:00
Jonas Platte 4705389ab7 refactor: Use native async fn in traits for testing traits 2025-05-29 11:45:16 +02:00
Damir Jelić db931c5d5c chore: Bump our decancer version
This removes the paste dependency decancer had. We still need to have a
denyc exception for paste because of rmp-serde and ratatui.
2025-05-29 11:40:37 +02:00
Jonas Platte 9a0b56ad1a refactor(ci): Don't rerun most CI jobs when un-drafting a PR
This only makes sense to do for workflows that branch off of
github.event.pull_request.draft, which only bindings_ci.yml does at this
point in time.
2025-05-29 11:05:03 +02:00
Jonas Platte 3c20ee41d6 chore: Fix clippy lints 2025-05-29 10:59:56 +02:00
Jorge Martín ed245a0cf0 refactor(ffi): When mapping ffi::StateEventContent, log any unsupported event types
The same was done for unsupported message-like event contents.
2025-05-29 09:54:39 +02:00
Jorge Martín 4626c4caaf refactor(ffi): When mapping ffi::MessageLikeEventContent, log any unsupported event types
At the moment, the logs just say 'Unsupported Event Type', which is not that helpful.
2025-05-29 09:54:39 +02:00
Ivan Enderlin 7cda6d2ea6 chore(sdk): Add more logs for Room::leave.
This patch adds a bit more logs in `Room::leave` to understand what's
happening for some users.
2025-05-28 14:03:05 +02:00
Jorge Martín 2ec15984a8 test: Improve NotificationClient tests using the modern test utils 2025-05-28 12:32:58 +02:00
Yousef Moazzam 01f035d574 Test: Replace sync_timeline_event! with EventFactory for events in event item tests (#5093)
Part of #3716

I did notice that the `sender` and `member` methods have some overlap in
what values get set for the "sender" and "state key", and I tried to
make sure that in my changes to use `EventFactory` the original event
configuration is being replicated, so please do double-check me on that
note in particular.

Signed-off-by: Yousef Moazzam <yousefmoazzam@hotmail.co.uk>
2025-05-28 10:48:25 +02:00
Damir Jelić 53b01fb8a5 test: Enable the historic room key bundle storage test, except on WASM
The test was ignored since the functionality was only implemented for
the memory and SQLite store. This caused a bug in the SQLite
implementation to go unnoticed.

Let's just disable it for WASM since this is the only place where we
didn't yet implement the necessary methods.
2025-05-27 18:15:36 +02:00
Jorge Martín 79c47b4470 fix(sdk): Handle 520 HTTP status code as a permanent error
The status code is usually returned by Cloudflare to indicate an unknown server error, so we should cancel the upload and let the user retry if they want to.
2025-05-27 17:56:44 +02:00
Damir Jelić 089abec866 fix(sdk): Don't require the invite details to be present when accepting an room invite 2025-05-27 17:46:10 +02:00
Damir Jelić 064fd6cb0b fix(sqlite): Use the correct column name for the sender of bundled room keys 2025-05-27 17:46:10 +02:00
Damir Jelić 60d3b3d56b test: Finish up the shared history integration test 2025-05-27 17:46:10 +02:00
Damir Jelić 995838d9d3 refactor(tests): Move the shared history test into its own module 2025-05-27 17:46:10 +02:00
Damir Jelić 1d4d4bc741 refactor(tests): Create a submodule for the end-to-end encryption integration tests 2025-05-27 17:46:10 +02:00
Damir Jelić 41a5fd90f4 feat(tests): Add a macro to assert that a TimelineEventKind was encrypted 2025-05-27 17:46:10 +02:00
Damir Jelić 3d9d619f8b feat(sdk): Import the room keys we download from the shared history bundle 2025-05-27 17:46:10 +02:00
Damir Jelić af38f0d1ee refactor(crypto): Move the room key bundle import method under the store 2025-05-27 17:46:10 +02:00
Damir Jelić 091a5fb354 refactor(crypto): Clarify some things in the room key bundle import logic 2025-05-27 17:46:10 +02:00
Richard van der Hoff 8a1d6ce0eb feat(sdk): Attempt to download room key bundles when we accept an invite 2025-05-27 17:46:10 +02:00
Ivan Enderlin 0f5f24527b chore(ffi): Remove Room::is_tombstoned.
This patch removes the `Room::is_tombstoned` method as using
`Room::successor_room` plays the same role and its returned value is
always useful.
2025-05-27 17:35:31 +02:00
Ivan Enderlin da60c1488e feat(ffi): Add the DeduplicateVersions room list filter.
This patch adds `RoomListEntriesDynamicFilterKind::DeduplicateVersions`
to use `new_filter_deduplicate_versions`.
2025-05-27 17:35:31 +02:00
Ivan Enderlin f65893d65e doc(base): Remove a useless link reference. 2025-05-27 17:35:31 +02:00
Ivan Enderlin 3e89b6b8f9 feat(ffi): Add SuccessorRoom and PredecessorRoom.
This patch removes `RoomTombstoneInfo` and replaces it by
`SuccessorRoom`. This patch renames `RoomInfo::tombstone` to
`RoomInfo::success_room`.

This patch also implements `Room::successor_room()` and
`Room::predecessor_room()`, and adds documentation.
2025-05-27 17:35:31 +02:00
Mauro 7531167824 feat: Let the media preview config return an optional
This allows applications to decide what they'd like to do if there isn't a value present. It allows the application to decide what the default should be.
2025-05-27 16:24:41 +02:00
Ivan Enderlin d24e269ecc doc(ui): Fix typos. 2025-05-27 14:02:21 +02:00
Ivan Enderlin 88c18c5499 feat(ui): New Room List filter: deduplicate_versions.
This patch adds the new `deduplicate_versions`. This new filter will
filter out room versions that are outdated. Only the “active” versions
are kept.

A room version is considered active if and only if:

* the room is joined and has no successor,
* the room is joined and has a successor room that is invited or knocked,
* the room is left, invited, banned or knocked.

All other rooms are filtered out.
2025-05-27 14:02:21 +02:00
Ivan Enderlin d0f1e6ce6d chore(base): Expose the new SuccessorRoom and PredecessorRoom types.
This patch makes the `SuccessorRoom` and `PredecessorRoom` types public.
2025-05-27 14:02:21 +02:00
Johannes Marbach 10668f20b0 feat(send_queue): Implement sending of MSC4274 galleries (#4977)
This was broken out of
https://github.com/matrix-org/matrix-rust-sdk/pull/4838 and is a step
towards implementing
[MSC4274](https://github.com/matrix-org/matrix-spec-proposals/pull/4274).

* The entry point for sending galleries via the send queue is a new
method
[`RoomSendQueue::send_gallery`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-8752e86459c22cff470d7ca617240dcbdf222c3c6c98be2af2e43ddec071154cR362)
which is a generalization of `RoomSendQueue::send_attachment`.
* `send_gallery` takes as input parameters a
[`GalleryConfig`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-d38d74cec6159cf769c32bed496199146175f05428fc23ab13bc2c629900da3eR283)
(containing info about the gallery itself, such as its caption) and a
vector of
[`GalleryItemInfo`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-d38d74cec6159cf769c32bed496199146175f05428fc23ab13bc2c629900da3eR355)s
(containing info about each image / file / etc. in the gallery).
* `send_gallery` creates the gallery event content via
[`Room:make_message_event`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-474f20e47fdcf60feac3f839a81f82fbb2c1fd0bb406388b0262adb60216ce3bR2281)
which was renamed from `make_attachment_event` to reflect the fact that
it creates general `msgtype` events now.
* `send_gallery` maps the passed item infos into
[`GalleryItemQueueInfo`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-d569f54c7901b5cd660aae77045c80dabbd3c251f0fa5891530469f35941327aR2008)s.
This additional struct allows grouping all the metadata for a single
gallery item together.
* Finally `send_gallery` invokes
[`QueueStorage::push_gallery`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-d569f54c7901b5cd660aae77045c80dabbd3c251f0fa5891530469f35941327aR1294)
which is a generalization of `QueueStorage::push_media`.
* `send_gallery` pushes upload requests for the media and thumbnails to
the queue in a "daisy chain" manner. The first thumbnail (or media if no
thumbnail exists) is pushed as a `QueuedRequestKind::MediaUpload`. The
remaining thumbnails and media are pushed as
`DependentQueuedRequestKind::UploadFileOrThumbnail`s while chaining each
request to the previous one.
* Finally a
[`DependentQueuedRequestKind::FinishGallery`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-42a1a7ebe2446d916c9e013293bafc5eb16fd89bfe89248e3877ef031cc83ef2R265)
is pushed to finalize the gallery upload (analogous to the existing
`FinishUpload` for single media uploads).
* The `FinishGallery` request is handled in
[`QueueStorage::handle_dependent_finish_gallery_upload`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-8752e86459c22cff470d7ca617240dcbdf222c3c6c98be2af2e43ddec071154cR628)
which was modeled after `handle_dependent_finish_upload`.
* To be able to map the temporary event source for each gallery item to
the final `AccumulatedSentMediaInfo`, a hash map is used.
* Using the hash map, the gallery event is then updated to use the
actual media sources via
[`update_gallery_event_after_upload`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-8752e86459c22cff470d7ca617240dcbdf222c3c6c98be2af2e43ddec071154cR104)
and a new method
[`Room::make_gallery_item_type`](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-474f20e47fdcf60feac3f839a81f82fbb2c1fd0bb406388b0262adb60216ce3bR2303)
* An [integration
test](https://github.com/matrix-org/matrix-rust-sdk/pull/4977/files#diff-21532ad5467a69489d7913b8da7afd4d618b7e357ce94f769e6e60e395b58055R2048)
has been added to demonstrate the functionality.

This is relatively large, unfortunately, but including everything needed
to actually send the event made it possible to also add a test for it.
It would be nice if the amount of new code could be reduced but I'm
struggling a bit to find ways to integrate galleries with the existing
media uploads further.

- [x] Public API changes documented in changelogs (optional)

---------

Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-05-27 11:53:05 +02:00
Ivan Enderlin 2537f0a508 refactor(base): Create dispatch_room_member.
This patch extracts a bit of code from `dispatch` in a new response
processor: `dispatch_room_member`. The idea is to clarify the content of
`dispatch` itself.
2025-05-27 10:00:16 +02:00
Ivan Enderlin 1387772589 refactor(base): Remove a BTreeSet clone.
This patch moves the insertion of `new_user_ids` in
`updated_members_in_room` after the use of `new_user_ids` by
`update_or_set_if_room_is_newly_encrypted`. By moving it after, it saves
the need to clone it entirely, thus saving memory allocations.
2025-05-27 10:00:16 +02:00
Ivan Enderlin c4f9ef2e2e refactor(base): Improve dispatch_and_get_new_users.
This patch renames `dispatch_and_get_new_users` to `dispatch`. This
response processor no longer returns the new user IDs, but they are
written in a mutable reference argument. This argument is
typed by a new private trait: `NewUsers`. This trait is implemented on
`BTreeSet<OwnedUserId>` and on `()`. It helps to avoid allocations when
the new users are not needed.
2025-05-27 10:00:16 +02:00
Benjamin Bouvier acce75a6dc test: make the test for the previous commit more realistic
This reproduces the issue originally described, where it wasn't possible
to run a /members query in an event handler, because the sync lock was
taken at this point.
2025-05-27 09:09:41 +02:00
aeoncl 5e0704a7c7 fix(sliding sync): don't take the sync lock while handling events
Fixes #5091.
2025-05-27 09:09:41 +02:00
Benjamin Bouvier 206857bc9e feat(ffi): remove the state store when clearing caches
This is a dangerous operation, and requires that the sync service must
be stopped while we're touching this. Since this is an internal method,
that shouldn't be used in most clients anyways (as it usually papers
over actual issues happening elsewhere, on the server for instance), I
kept it simple with a scary doc comment explaining the preconditions,
but we could assert them at runtime, with a little bit more effort.
2025-05-27 08:59:59 +02:00
Benjamin Bouvier 9e1ea5d7d3 feat(sdk): expose the state store database name 2025-05-27 08:59:59 +02:00
Hugh Nimmo-Smith e90b105b36 feat(sdk): Add support for MSC4286
This patch updates Ruma to include support for the mx-external-payment-details span attribute from MSC4286.
2025-05-27 08:47:56 +02:00
dependabot[bot] 40ffd404e8 chore(deps): bump tj-actions/changed-files
Bumps [tj-actions/changed-files](https://github.com/tj-actions/changed-files) from 480f49412651059a414a6a5c96887abb1877de8a to c6634ca281a9fc05b03bee224ba00910cb78ab6e.
- [Release notes](https://github.com/tj-actions/changed-files/releases)
- [Changelog](https://github.com/tj-actions/changed-files/blob/main/HISTORY.md)
- [Commits](https://github.com/tj-actions/changed-files/compare/480f49412651059a414a6a5c96887abb1877de8a...c6634ca281a9fc05b03bee224ba00910cb78ab6e)

---
updated-dependencies:
- dependency-name: tj-actions/changed-files
  dependency-version: c6634ca281a9fc05b03bee224ba00910cb78ab6e
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-26 17:05:29 +02:00
Benjamin Bouvier b6b9dc8c1a fix(test): make the test_monthly_divider_mode test pass all on timezones 2025-05-26 15:39:04 +02:00
Benjamin Bouvier 4a397f5ab4 refactor(ffi): pass the UTD hook when constructing a Room from the room list (again!) 2025-05-26 14:48:16 +02:00
Benjamin Bouvier be927730fa refactor(ffi): get rid of RoomListItem
It is simply a Room now.
2025-05-26 14:48:16 +02:00
Benjamin Bouvier 81036da44c refactor(ffi): rename the SDK Room import to SdkRoom 2025-05-26 14:48:16 +02:00
Benjamin Bouvier b016f60e46 refactor(ffi): move methods from RoomListItem to Room
Only code motion. Most methods already existed on the `Room` impl block.
2025-05-26 14:48:16 +02:00
Benjamin Bouvier cd76cec089 refactor(ffi): also pass the UTD hook to the notification client 2025-05-26 14:48:16 +02:00
Benjamin Bouvier 820c73dd2f refactor(ffi): get rid of the timeline stored in a Room 2025-05-26 14:48:16 +02:00
Benjamin Bouvier 42a4a6c1a8 refactor(ui): get rid of the RoomListService::Room wrapper
It's just a room, now! Since there were some users of the
`latest_event()` that returned an `EventTimelineItem`, I kept this
method as a method in the Room trait extension that's in the UI crate,
so it's still convenient to use.
2025-05-26 14:48:16 +02:00
Ivan Enderlin eec9a067be fix(sdk): Continue leaving a room if server replies with 403.
This patch updates `Room::leave` to not early return when the server
returns a 403 error code on `/leave`. Indeed, if the user doesn't have
the permissions to leave a room, it's impossible for they to leave it.
Let's consider it's fine to ignore this particular error and continue
the process of leaving the room.
2025-05-26 14:42:17 +02:00
Jorge Martín e53eaf4213 refactor: Fetch the ignored user list account data from the store for Client::is_user_ignored
Also move it to `BaseClient` instead.
2025-05-26 13:02:58 +02:00
Jorge Martín a3725b6b24 fix: Do not retrieve notification events sent by ignored users 2025-05-26 13:02:58 +02:00
Stefan Ceriu f0c7370637 feat(ffi): expose the inviter directly on the room to avoid having to fetch the room preview
The room preview doesn't actually contain the inviter but instead retrieves it from the room invite details.
2025-05-24 10:49:44 +03:00
Yousef Moazzam f108840e28 test: put repeated event field values into variables 2025-05-23 14:12:14 +01:00
Yousef Moazzam f4f63a7e41 test: create plain text room event with EventFactory 2025-05-23 14:12:14 +01:00
Ivan Enderlin 26afd890ce test(base): Use EventFactory instead of JSON hardcoded value.
This patch updates two tests to use the `EventFactory` to replace JSON
hardcoded values to represent the events.
2025-05-23 11:35:53 +02:00
Ivan Enderlin bfac815a5e test: EventBuilder<RoomCreateEventContent> can set predecessor.
This patch adds the `predecessor` and `no_predecessor` methods on
`EventBuilder<RoomCreateEventContent>`. This is helpful to configure the
`predecessor` field.
2025-05-23 11:35:53 +02:00
Ivan Enderlin 95e8d0589b test: Fix EventFactory::create.
This patch fixes `EventFactory::create` where the `m.room.create` wasn't
created as a state-event (the `state_key` field was missing).

Also, it uses the `creator_user_id` in the `sender` field if no sender
was given.
2025-05-23 11:35:53 +02:00
Ivan Enderlin 16a923edda test: Simplify EventBuilder::into_raw_timeline.
This patch simplifies `EventBuilder::into_raw_timeline`. It is exactly
like `EventBuilder::into_raw`, so let's use it.
2025-05-23 11:35:53 +02:00
Ivan Enderlin 9c227c2321 feat(base): Add Room::successor_room and Room::predecessor_room.
First off, this patch renames `Room::tombstone` to
`Room::tombstone_content` (to be consistent with other methods, such as
`Room::create_content`).

Second, this patch adds the `Room::successor_room` and
`Room::predecessor_room` methods, along with the `SuccessorRoom` and
`PredecessorRoom` types. This naming more or less comes from the Matrix
specification:

- the term _predecessor_ is part of the specification,
- the term _successor_ isn't present _per se_, the words _replacement
  room_ are used instead, but I prefer _successor_ as it brings a nice
  symmetry with _predecessor_.
2025-05-23 11:35:53 +02:00
Ivan Enderlin 5d617da74c chore(base): Move the Room::*tombstone* methods in new tombstone module.
This patch moves the `Room::is_tombstoned` and `Room::tombstone` methods
in the new `tombstone` module.
2025-05-23 11:35:53 +02:00
Jonas Platte 3aa356dcd6 chore: Use shorter syntax for workspace inheritance where possible 2025-05-23 10:23:36 +02:00
Jonas Platte 491f7cd529 chore: Clean up Cargo.toml formatting 2025-05-23 10:23:36 +02:00
Timo 6d5ad4eddc feat(widget-driver): Add to-device support
The widget Driver should be able to send and receive to-device events.
This is useful for element call encryption keys.

This PR focusses on the widget driver and machine logic. To
send/communicate the events from the widget to the driver.

It skips any encryption logic. Some of the encryption logic will be part
of crypto crate and the code in the widget driver crate should be kept
minimal once the crypto crate is ready.

---------

Co-authored-by: Valere <bill.carson@valrsoft.com>
2025-05-22 13:38:28 +02:00
Yousef Moazzam ec638e017b test: remove import of unused sync_timeline_event! macro in shield test 2025-05-22 12:46:56 +02:00
Yousef Moazzam 8f693f4615 test: create plain text room event with EventFactory 2025-05-22 12:46:56 +02:00
Jorge Martín fe8f77ed93 refactor: when leaving an Invited room also forget it
This behaviour was added only at the `RoomPreview::leave` method, but since we're slowly moving away from it we should move the forget action to the `Room::leave` method instead
2025-05-22 12:07:19 +02:00
Benjamin Bouvier 5c6238f132 chore(deps): bump wasm-bindgen-test 2025-05-22 11:50:13 +02:00
Benjamin Bouvier a5b932d086 chore(base): rename config file to config.toml
There was a warning in the console about this, when running the
following: cargo xtask ci wasm-pack matrix-sdk-base
2025-05-22 11:50:13 +02:00
Benjamin Bouvier b0e8b8a532 chore(deps): bump web-sys 2025-05-22 11:50:13 +02:00
Benjamin Bouvier 2984030f90 chore(ffi): configure the sentry dependency differently on android
On Android, we should use rustls instead of native-tls; this requires
unsetting the default features of the `sentry` crate, and specifying
them by hand instead.

For consistency, I've done the same for the non-android sentry
dependency.
2025-05-22 11:50:13 +02:00
Benjamin Bouvier a3c82e9087 chore(deps): bump reqwest to 0.12.15 2025-05-22 11:50:13 +02:00
Benjamin Bouvier 56082f93d0 chore(sdk): forward "database is busy" errors to sentry 2025-05-22 11:50:13 +02:00
Benjamin Bouvier c8474511a7 feat(ffi): add support for sentry logging 2025-05-22 11:50:13 +02:00
Ivan Enderlin 1348525447 test(base): Fix a test. 2025-05-21 17:26:52 +02:00
Ivan Enderlin 56f9b2d9f6 chore(base): Rename rooms to room.
This patch renames the `rooms` module into `room`. It contains a single
kind of `Room`.
2025-05-21 17:26:52 +02:00
Ivan Enderlin b18680b853 test(base): Use SystemTime from web_time for Wasm. 2025-05-21 17:26:52 +02:00
Ivan Enderlin 72b2763dad chore(base): Run rustfmt from nightly. 2025-05-21 17:26:52 +02:00
Ivan Enderlin 7278a36704 chore(base): Move Room::get_member_hints in the display_name module.
This patch moves the `Room::get_member_hints` method inside the newly
created `display_name` module. That way it is isolated from the rest of
the codebase.
2025-05-21 17:26:52 +02:00
Ivan Enderlin bd9a895089 chore(base): Move Room::*room_call* methods in the new call module.
This patch moves the `Room::has_active_room_call` and
`Room::active_room_call_participants` methods into the new `call`
module. This patch also moves the associated tests in this new module.
2025-05-21 17:26:52 +02:00
Ivan Enderlin a71e7923e0 chore(base): Move the Room::MAX_ENCRYPTED_EVENTS constant in latest_event.
This patch moves the declaration of the `Room::MAX_ENCRYPTED_TESTS`
constants in the `latest_event` module.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 2433e91a6c chore(base): Move the m.room.create wrapper types in the new create module.
This patch moves the `m.room.create` wrapper types, aka
`RoomCreateWithCreatorEventContent` type and siblings, in the new
`create` module.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 48d2a1543c chore(base): Move code inside the same module.
This patch puts tests at the end of the file.
2025-05-21 17:26:52 +02:00
Ivan Enderlin bcd75362f7 chore(base): Move Room::*knock* methods into the new knock module.
This patch moves the `Room::*knock*` methods into the new `knock`
module.

The idea is to group API by “theme” to get smaller modules and more
organised code.
2025-05-21 17:26:52 +02:00
Ivan Enderlin f4488e42a2 chore(base): Move Room::state and sibling types into new state module.
This patch moves the `Room::state` method, along with the ``RoomState`
and `RoomStateFilter` types into the new `state` module. This patch also
moves the tests in this new module.

The idea is to group API by “theme” to get smaller modules and more
organised code.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 3d13b60b68 chore(base): Merge rooms::normal into rooms.
This patch merges the `rooms/normal.rs` file into `rooms/mod.rs`.

The name `normal` is present for historical reasons that no longer stand
today. This is no needed anymore. Let's simplify the modules.
2025-05-21 17:26:52 +02:00
Ivan Enderlin f1c54d1e27 chore(base): Move tests in the correct module.
This patch move tests about the `RoomDisplayName` in the newly created
`display_name` module.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 27edb163e9 chore(base): Move tests in the correct module.
This patch moves tests about `RoomNotableTags` in the newly created
`tags` module.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 6d9d202701 chore(base): Move Room::*latest_event*() inside the new latest_event module.
This patch moves everything related to the `Room` latest event API
inside the new `latest_event` module. This patch also moves the tests.
The idea is to get a smaller `rooms::normal` module, and to clarify the
code by grouping `Room` APIs by “theme”.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 61d99ef709 chore(base): Move everything related to Room members in members.
This patch moves all types and methods used by or implemented on `Room`
inside the existing `members` module.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 6f031261d5 chore(base): Move Room::is_favourite and ::is_low_priority into new tags module.
This patch moves the  Room::is_favourite` and `::is_low_priority`, along
with the `RoomNotableTags` into the new `tags` module. This patch also
moves the tests in this new module.

The idea is to group API by “theme” to get smaller modules and more
organised code.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 4a57044680 chore(base): Move Room::encryption_* mtehods into new encryption module.
This patch moves the `Room::encryption_state()` and
`Room::encryption_settings()` methods, and the sibling types, into a new
`encryption` module. This patch also moves the tests in this new module.
The idea is to group `Room` API by “theme” in modules, to clarify the
code.
2025-05-21 17:26:52 +02:00
Ivan Enderlin d5c0e209fc chore(base): Move Room::display_name() and siblings into new display_name module.
This patch moves the `Room::display_name()` method, and all the
siblings, into a new `display_name` module. It includes types like
`RoomDisplayName`, `UpdatedRoomDisplayName`, `RoomSummary` etc. This
patch also moves the tests in this new module. The idea is to group
`Room` API by “theme” in modules, to clarify the code and to make the
big `rooms::normal` module smaller.
2025-05-21 17:26:52 +02:00
Ivan Enderlin 737654549b chore(base): Move the Room's room info related methods and tests in room_info.
This patch moves the `Room::subscribe_info`, `::clone_info` and
`::set_room_info` methods from the `rooms::normal` module to the
`rooms::room_info` module. This patch also moves the tests related to
room info inside `room_info`.
2025-05-21 17:26:52 +02:00
Ivan Enderlin cc34603864 chore(base): Move RoomInfoNotableUpdate* inside room_info.
This patch moves the `RoomInfoNotableUpdate` and
`RoomInfoNotableUpdateReasons` types inside the `room_info` module.
2025-05-21 17:26:52 +02:00
Ivan Enderlin bad82ccd42 doc(ui): Explain why m.room.create is necessary.
This patch explains why having `m.room.create` is necessary. It's not
only about the room previews, but also about the room versions, and thus
the tombstoned rooms.
2025-05-21 17:26:52 +02:00
Ivan Enderlin d71cd68a90 refactor(base): Rename RoomInfo::version to data_format_version.
This patch renames the `RoomInfo::version` field to
`data_format_version` to avoid all possible confusion with the
`room_version` (from `m.room.create`).
2025-05-21 17:26:52 +02:00
Benjamin Bouvier 726111b073 refactor(timeline): group all the parameters for a remote echo in TimelineAction::from_content 2025-05-21 16:59:41 +02:00
Benjamin Bouvier 298fa7d5d2 feat(timeline): pass the encryption info for a bundled edit when constructing the edit aggregation
This should properly update shields in case the bundled edit was
correctly decrypted.
2025-05-21 16:59:41 +02:00
Benjamin Bouvier 4a627baae8 feat(timeline): indicate when the replied-to event is not a standalone item
If the replied-to event is an aggregation, the
`RepliedToEvent::try_from_timeline_event` will now return `Ok(None)`,
and the caller may handle this as they please.

In the FFI layer, this will be filled with an error message indicating
that the event is unsupported.
2025-05-21 15:52:31 +02:00
Benjamin Bouvier 560e33c27b refactor(timeline): deduplicate parsing of events when making a RepliedToEvent 2025-05-21 15:52:31 +02:00
Stefan Ceriu d84cf0614d change(ffi): return errors if the client or utd delegates were already set 2025-05-21 16:38:20 +03:00
Stefan Ceriu 3f1bc2591e chore(ffi): report an error if the timeline is set to report UTDs but the hook manager isn't configured 2025-05-21 16:38:20 +03:00
Stefan Ceriu 8e83b724da chore(ffi): rename the utd_hook to utd_hook_manager 2025-05-21 16:38:20 +03:00
Stefan Ceriu 767b10f5e2 change(ffi): remove now unused ClientDelegate did_refresh_tokens callback (dropped in favor of the ClientSessionDelegate) 2025-05-21 16:38:20 +03:00
Stefan Ceriu 4e2b5562f1 change(ffi): use a OnceLock to guard against multiple settings of the ClientDelegate 2025-05-21 16:38:20 +03:00
Stefan Ceriu 8ef471b492 chore(multiverse): simplify marking a room as read 2025-05-21 16:38:20 +03:00
Stefan Ceriu de6998dbe0 change(ffi): move the UTD delegate directly to the client for ease of use 2025-05-21 16:38:20 +03:00
Stefan Ceriu e48b1f6056 change(ffi): stop retrieving room list last messages from through the timeline
As per the plan defined in #4718:

```
the room_list_service::room::RoomInner shouldn't make use of its inner timeline;
it's only used in a direct getter, or to compute the latest room event, but it's not working
as intended, since local echoes aren't properly displayed in the room list.
This non-working feature can be removed, in favor of #4112
```
2025-05-21 16:38:20 +03:00
Stefan Ceriu 7074110780 change(ffi): remove the UTD manager from the sync service, room list service and room list items 2025-05-21 16:38:20 +03:00
Stefan Ceriu c90d272374 change(ffi): add timeline configuration option for reporting UTDs 2025-05-21 16:38:20 +03:00
Stefan Ceriu e6dc203c4d change(ffi): pass the client utd manager down into the timeline builder 2025-05-21 16:38:20 +03:00
Stefan Ceriu 195ee35eea change(ffi): move the utd hook from the sync service to the client 2025-05-21 16:38:20 +03:00
Stefan Ceriu 70122a4407 change(ui): stop relying on a room's stored timeline for marking it as read 2025-05-21 16:38:20 +03:00
Stefan Ceriu f2ca0697af chore(ui): remove the timeline's builder method and make the builder's constructor public 2025-05-21 16:38:20 +03:00
Kévin Commaille 9f196be2f6 Fix doc link
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille 254d86bc45 refactor(ui): Set room as variable instead of calling self.room() every time
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille a8dcea6931 refactor(sdk): Make Room::set_unread_flag() a no-op if the unread flag already has the wanted value
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille eed04ecdb3 chore: Add changelog entries for #5055
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille c131e0cfe5 test(ui): Add tests for unsetting the unread flag when sending receipts
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille 5f01c72a48 refactor(ui): Use the new mock endpoints in tests
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille bf7d5e7841 feat(ui): Unset the unread flag when sending unthreaded receipts in Timeline
Updates the unread flag or the room in `Timeline::send_single_receipt()`
and `Timeline::send_multiple_receipts()` if the room is marked as unread
and the receipts are unthreaded.

Updates it also in `Timeline::mark_as_read()`, even if there is no
latest event ID.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille dff1886015 test(sdk): Add tests for unsetting the unread flag when sending receipts
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille 14a73dc932 refactor(sdk): Use new mock endpoints for tests
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille 51be581d48 feat(test): Add RoomAccountDataTestEvent::MarkedUnread
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille 0a41febe15 test(sdk): Mock endpoints for sending receipts and room account data
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Kévin Commaille 63eb429843 feat(sdk): Unset the unread flag when sending unthreaded receipts in Room
Updates the unread flag or the room in `Room::send_single_receipt()` and
`Room::send_multiple_receipts()` if the room is marked as unread and the
receipts are unthreaded.

Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-21 13:51:48 +02:00
Mauro 91815ab678 feat(bindings): added APIs to get the media preview config from the store 2025-05-21 12:15:17 +02:00
Benjamin Bouvier a98f71ed0c feat(timeline): handle live aggregations on non-live timelines (#5060)
This makes it possible to handle reactions/redactions/edits/etc. on
non-live timelines. As a result, the pinned and focused timelines will
now get live reactions/redactions and so on. This makes it possible to
also have the thread timelines handle those live events, although it's
unclear how it will pane out in the end, when the event cache is also
involved.
2025-05-20 18:03:57 +02:00
Benjamin Bouvier 6f8b744c24 refactor(timeline): address review comments 2025-05-20 13:50:02 +02:00
Benjamin Bouvier 5e9c76f476 refactor(timeline): avoid cloning of relates_to for room messages
This can be done by splitting the handling of the msgtype/mentions from
the handling of the `relates_to` field, requiring a few API changes here
and there.
2025-05-20 13:50:02 +02:00
Benjamin Bouvier 4fd0f2a32c refactor(timeline): slightly optimize flow for saving a bundled edit
We only need the edit_json if we're about to save the edit aggregation.
Likewise, if there's no current event id (i.e. the event being handled
is a local echo), then we don't need to even try to extract anything
from the bundle information.
2025-05-20 13:50:02 +02:00
Benjamin Bouvier 74d5d6e265 refactor(timeline): group extracting the reply and thread root
The poll events's `related_to` field is a `RelationWithoutReplacement`,
while the two others are `Relation<C>`, where `C` is the event content
type (in case it was replacement). As a matter of fact, we try
converting the `Relation<C>` into a `RelationWithoutReplacement` (which
unfortunately requires cloning, which is wasteful if the relation was a
replacement indeed), and then we can use a single function to extract
the reply information and thread root info, for all three.
2025-05-20 13:50:02 +02:00
Benjamin Bouvier caa53be00e optimize(timeline): find the position of an event by starting from the end 2025-05-20 13:50:02 +02:00
Benjamin Bouvier b3086accd5 refactor(timeline): hey, i can actually remove this pending_edits field now 2025-05-20 13:50:02 +02:00
Benjamin Bouvier f010587201 chore: make clippy happy
bleh.
2025-05-20 13:50:02 +02:00
Benjamin Bouvier 2af751d8c6 optimize(timeline): avoid one clone if a new item has pending aggregations 2025-05-20 13:50:02 +02:00
Benjamin Bouvier f36f9915d1 refactor(timeline): simplify a few functions as a result of not providing the edit json ahead of time 2025-05-20 13:50:02 +02:00
Benjamin Bouvier e8f8e7bfd6 fix(timeline): properly update encryption info upon edit
To be fair, this is a regression from a previous commit in this PR.
2025-05-20 13:50:02 +02:00
Benjamin Bouvier dbe23777a0 refactor(timeline): use the aggregations manager for handling edits 2025-05-20 13:50:02 +02:00
Benjamin Bouvier b7191e3dc2 refactor(timeline): have Aggregations::try_remove_aggregation also take care of updating the item 2025-05-20 13:50:02 +02:00
Benjamin Bouvier 56ce93ce72 refactor(timeline): simplify a bit mark_aggregation_as_sent by having it do more work
This avoids another struct definition, and items are going to be needed
for edits anyways.
2025-05-20 13:50:02 +02:00
Benjamin Bouvier 9cbc674cf2 optimize(timeline): don't eagerly clone an EventTimelineItem before applying an aggregation onto it 2025-05-20 13:50:02 +02:00
Benjamin Bouvier 16fe53c40d refactor!(timeline): have TimelineItem::reactions() return an Option<&ReactionsByKeyBySender> instead of owned non-optional 2025-05-20 13:50:02 +02:00
Benjamin Bouvier 1b581d52e8 refactor(timeline): rename Aggregations::apply to Aggregations::apply_all
It applies *all* the stashed aggregations for a given event timeline
item.
2025-05-20 13:50:02 +02:00
Benjamin Bouvier dd6604e9f3 feat(timeline): handle redaction in the pending aggregations
This allows having a redaction event come before the related event, and
still handle it when the redacted event shows up.
2025-05-20 13:50:02 +02:00
Yousef Moazzam f173510482 test: Replace sync_timeline_event! with EventFactory for beacon events in room integration tests 2025-05-20 12:31:23 +02:00
Benjamin Bouvier 905d9b9aba refactor(timeline): don't reload a pinned event timeline that hasn't changed since the previous time 2025-05-20 10:49:08 +02:00
Benjamin Bouvier 810056cd4d refactor(timeline): add logging for the pinned events task 2025-05-20 10:49:08 +02:00
Richard van der Hoff 4d2c261ff8 crypto: rewrite check_sender_trust_requirement to use VerificationState (#5044)
There are two reasons for this.

Firstly. we've already done a bunch of work to map `SenderData` into a
`VerificationState`, and the decision tree from `VerificationState` to
allow/reject is simpler than going from `SenderData`, even if we have to
fudge it a bit to get the "legacy" flag. (Note that it allows us to get
rid of an `unreachable!` panic.)

Secondly, `VerficationState` represents the state of an *event*, whereas
`SenderData` is about the session as a whole. A session can be fine,
whilst events (claiming to be) encrypted with it can be suspect. What we
want here is to check a specific message. Currently, this doesn't make
any functional difference, but conceptually it's cleaner to check the
`VerificationState`.

Note that there are a bunch of tests for this method in
`matrix-sdk-crypto/src/machine/tests/decryption_verification_state.rs`,
called `test_decryption_trust_requirement`.
2025-05-19 18:35:21 +01:00
Ivan Enderlin d4626835bb chore(base): Fix formatting. 2025-05-19 16:09:32 +02:00
Ivan Enderlin f684883902 chore(base): Move RoomInfo inside another module.
This patch moves the `RoomInfo` type and its implementations inside the
`room_info` module.
2025-05-19 16:09:32 +02:00
Ivan Enderlin cf6316e290 chore(base): Move BaseRoomInfo into its own module.
This patch extracts the `BaseRoomInfo` type and its implementations
inside its own module.
2025-05-19 16:09:32 +02:00
Ivan Enderlin 12caf12d8a doc(base): Fix a typo. 2025-05-19 16:09:32 +02:00
Ivan Enderlin 9809e1b53c doc(sdk): Fix a typo in an inline comment. 2025-05-19 15:58:58 +02:00
Ivan Enderlin 80b7eed14b task(sdk): Fix warnings error without e2e-encryption. 2025-05-19 15:58:58 +02:00
Ivan Enderlin 6980dc5628 doc(sdk): Add #5047. 2025-05-19 15:58:58 +02:00
Ivan Enderlin 9366bc85e9 refactor(sdk): Remove FrozenSlidingSync.
This patch removes `FrozenSlidingSync`. Its unique field is supposed to
be stored in the crypto store.
2025-05-19 15:58:58 +02:00
Ivan Enderlin 0c193500d2 refactor(sdk): Remove SlidingSyncRoom \o/.
This patch FINALLY removes `SlidingSyncRoom`, youhou!
2025-05-19 15:58:58 +02:00
Ivan Enderlin 6c68cef6e0 refactor(sdk): Remove SlidingSync::rooms.
This patch removes the `SlidingSync::rooms` field. A cascade of removal
happens, and many part of the code is simplified. The most notable is
`FrozenSlidingSync`.
2025-05-19 15:58:58 +02:00
Ivan Enderlin 5a7a42cde3 refactor(sdk): Stop maintaining SlidingSync::rooms.
This patch stops maintaining/updating `SlidingSync::rooms`. The goal is
to remove `SlidingSyncRoom`.
2025-05-19 15:58:58 +02:00
Ivan Enderlin 0ad88842cc refactor(sdk): Remove SlidingSync::get_rooms and get_all_rooms.
This patch removes `SlidingSync::get_rooms` and `get_all_rooms`. The
goal is to remove `SlidingSyncRoom`.
2025-05-19 15:58:58 +02:00
Ivan Enderlin 7c0f7f4715 refactor(sdk): Remove SlidingSync::get_number_of_rooms.
This patch removes `SlidingSync::get_number_of_rooms`. The goal is to
remove `SlidingSyncRoom`.
2025-05-19 15:58:58 +02:00
Ivan Enderlin 52c38ec44d refactor(base): Remove SlidingSync::get_room.
This patch removes the `SlidingSync::get_room` method. The goal is to
remove `SlidingSyncRoom`.
2025-05-19 15:58:58 +02:00
Valere Fedronic 21de891ea5 feat(sdk): Add the encrypt_and_send_raw_to_device method
This method allows users to encrypt and send custom to-device events to a set of devices of their choosing.
2025-05-19 11:20:25 +00:00
Mauro 154f29e5a0 feat(sdk): implement and observe MSC4278 config value
This patch
- Updates Ruma to use the improved MediaPreviewConfig event type that
also supports a `Default` for the content type
- Implemented a way to observe the stable and unstable values of the
event and return the used one accordingly, if no one is present the
default will be used
- Set the value (will only use unstable type for now)
2025-05-19 12:35:50 +02:00
Ivan Enderlin 7f07731471 doc(changelog): Add #5054. 2025-05-19 11:42:09 +02:00
Ivan Enderlin 1a0a4d7905 chore(base): Remove RoomInfo::prev_room_state.
This patch removes the `RoomInfo::prev_room_state` field, along with the
`RoomInfo::prev_state` method.

This data was introduced during the knocking project but was never used,
and is not used nowadays. Let's remove it.
2025-05-19 11:42:09 +02:00
Jonas Platte e3bcd4d5b2 chore: Upgrade dirs to 6.0 in examples 2025-05-19 09:23:02 +02:00
Timo ea4c9a41f8 feat(widgets): Add the controlledMediaOutput url parameter to the VirtualElementCallWidgetOptions.
This is used to configure EC on devices that need to control media outputs on their own (android, ios).
If set, EC will display a list of devices provided by the app.
2025-05-16 15:48:49 +02:00
Ivan Enderlin ac2c7f431c feat(ui): Add m.room.tombstone to the room list required_state.
This patch adds the `m.room.tombstone` state event to the list of
events in `required_state` used by the `RoomListService`. The goal is to
offer the possibility for the consumers to know whether a room has been
tombstoned or not.
2025-05-16 15:11:11 +02:00
Ivan Enderlin c0d6e87c99 task(base): Fix conflicts with a previous patch. 2025-05-16 14:43:45 +02:00
Ivan Enderlin 6162600bda refactor(base): Remove &mut Context argument from response processors when unused.
This patch removes the `_context: &mut Context` argument from response
processors when it's unused.
2025-05-16 14:43:45 +02:00
Ivan Enderlin 1187539ea4 chore(base): Remove the useless PreviousEventsProvider. 2025-05-16 14:43:45 +02:00
Ivan Enderlin 2649587d2f refactor(sdk): Use the Event Cache for read_receipts::compute_unread_counts.
The `read_receipts::compute_unread_counts` function needs the _previous
events_ to compute the read receipt correctly. These previous events
were store in `SlidingSyncRoom::timeline_queue`. Since the removal of
`timeline_queue` in the previous patches, this patch uses the Event
Cache to fetch them. It only uses events that are loaded in memory.
This is as correct as the prior behaviour, even this is still incorrect
since it doesn't back-paginate to get a better view. This is for
later. The goal of this patch is to restore the same behaviour, without
`timeline_queue`.

The main problem is that read receipts are computed in
`matrix-sdk-base`, and that the Event Cache lives in `matrix-sdk`. Thus,
we change the `SlidingSyncResponseProcessor` to handle read receipt
in particular.

The
`matrix_sdk_base::response_processors::rooms::msc4186::extensions::dispa
tch_ephemeral_events` function has been split in
two methods `dispatch_typing_ephemeral_events`, and
`dispatch_receipt_ephemeral_event_for_room`. The workflow has been a
little bit redesigned to fit in the new `SlidingSyncResponseProcessor`
constraints.

This patch moves one test from `matrix-sdk-base` into `matrix-sdk`,
because to compute the read receipt, the Event Cache must be
enabled/listening to sync updates.
2025-05-16 14:43:45 +02:00
Ivan Enderlin 68651aac1f feat(sdk): Add RoomEventCache::events to avoid ::subscribe.
`RoomEventCache::subscribe` returns the set of events + the
`RoomEventCacheListener`. However, creating this listener isn't
cheap, especially dropping it. That's why this patch creates
`RoomEventCache::events` to replace `subscribe` when the listener is
not necessary.
2025-05-16 14:43:45 +02:00
Ivan Enderlin 2c8f48fabb doc(base): Fix inline comment typos. 2025-05-16 14:43:45 +02:00
Ivan Enderlin c426c03624 refactor(sdk): Remove timeline and prev_batch from SlidingSyncRoom. 2025-05-16 14:43:45 +02:00
Ivan Enderlin eeaa091024 chore(ffi): Justify the allow(clippy::large_enum_variant). 2025-05-16 14:27:49 +02:00
Ivan Enderlin 7ef962f931 chore(labs): Allow clippy::large_enum_variant in multiverse.
This is development-, debug-oriented tool. Let's allow
`clippy::large_enum_variant` for the moment.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 8480e0fc55 chore(ui): Allow clippy::large_enum_variant on TimelineAction.
This enum is large, but it's used in a short period of time, not
collected somewhere, so it's safe to accept a large size here.
2025-05-16 14:27:49 +02:00
Ivan Enderlin bf5e0124ab refactor(ui): Reduce the size of NotificationEvent.
This patch reduces the size of `NotificationEvent` from 576 bytes to
16 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin d56ad64cc2 refactor(ui): Reduce the size of NotificationStatus.
This patch reduces the size of `NotificationStatus` from 216 bytes to
16 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin ab3f22c212 refactor(sdk): Reduce the output size of get_header.
This patch reduces the size of the output's `Result::Err` variant of
`get_header` from 160 bytes to 8 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin e41dbd6300 refactor(sdk): Reduce size of HttpError.
This patch reduces the size of `HttpError` from 160 bytes to 24 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 29a8556f10 refactor(sdk): Reduce size of ReplyContent.
This patch reduces the size of `ReplyContent` from 448 bytes to
16 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 8d0d920808 refactor(sdk): Replace iter().any() by contains().
This is faster for scalars, but it falls back to a regualar
`iter().any()` for other types. It's the same, but at least Clippy
doesn't complain.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 1cdc9ff6e4 refactor(sdk): Use IoError::other.
This patch replaces `IoError::new(IoErrorKind::Other, …)` by
`IoError::other(…)`.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 9541123fcf refactor(crypto): Reduce the size of SasState.
This patch reduces the size of `SasState` from 288 bytes to 88 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin ed4b789f87 refactor(crypto): Reduce the size of OutgoingContent.
This patch reduces the size of `OutgoingContent` from 160 bytes to
24 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 18a3c37554 refactor(crypto): Reduce sizes of Verification and VerificationRequestState.
This patch reduces the sizes of `Verification` from 376 bytes to
16 bytes, and `VerificationRequestState` from 424 bytes to 96 bytes.

It also reduces the size of a couple of other types in the same vain.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 92b4b03a8d refactor(crypto): Reduce the size of OutgoingContent and RoomMessageRequest.
This patch reduces the sizes of `OutgoingContent` from 464 bytes to
160 bytes, and `RoomMessageRequest` from 480 bytes to 40 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 192c50dcad refactor(crypto): Reduce the size of OutgoingVerificationRequest.
This patch reduces the size of `OutgoingVerificationRequest` from
480 bytes to 64 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 7b34eaabe5 refactor(crypto): Reduce the size of AnyOutgoingRequest.
This patch reduces the size of `AnyOutgoingRequest` from 488 bytes to
72 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 2eb4278835 refactor(crypto): Reduce the size of RoomIdentityChange.
This patch reduces the size of `RoomIdentityChange` from 576 bytes to
72 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 293d4ee08c refactor(crypto): Reduce the size of MaybeEncryptedRoomKey.
This patch reduces the size of `MaybeEncryptedRoomKey` from 336 bytes
to 32 bytes.
2025-05-16 14:27:49 +02:00
Ivan Enderlin 87066a127e refactor(crypto): Use IoError::other.
This patch uses `IoError::other(…)` as a shortcut of
`IoError::new(ErrorKind::Other, …)`.
2025-05-16 14:27:49 +02:00
Kévin Commaille 4847a3135b feat(base-sdk): Ignore marked_unread room account data with unstable prefix after seeing one with stable prefix
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-16 09:55:02 +02:00
Kévin Commaille af02e0c472 feat(sdk): Send stable m.marked_unread room account data
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-16 09:55:02 +02:00
Stefan Ceriu da2dda0e45 fix(ui): populate the thread_root and in_reply_to fields for stickers and polls
They have never been set and there was no way of telling if stickers and polls belong on a thread or come in reply of any other message.

This patch also exposes methods for setting these relations on the event factory level.
2025-05-15 16:45:34 +03:00
Benjamin Bouvier 69b8878890 fix(sdk): mark rooms joined with join_room_by_id or join_room_by_id_or_alias as DMs if needs be
This moves the logic from `Room::join()` to these two methods. This is
isofunctional, because `Room::join()` does call into
`Client::join_room_by_id()` internally.
2025-05-15 14:19:31 +02:00
Damir Jelić 7893e55a8d refactor(crypto): Make the room key importing logic more generic 2025-05-15 12:23:23 +02:00
Damir Jelić c0e45a2e0f refactor(widgets): Rename the then() function into add_response_handler() (#5037)
The then() function can be used with booleans and futures to execute a
piece of code if the boolean is true or once the future is completed.

In contrast, the then() function in the widget driver is not executed
immediately. Instead it only adds a callback that is later on executed
by the widget driver.
2025-05-14 16:16:04 +02:00
Stefan Ceriu 13a65c8dfe feat(ui): add new Thread timeline focus mode and associated events loader (#5032)
… that allows building a timeline instance specific to a particular
thread root.

Creating a timeline in this mode will start by backpaginating root event
relations with `num_events` and automatically insert the thread root
event when reaching the end. It will include
`RelationsOfType(RelationType::Thread)` but also recurse over the
retrieved events to fetch reactions.
It will not however react to new events received over sync or that the
user sends (for now).

This patch will also help incrementally deliver the upstream client
support for creating such a timeline.

Part of #4833 (meta #4869).
2025-05-14 14:14:29 +00:00
Kévin Commaille 36667c1298 chore: Get rid of cargo-deny errors due to new advisories
Signed-off-by: Kévin Commaille <zecakeh@tedomum.fr>
2025-05-14 15:42:46 +02:00
Benjamin Bouvier e4f2299785 refactor(timeline): get rid of FullEventMeta and replace it with EventMeta + function parameters 2025-05-14 13:30:24 +02:00
Benjamin Bouvier 81a2679bb8 refactor(timeline): only compute the TimelineEventContext when it's needed 2025-05-14 13:30:24 +02:00
Benjamin Bouvier 9087263da4 refactor(timeline): rewrite how failed-to-parse items are added 2025-05-14 13:30:24 +02:00
Benjamin Bouvier d58111fa04 refactor(timeline): isolate computation of should_add in its own function 2025-05-14 13:30:24 +02:00
Benjamin Bouvier ab87ea5770 refactor(timeline): simplify computation of should_add a bit 2025-05-14 13:30:24 +02:00
Benjamin Bouvier 6b62b41a60 refactor(timeline): get rid of the return value of find_item_and_apply_aggregation
As it's now unused.
2025-05-14 13:30:24 +02:00
Benjamin Bouvier b1f088277d refactor(timeline): get rid of HandleEventResult 2025-05-14 13:30:24 +02:00
Benjamin Bouvier 277eae75d9 refactor(timeline): make item_added a local variable instead of deeply-stored context 2025-05-14 13:30:24 +02:00
Benjamin Bouvier 20559e3f2c refactor(timeline): get rid of unused HandleEventResult::items_updated 2025-05-14 13:30:24 +02:00
Benjamin Bouvier 341f9c267d feat(state store): enable the busy timeout to automatically retry operations on busy dbs
Under some very particular circumstances, the "database is locked" error
can still happen, even in WAL mode, even if the database connection is
not being upgraded from a read transaction to a write transaction.

We *think* this might be the reason behind errors like
github.com/element-hq/element-x-ios/issues/3582, so we're enabling the
sqlite busy_timeout, which will retry the operation after a short sleep,
until the busy timeout is being hit.
2025-05-14 13:27:54 +02:00
Timo af3039abde docs(WidgetDriver): Add module documentation
Co-authored-by: Robin <robin@robin.town>
Signed-off-by: Damir Jelić <poljar@termina.org.uk>
2025-05-14 11:42:55 +02:00
Benjamin Bouvier 4d027ec405 doc: add a changelog entry for the persistent storage of the event cache 2025-05-13 15:50:21 +02:00
dependabot[bot] 3cd64ac03b chore(deps): Bump tokio from 1.43.0 to 1.43.1
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.43.0 to 1.43.1.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.43.0...tokio-1.43.1)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.43.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-13 14:58:30 +02:00
Jorge Martín 44e103c0e3 feat(ffi): expose ffi::RoomInfo::tombstone
This replaces `ffi::RoomInfo::is_tombstoned`, including the needed extra info for the migration UI.
2025-05-13 14:41:41 +02:00
dependabot[bot] 7d992d1af8 chore(deps): Bump ring from 0.17.8 to 0.17.14
Bumps [ring](https://github.com/briansmith/ring) from 0.17.8 to 0.17.14.
- [Changelog](https://github.com/briansmith/ring/blob/main/RELEASES.md)
- [Commits](https://github.com/briansmith/ring/commits)

---
updated-dependencies:
- dependency-name: ring
  dependency-version: 0.17.14
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-13 14:37:12 +02:00
Benjamin Bouvier ac42953524 doc(timeline): add extra documentation for HandleAggregationKind 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 06759359af refactor(timeline): simplify lightly computation of should_add_new_items for local events 2025-05-13 14:15:00 +02:00
Benjamin Bouvier a3a30885c0 refactor(timeline): rename TimelineEventKind into TimelineAction and add comments 2025-05-13 14:15:00 +02:00
Benjamin Bouvier b448c4ac39 refactor(timeline): get rid of TimelineEventKind::Message 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 6a874fec2d refactor(timeline): use TimelineEventKind::AddItem for most room messages 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 998019b8b8 refactor(timeline): use TimelineEventKind::AddItem for poll starts 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 5a0b33fcd1 refactor(timeline): use TimelineEventKind::AddItem for call invite/notify/sticker 2025-05-13 14:15:00 +02:00
Benjamin Bouvier ec55d7cb58 refactor(timeline): use TimelineEventKind::HandleAggregation for poll edits/responses/ends 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 706f78d5b3 refactor(timeline): use TimelineEventKind::HandleAggregation for edits 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 1218cb4c28 refactor(timeline): use TimelineEventKind::HandleAggregation for redactions 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 31bd8a3587 refactor(timeline): introduce TimelineEventKind::HandleAggregation for non-items
This variant will be used to cause side-effects to existing timeline
items, because the event they relate to is for an aggregation
(edit/reaction/etc.).

This is used here for reactions.
2025-05-13 14:15:00 +02:00
Benjamin Bouvier 9e70cc5dde refactor(timeline): add a small helper function to create TimelineEventKind::AddItem items 2025-05-13 14:15:00 +02:00
Benjamin Bouvier d78a4927fd refactor(timeline): use TimelineEventKind::AddItem for room member and state events 2025-05-13 14:15:00 +02:00
Benjamin Bouvier bf246b6c09 refactor(timeline): use TimelineEventKind::AddItem for redacted messages 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 5da2235973 refactor(timeline): use TimelineEventKind::AddItem for UTDs 2025-05-13 14:15:00 +02:00
Benjamin Bouvier a9de4709f9 refactor(timeline): use TimelineEventKind::AddItem to insert failed-to-parse items 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 3b8d7ffacd refactor(timeline): introduce a new TimelineEventKind::AddItem variant
The intent is that the `TimelineItemContent` can be constructed in a
single place, avoiding the need to create it in multiple places.
2025-05-13 14:15:00 +02:00
Benjamin Bouvier 3eee5a4a92 refactor(timeline): bury one use of TimelineEventKind 2025-05-13 14:15:00 +02:00
Benjamin Bouvier 6fed5747bb refactor(timeline): remove another spurious is_own_event
Once again, this information is available in the `TimelineMetadata`.
2025-05-13 14:15:00 +02:00
Benjamin Bouvier 442094a725 refactor(timeline): remove spurious FullEventMeta::is_own_event
This information can be accessed via the `TimelineMetadata::own_user_id`
field, which is instantiated only once.
2025-05-13 14:15:00 +02:00
Benjamin Bouvier de66047eee refactor(event cache): simplify Deduplicator so it only operates with the store impl 2025-05-13 10:17:21 +02:00
Benjamin Bouvier 48da03a148 refactor(event cache): don't make the store optional in the event cache 2025-05-13 10:17:21 +02:00
Benjamin Bouvier 13a2a8757e feat(event cache): enable storage by default \o/ 2025-05-13 10:17:21 +02:00
Benjamin Bouvier 1d901ec12a refactor(room list): get rid of the sliding sync in room_list_service::Room
This was only used to retrieve events cached in the timeline_queue().
2025-05-13 10:17:21 +02:00
Benjamin Bouvier 7115203a90 feat(event cache): get rid of add_initial_events() entirely 2025-05-13 10:17:21 +02:00
Jorge Martín 68fb60f223 test(ui): add more tests for fetching invite notifications in sliding sync 2025-05-13 09:10:44 +02:00
Jorge Martín 1f064fe474 test(ui): migrate notification fetching tests to use the batched methods
Also add one for the sliding sync + /context case
2025-05-13 09:10:44 +02:00
Jorge Martín 008c6f6d6c feat(ui): allow retrieving push notification events in batches 2025-05-13 09:10:44 +02:00
Yousef Moazzam 1afad3ab78 test: remove import of unused sync_timeline_event! macro 2025-05-13 09:04:55 +02:00
Yousef Moazzam d1802086ad test: create room canonical alias events with EventFactory 2025-05-13 09:04:55 +02:00
Yousef Moazzam cabe9632af test: add room canonical alias event method to EventFactory 2025-05-13 09:04:55 +02:00
Ivan Enderlin 08aa9c8614 doc(ui): Fix a typo in a comment. 2025-05-12 17:15:43 +02:00
Ivan Enderlin 831bba5cf0 test(ui): Add tests for push_local and push_date_divider. 2025-05-12 17:15:43 +02:00
Ivan Enderlin d727111a51 doc(ui): Add #5000 in the CHANGELOG.md. 2025-05-12 17:15:43 +02:00
Ivan Enderlin 8d785b762e chore(ui): Make Clippy happy. 2025-05-12 17:15:43 +02:00
Ivan Enderlin ad4ae230d5 refactor(ui): EventHandler uses regions to improve the code and avoid bugs.
This patch updates `EventHandler` to use the correct regions where
appropriate, thus reducing the complexity of the code, and removing
classes of bugs.

In the case of `Flow::Remote { position: TimelineItemPosition::At { …
}}`, we no longer need to skip the local timeline items, and to handle
the presence of the `TimelineStart` timeline item. The code is less
complex.

In the case of `Flow::Remote { position: TimelineItemPosition::End { …
}}`, that's exactly the same at the previous case.

In the case of `recycle_local_or_create_item`, the `try_fold` approach
is replaced entirely with a simple `iter_locals_region`, reducing the
size of the comments explaining the code, reducing the complexity of the
code, and reducing the surface of bugs.
2025-05-12 17:15:43 +02:00
Ivan Enderlin 54f7963152 refactor(ui): TimelineStateTransaction works on _remotes_ and _all_ regions.
This patch updates `TimelineStateTransaction` to work on the correct
regions, _remotes_ in one place, and all regions in another place.
2025-05-12 17:15:43 +02:00
Ivan Enderlin b59c0b671e refactor(ui): TimelineMetadata works on the _remotes_ region.
This patch updates `TimelineMetadata` to work on the _remotes_ region
only, excluding the _start_ and the _locals_ regions. It helps to reduce
the risk of inserting items in an incorrect regions.

This patch also removes on more `rfind_event_by_id` usage, which is
nice.
2025-05-12 17:15:43 +02:00
Ivan Enderlin c6453a4cb3 refactor(ui): ReadReceiptTimelineUpdate works on _remotes_ region.
This patch updates `ReadReceiptTimelineUpdate` to work on the _remotes_
region only, excluding the _start_ and the _lcoals_ regions. It helps
to reduce the risk of inserting a `ReadMarker` inside the _start_ or the
_locals_ regions.
2025-05-12 17:15:43 +02:00
Ivan Enderlin 74bf699615 refactor(ui): DateDividerAdjuster works on _remotes_ and _locals_ regions.
This patch updates `DateDividerAdjuster` to work on _remotes_ and
_locals_ regions only, excluding the _start_ region. It helps to reduce
the risk of inserting a `DateDivider` inside the _start_ region.

This patch also uses the new `push_date_divider` method, which provides
a couple of invariants.
2025-05-12 17:15:43 +02:00
Ivan Enderlin e1f94bf9c4 feat(ui): Define _regions_ in the Timeline.
This patch defines a new concept in the `Timeline`: Regions.

The `ObservableItems` holds all the invariants about the _position_ of the
items. It defines three regions where items can live:

1. the _start_ region, which can only contain a single `TimelineStart`,
2. the _remotes_ region, which can only contain many `Remote` timeline
   items with their decorations (only `DateDivider`s and `ReadMarker`s),
3. the _locals_ region, which can only contain many `Local` timeline items
   with their decorations (only `DateDivider`s).

The `iter_all_regions` method allows to iterate over all regions.
`iter_remotes_region` will restrict the iterator over the _remotes_
region, and so on. These iterators provide the absolute indices of the
items, so that it's harder to make mistakes when manipulating the indices of
items with operations like `insert`, `remove`, `replace` etc.

Other methods like `push_local` or `push_date_divider` insert the items
in the correct region, and check a couple of invariants.
2025-05-12 17:15:43 +02:00
Ivan Enderlin 44a0745110 chore(base): Move the bitflags dependency in the workspace. 2025-05-12 17:15:43 +02:00
Ivan Enderlin 94b76168e8 refactor(ui): Add ObservableItemsTransaction::has_local.
This patch implements the `has_local` method on
`ObservableItemsTransaction`, which is way faster than the previous the
previous solution which was to iterate over all items to find at least
one local timeline item.
2025-05-12 17:15:43 +02:00
Ivan Enderlin 55ea80b485 refactor(ui): Add ObservableItemsTransaction::push_local.
This patch adds the `push_local` method on `ObservableItemsTransaction`
to add semantics and hardcode the invariant in a single place for the
different timeline items.
2025-05-12 17:15:43 +02:00
Ivan Enderlin 4e501e88ee refactor(ui): Add ObservableItemsTransaction::push_timeline_start_if_missing.
This patch adds the `push_timeline_start_if_missing` method on
`ObservableItemsTransaction` to add semantics and hardcode the
invariant in a single place for the different timeline items.
2025-05-12 17:15:43 +02:00
Ivan Enderlin afc02781e9 test(ui): Add a regression test.
This patch adds a regression test ensuring [this bug][4976] cannot
happen anymore.

[4976]: https://github.com/matrix-org/matrix-rust-sdk/issues/4976
2025-05-12 17:15:43 +02:00
Ivan Enderlin c2072e1cc2 test(ui): Support index [$nth] --- date divider --- in assert_timeline_stream!. 2025-05-12 17:15:43 +02:00
Ivan Enderlin eef99b2679 test: Add assert messages in the assert_timeline_stream macro.
This patch improves the `assert_timeline_stream` macro by adding a bunch
of assert messages in case it fails.
2025-05-12 17:15:43 +02:00
Ivan Enderlin 581d54f65f fix(ui): Offset the timeline index in the presence of a TimelineStart.
This patch fixes the insertion of a new `TimelineItem` in the presence
of a `TimelineStart` that shifts/offsets the timeline index of 1.
2025-05-12 17:15:43 +02:00
dependabot[bot] 5f5ea69a32 chore(deps): Bump tj-actions/changed-files
Bumps [tj-actions/changed-files](https://github.com/tj-actions/changed-files) from 4168bb487d5b82227665ab4ec90b67ce02691741 to 480f49412651059a414a6a5c96887abb1877de8a.
- [Release notes](https://github.com/tj-actions/changed-files/releases)
- [Changelog](https://github.com/tj-actions/changed-files/blob/main/HISTORY.md)
- [Commits](https://github.com/tj-actions/changed-files/compare/4168bb487d5b82227665ab4ec90b67ce02691741...480f49412651059a414a6a5c96887abb1877de8a)

---
updated-dependencies:
- dependency-name: tj-actions/changed-files
  dependency-version: 480f49412651059a414a6a5c96887abb1877de8a
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-12 17:00:46 +02:00
Johannes Marbach 08800f7d60 Reduce boilerplate further 2025-05-12 10:56:57 +02:00
Johannes Marbach eb51a7f145 Use macros to reduce boilerplate 2025-05-12 10:56:57 +02:00
Johannes Marbach 8cf09217d6 Switch to structs in yet more places 2025-05-12 10:56:57 +02:00
Johannes Marbach f81945ad7e Fix build error 2025-05-12 10:56:57 +02:00
Johannes Marbach c21f97274c Switch to struct 2025-05-12 10:56:57 +02:00
Johannes Marbach da67bacfbf Add changelog 2025-05-12 10:56:57 +02:00
Johannes Marbach 175d854a9b feat(ffi): Add methods for observing account data changes
Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
2025-05-12 10:56:57 +02:00
Ivan Enderlin afabfb97b6 task(ui): Log when the room name is empty when filtering the room list. 2025-05-12 10:24:52 +02:00
Yousef Moazzam 8e4554d3c0 test: create room server ACL event with EventFactory 2025-05-12 09:30:36 +02:00
Yousef Moazzam f1ea47f0b6 test: add room server ACL event method to EventFactory 2025-05-12 09:30:36 +02:00
Yousef Moazzam 26f1282c6a test: create room power level events with EventFactory 2025-05-10 20:35:57 +02:00
Yousef Moazzam 4053321cd0 test: add room power levels event method to EventFactory 2025-05-10 20:35:57 +02:00
Robin 561158c7bb fix(tests): Avoid depending on the local time zone in tests
This test fails when run in the Americas, because over here the Unix epoch took place in 1969 =D
2025-05-09 20:47:48 +02:00
Mauro Romito c023745dcf crates: update Ruma to support MSC 4278
This will later be handled once the account data observation PR is ready
2025-05-09 14:41:17 +02:00
Yousef Moazzam 6ba68fe87e test: add timeline events in bulk to room builder 2025-05-09 11:51:45 +02:00
Yousef Moazzam 7afb46cc0c test: create room create event with EventFactory 2025-05-09 11:51:45 +02:00
Yousef Moazzam 93dcd07073 test: add room create event method to EventFactory 2025-05-09 11:51:45 +02:00
Yousef Moazzam cf2f507951 test: create member event with EventFactory 2025-05-09 11:51:45 +02:00
Damir Jelić 35a2ce97d8 refactor(widget): Use streams to streamline the action processing logic 2025-05-09 11:07:41 +02:00
Ivan Enderlin f042084bd2 doc: Generate doc with --generate-link-to-definition.
This patch adds the `--generate-link-to-definition`
argument to `rustdoc` for `docs.rs`. This is using
https://github.com/rust-lang/rust/pull/84176 to add links in the source
code page.
2025-05-08 13:08:32 +02:00
Doug be6d5f9bd9 ffi: Add support for the login hints with OIDC. 2025-05-08 12:10:16 +02:00
Doug 506060f23d sdk: Add support for generic OAuth login hints.
See https://github.com/element-hq/matrix-authentication-service/pull/4512
2025-05-08 12:10:16 +02:00
Richard van der Hoff 55d475df04 Merge pull request #4988 from matrix-org/rav/history_sharing/better_sender_data
crypto: improve SenderData stored with room key bundle data
2025-05-07 22:31:48 +01:00
Richard van der Hoff f349a66292 crypto: improve SenderData stored with room key bundle data
If we already have cross-signing details for the owner of the device at the
point we receive the to-device message, we should store that rather than just
the device info.
2025-05-07 22:16:57 +01:00
Richard van der Hoff 3742bdc7cf crypto: move some logic from SenderDataFinder to SenderData
create a new method `SenderData::from_device` which does the last few steps of
`SenderDataFinder`: turns out we want it elsewhere. Add some tests to test that
functionality in isolation.
2025-05-07 22:16:57 +01:00
Doug b5b2450eac ffi: Expose the QrCodeData server name. 2025-05-07 13:40:29 +02:00
Denis Kasak fc071bafb2 docs: Various fixes for store-related comments.
- Doc comment for the SQLite-based state store incorrectly referred to
  it as a "cryptostore".
- Consistent capitalisation of SQLite.
- Consistent use of indefinite article "an" before SQLite.
- Fix line length.
2025-05-06 13:55:03 +02:00
Yousef Moazzam e4ce1790cd test: replace sync_timeline_event! with EventFactory in notification test 2025-05-06 13:34:00 +02:00
Ivan Enderlin 3461b13ec7 doc(sqlite): Add entry in the CHANGELOG.md. 2025-05-06 09:17:54 +02:00
Ivan Enderlin 83e4314645 fix(sqlite): Fix a UNIQUE constraint violation with Update::RemoveItem.
Imagine we have the following events:

| event_id | room_id | chunk_id | position |
|----------|---------|----------|----------|
| $ev0     | !r0     | 42       | 0        |
| $ev1     | !r0     | 42       | 1        |
| $ev2     | !r0     | 42       | 2        |
| $ev3     | !r0     | 42       | 3        |
| $ev4     | !r0     | 42       | 4        |

`$ev2` has been removed, then we end up in this state:

| event_id | room_id | chunk_id | position |
|----------|---------|----------|----------|
| $ev0     | !r0     | 42       | 0        |
| $ev1     | !r0     | 42       | 1        |
|          |         |          |          | <- no more `$ev2`
| $ev3     | !r0     | 42       | 3        |
| $ev4     | !r0     | 42       | 4        |

We need to shift the `position` of `$ev3` and `$ev4` to `position - 1`,
like so:

| event_id | room_id | chunk_id | position |
|----------|---------|----------|----------|
| $ev0     | !r0     | 42       | 0        |
| $ev1     | !r0     | 42       | 1        |
| $ev3     | !r0     | 42       | 2        |
| $ev4     | !r0     | 42       | 3        |

Usually, it boils down to run the following query:

```sql
UPDATE event_chunks
SET position = position - 1
WHERE position > 2 AND …
```

Okay. But `UPDATE` runs on rows in no particular order. It means that
it can update `$ev4` before `$ev3` for example. What happens in this
particular case? The `position` of `$ev4` becomes `3`, however `$ev3`
already has `position = 3`. Because there is a `UNIQUE` constraint
on `(room_id, chunk_id, position)`, it will result in a constraint
violation.

There is **no way** to control the execution order of `UPDATE` in
SQLite. To persuade yourself, try:

```sql
UPDATE event_chunks
SET position = position - 1
FROM (
    SELECT event_id
    FROM event_chunks
    WHERE position > 2 AND …
    ORDER BY position ASC
) as ordered
WHERE event_chunks.event_id = ordered.event_id
```

It will fail the same way.

Thus, we have 2 solutions:

1. Remove the `UNIQUE` constraint,
2. Be creative.

The `UNIQUE` constraint is a safe belt. Normally, we have
`event_cache::Deduplicator` that is responsible to ensure there is no
duplicated event. However, relying on this is “fragile” in the sense it
can contain bugs. Relying on the `UNIQUE` constraint from SQLite is more
robust. It's “braces and belt” as we say here.

So. We need to be creative.

Many solutions exist. Amongst the most popular, we see _dropping and
re-creating the index_, which is no-go for us, it's too expensive. I
(@hywan) have adopted the following one:

- Do `position = position - 1` but in the negative space, so
 `position = -(position - 1)`. A position cannot be negative; we are
  sure it is unique!
- Once all candidate rows are updated, do `position = -position` to move
  back to the positive space.

'told you it's gonna be creative.

This solution is a hack, **but** it is a small number of operations, and
we can keep the `UNIQUE` constraint in place.

This patch updates the `test_linked_chunk_remove_item` to handle
6 events. On _my_ system, with _my_ SQLite version, it triggers the
`UNIQUE` constraint violation without the bug fix.
2025-05-06 09:17:54 +02:00
dependabot[bot] c726bc5904 chore(deps): Bump tj-actions/changed-files
Bumps [tj-actions/changed-files](https://github.com/tj-actions/changed-files) from 5426ecc3f5c2b10effaefbd374f0abdc6a571b2f to 4168bb487d5b82227665ab4ec90b67ce02691741.
- [Release notes](https://github.com/tj-actions/changed-files/releases)
- [Changelog](https://github.com/tj-actions/changed-files/blob/main/HISTORY.md)
- [Commits](https://github.com/tj-actions/changed-files/compare/5426ecc3f5c2b10effaefbd374f0abdc6a571b2f...4168bb487d5b82227665ab4ec90b67ce02691741)

---
updated-dependencies:
- dependency-name: tj-actions/changed-files
  dependency-version: 4168bb487d5b82227665ab4ec90b67ce02691741
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-05 18:35:37 +03:00
dependabot[bot] 970af0de7c chore(deps): Bump crate-ci/typos from 1.31.2 to 1.32.0
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.31.2 to 1.32.0.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.31.2...v1.32.0)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.32.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-05 17:31:29 +02:00
mpeter50 8be0a7df95 Update logging of device verification request timestamp valdiation
In element-hq/element-web#29625 it was found to be useful to give more visibility to this kind of verification error.

Signed-off-by: mpeter50 <83356418+mpeter50@users.noreply.github.com>
2025-05-05 09:46:29 +03:00
Michael Goldenberg 8fd122c431 style(indexeddb): cargo fmt
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-05-05 08:44:54 +02:00
Michael Goldenberg f661b82f18 refactor(indexeddb): rename module (indexeddb_serializer -> serializer)
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-05-05 08:44:54 +02:00
Michael Goldenberg 77ee7f1d19 refactor(indexeddb): change indexeddb_serializer::Result to use IndexeddbSerializerError
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-05-05 08:44:54 +02:00
Michael Goldenberg af90b7ac4e refactor(indexeddb): add conversions into IndexeddbSerializerError
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-05-05 08:44:54 +02:00
Michael Goldenberg 3f3daef01c refactor(indexeddb): add conversion IndexeddbSerializerError -> IndexeddbCryptoStoreError
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-05-05 08:44:54 +02:00
Michael Goldenberg c2e859273d refactor(indexeddb): add enum for general IndexedDB serialization errors
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-05-05 08:44:54 +02:00
Richard van der Hoff 3b84b2c5e7 crypto-ffi: fix error message for MissingRoomKey (#4997)
This error does not necessarily mean that the session was *withheld*.
2025-05-02 15:52:15 +01:00
Stefan Ceriu 284db61540 feat(ffi): expose a new get_room method on the NotificationClient that will fetch it from its inner in-memory store backed client instead of the parent one.
This is necessary because the `NotificationClient` runs a sliding sync loop and the retrieved data isn't pushed back into the parent client stores (because of cross process locking shenanigans).
This will be used with the previously introduced `org.matrix.msc3401.call.member` required state to check whether a room still has an ongoing call before showing the ringing screen.
2025-04-30 12:48:41 +03:00
Stefan Ceriu 8e19a5eb33 change(notification_client): request the org.matrix.msc3401.call.member state events resolving notification payloads
- this will be used to check whether a room still has an active call (`has_active_room_call`) before showing the ringing screen
2025-04-30 12:48:41 +03:00
Jorge Martín ef4cb79cde fix(sdk): Upload encrypted media with application/octet-stream mime type
This is apparently the right way to do it, both because some HS expect only this mimetype and also so we don't leak the mime type of the encrypted media.
2025-04-30 09:10:27 +02:00
Timo 9fbb9cbe9b WidgetDriver: refactor Filter
This commit simplifies the filter public api.

Rethinking the public api we only need:
 - to know if events can be sent based on the capabilities
 - to know if events can be sent to the widget (read) based on the capabilities
 - if it even makes sense to sent a cs api read request or if all possibly returned events
   would not match the type.

To simplify the code in the machine it also made sense to add `From` implementation
to the FilterInputs instead of gathering the relevant data from all kinds of Raw events.

The new api is simpler:
All possible events we need to check can be converted into filter inputs (using `into()`).
`capabilites` has two allow_read/allow_send that consume filter inputs.
`capabilites` can be asked if there is any filter for specific event types
to allow not send unnecassary requests.
2025-04-29 18:15:07 +02:00
Timo 4e64f28318 WidgetDriver: filter event_type change from dedicated ...EventType -> String
This is (sadly) required since we cannot do `as_str()` for `TimlineEventType` and other `ruma` event types.
So we need to use `String`. We also never used them more specifically than strings.
2025-04-29 18:15:07 +02:00
Timo 5e2f775b2b WidgetDriver: rename EventFilter->Filter & MatrixEventFilterInput -> FilterInput
This is a simple devtool refactor rename. Nothing fancy here.
2025-04-29 18:15:07 +02:00
procr1337 0856f4e6b0 refactor(crypto): Properly encapsulate internal OutboundGroupSession state
Previously, the `share_strategy` was breaking the abstraction provided
by `OutboundGroupSession` by accessing its internal fields in an
inconsistent and adhoc way. Now all fields are private and a proper
abstraction was added to access the required state in a consistent API.
2025-04-29 17:39:21 +02:00
Benjamin Bouvier ae4cdda939 feat(sdk): add a room method to retrieve all related events 2025-04-29 15:01:31 +02:00
Benjamin Bouvier 0db273bf38 test(sdk): add a mocking endpoint for listing relations and test Room::relations 2025-04-29 15:01:31 +02:00
Benjamin Bouvier a912a7584f test(sdk): add a mocking endpoint for listing threads and test Room::list_threads() 2025-04-29 15:01:31 +02:00
Benjamin Bouvier fa1aa57581 feat(sdk): add a room method to retrieve a list of threads 2025-04-29 15:01:31 +02:00
Richard van der Hoff b22bb3fa86 crypto: Move some test helpers out from sender_data_finder 2025-04-29 12:36:32 +01:00
Michael Goldenberg c3ed8b9e7b docs(ffi): update changelog
Signed-of-by: Michael Goldenberg <m@mgoldenberg.net>
2025-04-29 12:35:31 +02:00
Michael Goldenberg 6e442d9046 feat(ffi): rename fields in UploadSource to match AttachmentSource
Signed-of-by: Michael Goldenberg <m@mgoldenberg.net>
2025-04-29 12:35:31 +02:00
Michael Goldenberg 79c5edd319 refactor(ffi): add conversion from UploadSource to AttachmentSource
Signed-of-by: Michael Goldenberg <m@mgoldenberg.net>
2025-04-29 12:35:31 +02:00
Michael Goldenberg bd6361e23a feat(ffi): replace file-related fields with UploadSource in UploadParameters
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-04-29 12:35:31 +02:00
Michael Goldenberg 02fdf8c0d3 feat(ffi): add UploadSource for representing upload data
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-04-29 12:35:31 +02:00
Michael Goldenberg 1e835b24fb feat(ffi): update changelog
Signed-off-by: Michael Goldenberg <m@mgoldenberg.net>
2025-04-29 12:35:31 +02:00
Michael Goldenberg 1a12ba3ad4 feat(ffi): allow file data to be passed through bindings when sending attachment
Signed-of-by: Michael Goldenberg <m@mgoldenberg.net>
2025-04-29 12:35:31 +02:00
dependabot[bot] d9f2588561 chore(deps): Bump tj-actions/changed-files
Bumps [tj-actions/changed-files](https://github.com/tj-actions/changed-files) from c34c1c13a740b06851baff92ab9a653d93ad6ce7 to 5426ecc3f5c2b10effaefbd374f0abdc6a571b2f.
- [Release notes](https://github.com/tj-actions/changed-files/releases)
- [Changelog](https://github.com/tj-actions/changed-files/blob/main/HISTORY.md)
- [Commits](https://github.com/tj-actions/changed-files/compare/c34c1c13a740b06851baff92ab9a653d93ad6ce7...5426ecc3f5c2b10effaefbd374f0abdc6a571b2f)

---
updated-dependencies:
- dependency-name: tj-actions/changed-files
  dependency-version: 5426ecc3f5c2b10effaefbd374f0abdc6a571b2f
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-29 12:31:49 +02:00
dependabot[bot] 5268bc35db chore(deps): Bump crate-ci/typos from 1.31.1 to 1.31.2
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.31.1 to 1.31.2.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.31.1...v1.31.2)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: 1.31.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-29 12:20:08 +02:00
Valere Fedronic ff32840387 refactor(crypto): Move session_id from EncryptionInfo to AlgorithmInfo as it is megolm specific
This patch moves the `session_id` field from EncryptionInfo to
AlgorithmInfo::MegolmV1AesSha2 as it is specific to Megolm. We provide
transparent migration of the serialized data from one format to the other.

In the future we plan to reuse `EncryptionInfo` for to_device decryption
(using olm not megolm). So megolm session_id should move to algorithm
specific data.
2025-04-29 08:07:03 +00:00
Mauro Romito b4afb91de5 feat(bindings): check if report room api is supported 2025-04-29 09:48:29 +03:00
Richard van der Hoff d800d3c324 crypto: clean up confusing method (#4983)
This method had a confusing name: it didn't receive a key bundle, but
rather the data *about* a key bundle.

Remove the unused `sender_key` parameter while we are at it: we use the
embedded (and already-checked) `event.sender_device_keys` here.
2025-04-28 13:55:51 +01:00
Richard van der Hoff 7c84ab2701 Merge pull request #4982 from matrix-org/rav/random_fix_1
sdk: remove redundant variable
2025-04-28 13:51:12 +01:00
procr1337 6e119c737c fix(crypto): Take into account pending to-device room key sharing requests when collecting devices that have already received a session
This avoids conditions where a key may be shared with a device only
after we decided that it is fine to reuse (and not rotate) the session
based on the wrong assumption that that particular device does not have
the keys.

Signed-off-by: Niklas Baumstark
[niklas.baumstark@gmail.com](mailto:niklas.baumstark@gmail.com)
2025-04-25 15:51:41 +02:00
Valere Fedronic 237c0256a2 fix(tests): tweak a flaky test to make it more stable + logs (#4968)
Tentative fix for
https://github.com/matrix-org/matrix-rust-sdk/issues/4832

Tweaked a bit the timings and added more logging in the UTD manager to
see what is happening exactly in case it is still flaky.

Signed-off-by: Damir Jelić <poljar@termina.org.uk>
Co-authored-by: Damir Jelić <poljar@termina.org.uk>
Co-authored-by: Benjamin Bouvier <benjamin@bouvier.cc>
2025-04-25 10:42:55 +00:00
Benjamin Bouvier f763d3690d docs(common): add a comment explaining how to use the timer! macro 2025-04-24 18:21:00 +02:00
Andy Balaam 91d085c41b task(tests): Ignore test_new_users_first_messages_dont_warn_about_insecure_device_if_it_is_secure because it is flaky 2025-04-24 15:14:58 +01:00
procr1337 afb6627bef fix(crypto): Fixed a bug where room keys would be rotated unecessarily
Previously, `is_session_overshared_for_user` did not take into account
that `shared_with_set` also contains withheld device IDs who explicitly
have never received the session keys. This would lead to it mistakenly
determining oversharing for those devices for every event being sent in
the presence of blacklisted/withheld devices in the room, and rotating
the group session accordingly.

The fix is to correctly exclude devices with `ShareInfo::Withheld` from
the enumeration.

Signed-off-by: Niklas Baumstark niklas.baumstark@gmail.com
2025-04-24 14:39:02 +02:00
Benjamin Bouvier 8c3f55456f refactor(widget): reduce indent in a few places thanks to early returns 2025-04-24 14:07:27 +02:00
Benjamin Bouvier 03d9e9b368 refactor(widget): avoid complicated combinators and make decisions more local and explicit 2025-04-24 14:07:27 +02:00
Benjamin Bouvier 75c4af5f4e chore(widget): make some names more explicit 2025-04-24 14:07:27 +02:00
Benjamin Bouvier c9f6938cb7 refactor(widget): get rid of WidgetDriverRequestHandle::null too 2025-04-24 14:07:27 +02:00
Benjamin Bouvier 939af521f3 refactor(widget): simplify further the MatrixDriverRequestHandle 2025-04-24 14:07:27 +02:00
Benjamin Bouvier bb9d481d88 refactor(widget): get rid of the null MatrixDriverRequestHandle 2025-04-24 14:07:27 +02:00
Benjamin Bouvier 3df336ab1c refactor(widget): get rid of function used only once 2025-04-24 14:07:27 +02:00
Benjamin Kampmann 12e358a54f fix(sdk): Don't overwrite previously added state events in state_event processing
Fixes #4952 .

Signed-off-by: Benjamin Kampmann <ben@acter.global>
2025-04-24 13:49:22 +02:00
Richard van der Hoff 468e7c35f6 Merge pull request #4932 from matrix-org/rav/history_sharing/save_key_bundle_data
crypto: store received room key bundle data information

Add hooks to the memory store and sqlite store to stash the information about room key data.
2025-04-24 12:22:14 +01:00
Richard van der Hoff a3cb1cd6b5 Merge branch 'main' into rav/history_sharing/save_key_bundle_data 2025-04-24 12:07:21 +01:00
Johannes Marbach 1554e05d8a refactor(send_queue): generalize SentRequestKey::Media and DependentQueuedRequestKind::UploadFileWithThumbnail to prepare for MSC4274 gallery uploads (#4897)
This was broken out of
https://github.com/matrix-org/matrix-rust-sdk/pull/4838 and is a
preliminary step towards implementing
[MSC4274](https://github.com/matrix-org/matrix-spec-proposals/pull/4274).
`SentRequestKey::Media` and
`DependentQueuedRequestKind::UploadFileWithThumbnail` are generalized to
allow chaining dependent media uploads and accumulating sent media
sources.

- [x] Public API changes documented in changelogs (optional)

---------

Signed-off-by: Johannes Marbach <n0-0ne+github@mailbox.org>
Co-authored-by: Benjamin Bouvier <benjamin@bouvier.cc>
2025-04-24 09:52:33 +00:00
Richard van der Hoff 85e0626d5f indexeddb: fudge implementation of get_received_room_key_bundle_data 2025-04-23 19:59:24 +01:00
Richard van der Hoff e89c45ba42 sqlite: store data on received room key bundles 2025-04-23 19:59:24 +01:00
Richard van der Hoff 6173aef064 memorystore: store received room key bundle data 2025-04-23 19:59:24 +01:00
Richard van der Hoff 00364d95af crypto: add methods for room key bundles to store traits 2025-04-23 19:59:24 +01:00
Richard van der Hoff 3aa0983a5c crypto: add received room key bundles to store changes list
After we receive a to-device message holding room key bundle info, add the data
to the store's Changes structure
2025-04-23 19:59:24 +01:00
Richard van der Hoff 4be4d39851 crypto: add types to support decryption of RoomKeyHistoryBundle to-device
events
2025-04-23 19:59:24 +01:00
Benjamin Bouvier 884775086a chore: add an intermittent test failure policy 2025-04-23 15:34:26 +02:00
Damir Jelić a60e336f85 feat(crypto): Start using the stable identifier for the sender device keys
This patch updates the sending side of the `sender_device_keys` field
introduced in MSC4147.

Since the MSC got merged, we're switching from the unstable identifier
to the stable one.

A couple of snapshot tests were added modified to make this happen.
2025-04-23 15:25:11 +02:00
Benjamin Bouvier 426a4ff1bf chore(ci): make clippy happy on all configurations 2025-04-23 14:49:49 +02:00
Benjamin Bouvier 9492614ea6 refactor(sdk): rename a few push_action_ctx variables back into push_ctx 2025-04-23 14:49:49 +02:00
Benjamin Bouvier 234e0be337 refactor(timeline): reuse the same push context for all the events we're trying to re-decrypt 2025-04-23 14:49:49 +02:00
Benjamin Bouvier b6d71a3875 refactor(timeline): make use of PushContext in the RoomDataProvider trait 2025-04-23 14:49:49 +02:00
Benjamin Bouvier 4c8e2fd4ae refactor(sdk): no need to recompute push actions from /messages, since try_decrypt_event does it for us 2025-04-23 14:49:49 +02:00
Benjamin Bouvier 55342a84fa refactor(sdk): explicit the case where we can't compute the push actions 2025-04-23 14:49:49 +02:00
Benjamin Bouvier 9950268164 refactor(sdk): rename Room::push_action_ctx to Room::push_context() (and associated type too) 2025-04-23 14:49:49 +02:00
Benjamin Bouvier f17c9fb2d5 refactor(sdk): rename Room::push_context() to Room::push_condition_room_ctx() 2025-04-23 14:49:49 +02:00
Benjamin Bouvier 93c961d673 refactor(sdk): avoid recomputing the push context and ruleset for every single event when decrypting a batch 2025-04-23 14:49:49 +02:00
Benjamin Bouvier 6e786e0ede refactor(sdk): use Room::try_decrypt_event in an extra location
The previous code was wrong, in that it wouldn't properly compute push
actions for events that were not encrypted and received with /messages.
2025-04-23 14:49:49 +02:00
Timo 6c4a4382d7 WidgetDriver: Use matrix_sdk_common::executor::spawn instead of tokio::spawn to make it wasm compatible. (#4959)
This PR is a revived version of:
https://github.com/matrix-org/matrix-rust-sdk/pull/4707 since it is now
possible to easily add wasm support thanks to:
https://github.com/matrix-org/matrix-rust-sdk/pull/4572

Using the `executer::spawn` will select `tokio::spawn` or
`wasm_bindgen_futures::spawn_local` based on what platform we are on.

~~They behave differently in that `tokio` actually starts the async
block inside the spawn but the wasm `spawn` wrapper will only start the
part that is not inside the `async` block and the join handle needs to
be awaited for it to work.~~

This has now changed with:
https://github.com/matrix-org/matrix-rust-sdk/pull/4572.
Now they behave the same and this PR becomes a very simple change.
2025-04-23 14:39:34 +02:00
Richard van der Hoff 7272a347fa Merge pull request #4961 from matrix-org/rav/history_sharing/deflake_integ_test
test: attempt to deflake history-sharing integ test
2025-04-23 11:49:41 +01:00
Richard van der Hoff 6d1c24f6fb test: attempt to deflake history-sharing test
Rather than attempting to trigger Alice's encryption sync loop with an incoming
message from Bob, instead have Alice send a message once Bob has joined the
room.
2025-04-23 11:33:06 +01:00
Richard van der Hoff 4300148663 test: factour out new helper wait_until_some. 2025-04-23 11:33:06 +01:00
Richard van der Hoff 75cde02283 Merge pull request #4946 from matrix-org/rav/history_sharing/share_on_invite
sdk: share room history when we send an invite, subject to an experimental feature flag.
2025-04-23 11:15:57 +01:00
Damir Jelić 59ecb1edbd fix(multiverse): Add a shortcut to mark rooms as read back 2025-04-23 11:39:59 +02:00
Richard van der Hoff 6e963917d6 sdk: clean up imports 2025-04-23 09:51:01 +01:00
Valere 7adf60d2c6 fixup: Cleaner ProcessedToDevice snapshot serialization 2025-04-22 16:30:53 +02:00
Valere bd576c22c0 fixup: test, redact snapshot value that is dependent of feature flag 2025-04-22 16:30:53 +02:00
Valere 35023ceb0b fixup: invalid tag in doc 2025-04-22 16:30:53 +02:00
Valere f1e7894c01 fixup: insta use shorter names 2025-04-22 16:30:53 +02:00
Valere ef44631fc6 review: remove outdated changelog line 2025-04-22 16:30:53 +02:00
Valere 541586f6cc review: add snapshot test with proper redaction 2025-04-22 16:30:53 +02:00
Valere f89150d3ee review: quick doc improvements 2025-04-22 16:30:53 +02:00
Valere b27770801c review: refactor, rename NotProcessed variant to Invalid 2025-04-22 16:30:53 +02:00
Valere a49bffac4c review: refactors ProcessedToDeviceEvent to tuple variants
Simplifies the `ProcessedToDeviceEvent` enum by converting its variants to tuple variants.

This change improves code readability and conciseness by removing the need for named fields within the variants.
2025-04-22 16:30:53 +02:00
Valere d4a0c2882d review: Move ProcessedToDeviceEvent to crypto types mod 2025-04-22 16:30:53 +02:00
Valere 031f4ec329 review: Remove encryption_info. Will be part of another PR 2025-04-22 16:30:53 +02:00
Valere 4bf103db38 test: Add more olm decryption encryption_info tests 2025-04-22 16:30:53 +02:00
Valere 4363105976 crypto: Add variants for plain text and encrypted to-device events
fixup: post rebase
2025-04-22 16:30:53 +02:00
Doug 3b133865f0 chore: Remove unused contacts field from OidcConfiguration. 2025-04-22 16:25:07 +02:00
Richard van der Hoff 82a0708b4e SDK: rename confusing-named Room::query_keys_for_untracked_users
This also sends out the query for dirty users, so the name was misleading.
2025-04-22 15:19:51 +01:00
dependabot[bot] 3eafefcf37 chore(deps): Bump tj-actions/changed-files
Bumps [tj-actions/changed-files](https://github.com/tj-actions/changed-files) from 9b4bb2bedb217d3ede225b6b07ebde713177cd8f to c34c1c13a740b06851baff92ab9a653d93ad6ce7.
- [Release notes](https://github.com/tj-actions/changed-files/releases)
- [Changelog](https://github.com/tj-actions/changed-files/blob/main/HISTORY.md)
- [Commits](https://github.com/tj-actions/changed-files/compare/9b4bb2bedb217d3ede225b6b07ebde713177cd8f...c34c1c13a740b06851baff92ab9a653d93ad6ce7)

---
updated-dependencies:
- dependency-name: tj-actions/changed-files
  dependency-version: c34c1c13a740b06851baff92ab9a653d93ad6ce7
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-22 10:02:57 +02:00
Andy Balaam d2874afb75 fix(integration-tests): Fixes #4871 (hopefully). Repeatedly sync in a test after other user cross-signs 2025-04-17 13:51:32 +02:00
Damir Jelić a848506669 feat(multiverse): Add a /invite command 2025-04-17 12:03:51 +02:00
Damir Jelić f0e49c2adf feat(multiverse): Render membership changes 2025-04-17 12:03:51 +02:00
Ivan Enderlin 74e2e767dd fix(base): Add RoomNotableUpdateReasons::NONE to… fix a possible regression.
This patch introduces a temporary hack.

So here is the thing. Ideally, we DO NOT want to emit this reason.
It does not makes sense. However, all notable update reasons
are not clearly identified so far. Why is it a problem? The
`matrix_sdk_ui::room_list_service::RoomList` is listening this stream
of [`RoomInfoNotableUpdate`], and emits an update on a room item if
it receives a notable reason. Because all reasons are not identified,
we are likely to miss particular updates, and it can feel broken.
Ultimately, we want to clearly identify all the notable update reasons,
and remove this one.
2025-04-17 09:13:41 +03:00
Ivan Enderlin 3ec831f5da test(base): Update tests after the previous patch.
This patch updates the tests, which now break because of the previous
batch that fixes a bug.
2025-04-17 09:13:41 +03:00
Ivan Enderlin ab34330e47 fix(base): Do not emit an RoomInfoNotableUpdate with empty reasons.
In case an empty `RoomInfoNotableUpdateReasons` is empty, let's not send
a `RoomInfoNotableUpdate`.
2025-04-17 09:13:41 +03:00
Ivan Enderlin 35e5cca3fb fix(base): room::display_name emits a RoomInfoNotableUpdateReasons::DISPLAY_NAME.
This patch updates the `room::display_name` response processor to emits
a `RoomInfoNotableUpdateReasons::DISPLAY_NAME`.
2025-04-17 09:13:41 +03:00
Ivan Enderlin 80a7aadf9f feat(base): changes::save_only will also broadcast room info notable updates.
This patch changes the `changes::save_only` and
`changes::save_and_apply` response processors to both broadcast the
`RoomInfoNotableUpdates`.
2025-04-17 09:13:41 +03:00
Ivan Enderlin 4837add55e test(base): Test that sliding sync persists the room (cached) display name. 2025-04-17 09:13:41 +03:00
Ivan Enderlin abf0bbb1a6 fix(base): Use the room::display_name processor for sync v2.
This patch uses `room::display_name` and `changes::save_only` to compute
the new display name for all rooms and save them, for sync v2 only.
2025-04-17 09:13:41 +03:00
Ivan Enderlin c1d885f913 fix(base): Create the room::display_name response processor.
This patch creates the `room::display_name::update_for_rooms` response
processor. It also creates the `changes::save_only` response processor.
Finally, this patch uses both to compute the new display name for all
rooms and save them, for sliding sync only.
2025-04-17 09:13:41 +03:00
Ivan Enderlin 568e60b434 refactor(base): Extract the “save” part of save_and_apply into its own function.
This patch extracts the “save” part of the `save_and_apply` response
processor into its own function. Thus we have `save_changes` (new) and
`apply_changes` that are used by `save_and_apply`.
2025-04-17 09:13:41 +03:00
Ivan Enderlin d05796d8cb task(base): Room::compute_display_name returns an UpdatedRoomDisplayName.
This patch updates `Room::compute_display_name` to return an
`UpdatedRoomDisplayName`. This is useful to know if the display name has
changed or not.
2025-04-17 09:13:41 +03:00
Ivan Enderlin adb7cd33d1 task(base): Introduce UpdatedRoomDisplayName.
This patch introduces a new enum: `UpdatedRoomDisplayName`, which
will be used to know if a room display name is different or not when
computing the room display name.
2025-04-17 09:13:41 +03:00
Richard van der Hoff 18f20a7e29 sdk: only share history if cross-signing is set up
... otherwise, it fails with an error, which makes the integ tests fail
2025-04-16 16:53:31 +01:00
Richard van der Hoff 96bdd91bad sdk: share room history when we send an invite
... subject to an experimental feature flag.
2025-04-16 16:53:27 +01:00
Damir Jelić bc50cae35f feat(multiverse): Add support to join rooms you've been invited to 2025-04-16 11:35:57 +02:00
Stefan Ceriu d36b2a6869 feat(ffi): introduce a ThreadSummary type within MsgLikeContent (#4933)
…that holds information on the thread the given item is the root of

- it holds the latest event content and sender at the moment but will
hold more information in the future e.g. number of replies, if it's
unread etc.
- the field is not currently being populate but is delivered earlier so
it can power shipping the UI side on the embedders
2025-04-16 09:11:31 +03:00
Richard van der Hoff ed232df0b6 Merge pull request #4864 from matrix-org/rav/history_sharing/upload_bundle
crypto: encrypt, upload and share keys for room history
2025-04-15 18:00:03 +01:00
Richard van der Hoff 1a4f6effda Merge branch 'main' into rav/history_sharing/upload_bundle
Signed-off-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
2025-04-15 17:43:01 +01:00
Richard van der Hoff dc6fe93d1e crypto: fix changelog for 0.10.0 and 0.11.0 (#4939)
PR #4670 didn't land until 0.11.0.
2025-04-15 17:12:32 +01:00
Benjamin Bouvier a5537a8f24 fix(event cache): don't ditch a previous-batch token when we didn't have initial events (#4936)
See #4891 that shows a case where we should have saved the
previous-batch token, and instead ditched it, in the previous version.

Changes include:
- moving the code deciding to keep or ditch the `previous-batch` token
into `append_events_locked`.
- tweak the condition to ditch, so that the `previous-batch` token is
ditched only if we didn't have events in the event cache in the first
place, in addition to having storage + the timeline not being marked as
limited explicitly.

Credits to @zecakeh for the test case.
2025-04-15 15:29:11 +00:00
Benjamin Bouvier a27d6e2655 multiverse: prefer rendering back-paginated events instead of timeline's tail
This is useful to observe the virtyual start of timeline item in manual
testing.
2025-04-15 16:31:20 +02:00
Richard van der Hoff bce6c19bba Merge branch 'main' into rav/history_sharing/upload_bundle
Signed-off-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
2025-04-15 14:32:42 +01:00
Ivan Enderlin 22d092b83c chore(base): Rename ephemeral_events to dispatch_ephemeral_events. 2025-04-15 14:17:07 +02:00
Ivan Enderlin ee5671bef5 chore(base): Rename Room to RoomCreationData. 2025-04-15 14:17:07 +02:00
Ivan Enderlin 0b58b9112d chore(base): Make Clippy happy. 2025-04-15 14:17:07 +02:00
Ivan Enderlin 0fed5147b9 chore(base): Use Entry::or_default() to simplify code. 2025-04-15 14:17:07 +02:00
Ivan Enderlin b06234149f chore(base): Fix imports and e2e-encryption. 2025-04-15 14:17:07 +02:00
Ivan Enderlin 739f306bf0 refactor(base): Create the room::msc4186::extensions::room_account_data response processor.
This patch is twofold:

1. it transforms the `&mut` to a `&` for the room account data in the
   sliding sync flow, which allows to remove one big clone!
2. it adds the `room_account_data` response processor.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 5f3c96607f refactor(base): Create the room::msc4186::extensions::ephemeral_events response processor.
This patch creates the new `room::msc4186::extensions::ephemeral_events`
response processor.

Ideally we would like to merge this with `ephemeral_events`, but they
are a bit different. Let's see how it evolves in the future.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 235facb793 refactor(base): room::sync_v2::update_(joined|left)_room use room::Room.
This patch uses the `room::Room` structure in `room::sync_v2` to
reduce the number of arguments of the `update_joined_room` and the
`update_left_room` processors.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 9adb0deaa5 refactor(base): room::msc4186::update_any_room uses room::Room.
This patch uses the `room::Room` structure in
`room::msc4186::update_any_room` to reduce its number of arguments. It
results in the removal of te `allow(clippy::too_many_arguments)`.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 61b711ce76 chore(base): Create the room::Room structure.
This patch creates the `room::Room` structure to group common arguments
in the `room` processors.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 9e6dc71609 refactor(base): Remove the BaseStateStore argument in room:sync_v2::* processors.
This patch removes the `BaseStateStore` argument in `room::sync_v2::*`
response processors as it can be fetched from the `Notification`
argument.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 33b1c02873 chore(base): Rename room_data to room_response.
This patch tries to clarify that the `room_data` _is_ the HTTP response.
2025-04-15 14:17:07 +02:00
Ivan Enderlin f4ad575090 refactor(base): Remove SessionMeta from update_any_room.
This patch removes the `SessionMeta` argument of
`room::msc4186::update_any_room`. Tracking its usage, it reveals that
providing a `UserId` is sufficient. Happily, we already provide a
`UserId`, hence making `SessionMeta` useless here.
2025-04-15 14:17:07 +02:00
Ivan Enderlin f55730716a chore(base): Rename a variable room_type to room_state. 2025-04-15 14:17:07 +02:00
Ivan Enderlin bad1c683f8 chore(base): Rename fields of RoomUpdate.
This patch renames the fields in `RoomUpdate`: `join` becomes `joined`,
`leave` becomes `left`, `invite` becomes `invited`, to match their
associate type.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 2479339c46 refactor(base): Simplify the flow of membership.
This patch simplifies the flow of `membership` when the room is an
invited room.

Previously, we were creating the room as `Invited`. Then, later
overriding it to `Knocked` if we found it was such a room. Otherwise, we
were overriding it again to `Invited`. Well. Now the flow is simpler.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 45d5d1a802 refactor(base): Remove the numerous Option<…> returned by update_any_room.
This patch removes the 4 `Option<…>` returned by `update_any_room`: they
are replaced by a single new `RoomUpdateKind` enum.
2025-04-15 14:17:07 +02:00
Ivan Enderlin a218105aca refactor(base): Create the room::msc4186::update_any_room response processor.
This patch extracts the `BaseClient::process_sliding_sync_room` method
into the new `msc4186::update_any_room` response processor. So far, this
is purely a code move, without any changes (modulo method-to-function
transformation).

With `BaseClient:process_sliding_sync_room` comes
`BaseClient::process_sliding_sync_room_membership`,
`BaseClient::handle_own_room_membership`, `process_room_properties` and
`cache_latest_events`.
2025-04-15 14:17:07 +02:00
Ivan Enderlin 6bbb7fb498 chore(base): Remove unnecessary comments.
This patch removes comments that are irrelevant today. There is nothing
to fix.
2025-04-15 14:17:07 +02:00
Richard van der Hoff 80db096be8 crypto: fix changelog 2025-04-15 12:55:55 +01:00
Richard van der Hoff 9ef1a040dd test: add the start of an integration test for room history sharing
This is only a partial test, since we haven't yet implemented the receiver side
of the history-sharing messages.
2025-04-15 12:55:55 +01:00
Richard van der Hoff f11158ab6c sdk: send out the to-device requests created by Room::share_history 2025-04-15 12:55:55 +01:00
Richard van der Hoff 84a030aed0 crypto: Support for encrypting and sending room key history bundle data
For each device belonging to the user, encrypt and send to-device messages
containing the bundle data
2025-04-15 12:55:55 +01:00
Richard van der Hoff 7b25a50a51 sdk: add Room::share_history
The next step in our work on sharing encrypted room history. Add a method to
`matrix_sdk::room::Room` which will upload an encrypted key bundle.
2025-04-15 12:55:55 +01:00
Ivan Enderlin f32d0099fc chore(base): Make Clippy happy. 2025-04-15 11:57:39 +02:00
Ivan Enderlin 6d9cf861f6 chore(base): Remove the re-exports in timeline::builder.
This patch removes the re-exports of `Notification` and `E2EE` in
`timeline::builder`. Let's make things simple now that they are used
outside the `timeline` processors.
2025-04-15 11:57:39 +02:00
Ivan Enderlin 13e565a4dc refactor(base): Create the room::sync_v2::update_knocked_room response processor.
This patch creates the `update_knocked_room` processor, extracted from
the sync v2 flow.
2025-04-15 11:57:39 +02:00
Ivan Enderlin aeca1f1495 refactor(base): Use Notification wherever possible.
This patch groups arguments behind the `Notification` struct
if it makes sense. This patch also uses the new method
`Notification::push_notification_from_event_if` method to replace
duplicated code.
2025-04-15 11:57:39 +02:00
Ivan Enderlin c16bc6b435 refactor(base): Move and improve the Notification struct in response processors.
This patch moves the `timeline::builder::Notification` into
its own module, `notification`. This patch adds two methods:
`push_notification` and `push_notification_from_event_if`.
2025-04-15 11:57:39 +02:00
Ivan Enderlin 846fcfb408 feat(base): Add From implementations to build a RawAnySyncOrStrippedTimelineEvent.
This patch adds two `From` implementations on
`RawAnySyncOrStrippedTimelineEvent` to create the correct variant of
this enum. This is useful when we get generic types and want to build
this type.
2025-04-15 11:57:39 +02:00
Ivan Enderlin 1141b7db1a refactor(base): Create the room::sync_v2::update_invited_room response processor.
This patch creates the `update_invited_room` processor by extracting the
code for the sync v2 flow.
2025-04-15 11:57:39 +02:00
Ivan Enderlin b85a1a0998 refactor(base): Create the room::sync_v2::update_left_room response processor.
This patch creates the `update_left_room` processor, extracted from the
sync v2 flow.

I've noticed that `new_user_ids` is not used, so it has been put behind
a `_` variable for the moment, but some computations have been removed.
We need to clean this user ID flow.
2025-04-15 11:57:39 +02:00
Ivan Enderlin e62313d7ba reefactor(base): Create the room::sync_v2::update_joined_room response processor.
This patch extracts the logic to handle a `JoinedRoom` in a response
processor.
2025-04-15 11:57:39 +02:00
Ivan Enderlin 71510de602 refactor(base): Extract timeline::builder::E2EE into e2ee, and use it more.
This patch moves the `timeline::builder::E2EE` type into the `e2ee`
module. Gathering these 3 E2EE values in the same type was a good idea,
and is now applied to more places in the response processors.
2025-04-15 11:57:39 +02:00
Ivan Enderlin 28888a414b refactor(base): Compute now if and only if Level::INFO is enabled.
This patch computes the `now` variable if and only if it is required.
It is used by an `info!` log, so let's condition the creation of `now`
to that.
2025-04-15 11:57:39 +02:00
Ivan Enderlin 3538bb91e3 refactor(base): Context derives Default.
This patch makes `Context` to derive `Default`. The `new` constructor
also no longer takes a `RoomInfoNotableUpdates`, since it was always
used with a default value, it generates this value by itself.
2025-04-15 11:57:39 +02:00
Ivan Enderlin fdcc6dbeda chore(base): Replace an unwrap by an expect.
This patch updates a comment and replaces an `unwrap` by an `expect`.
2025-04-15 11:57:39 +02:00
dependabot[bot] f1cd8120a8 chore(deps): Bump tj-actions/changed-files
Bumps [tj-actions/changed-files](https://github.com/tj-actions/changed-files) from 6f67ee9ac810f0192ea7b3d2086406f97847bcf9 to 9b4bb2bedb217d3ede225b6b07ebde713177cd8f.
- [Release notes](https://github.com/tj-actions/changed-files/releases)
- [Changelog](https://github.com/tj-actions/changed-files/blob/main/HISTORY.md)
- [Commits](https://github.com/tj-actions/changed-files/compare/6f67ee9ac810f0192ea7b3d2086406f97847bcf9...9b4bb2bedb217d3ede225b6b07ebde713177cd8f)

---
updated-dependencies:
- dependency-name: tj-actions/changed-files
  dependency-version: 9b4bb2bedb217d3ede225b6b07ebde713177cd8f
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-15 11:31:54 +02:00
Richard van der Hoff 473852c7d5 Merge pull request #4922 from matrix-org/rav/check_sender_device_keys
crypto: check `sender_device_keys` on incoming Olm messages
2025-04-15 10:18:50 +01:00
Ivan Enderlin f19f8b25db fix(sdk): Remove include_heroes in sliding sync requests.
This patch removes all mentions of `include_heroes`. This field isn't
part of the MSC4186. We have the `test_compute_heroes_from_sliding_sync`
which continues to pass, everything fine on that side. There is no
mention of `include_heroes` in Synapse at the time of writing. It seems
to be an artifact from the sliding sync proxy experiment.
2025-04-14 18:26:27 +02:00
Jonas Richard Richter 4de202fc64 doc(changelog): add entry for room topic string in StateEventContent 2025-04-14 15:43:17 +02:00
Jonas Richard Richter 7b206d33f0 feat(ffi): update RoomTopic AnySyncStateEvent variant to include topic string 2025-04-14 15:43:17 +02:00
Ivan Enderlin 085de8bdae refactor(base): Create the ephemeral_events response processor.
This patch creates the `ephemeral_events` response processors:
`dispatch` and `dispatch_one`.

This remove duplicated code.
2025-04-14 08:48:18 +02:00
Ivan Enderlin fe0b954019 refactor(base): Create the dispatch_invite_and_knock response processor.
This patch creates the
`state_events::stripped::dispatch_invite_and_knock`, that is migrated
from the `BaseClient::handle_invite_state` method.
2025-04-14 08:48:18 +02:00
Ivan Enderlin e21ae2ae53 chore(base): Move dispatch_and_get_new_users inside the sync module.
This patch moves the `state_events::dispatch_and_get_new_users`
processor inside the `state_events::sync` module. Why? Because a similar
processor for `state_events::stripped` is about to be created.
2025-04-14 08:48:18 +02:00
Jorge Martín 0306683cbf feat(ffi): Add extra details to ClientError.
Also split `ClientError::new` into `ClientError::from_str` and `ClientError::from_err` so we can automatically get the details from the 2nd one.
2025-04-11 15:49:20 +02:00
Richard van der Hoff e020ba1023 crypto: check sender_device_keys on incoming Olm messages
MSC4147 added a `sender_device_keys` property to olm-encrypted to-device
messages, with recommendations about checking the values in that propety. We do
(most of?) those checks for `m.room_key` messages today, but not other types of
to-device message.
2025-04-11 12:00:18 +01:00
Richard van der Hoff 0697e0705b crypto: support MSC4147 device keys on custom to-device events
MSC4147 added a `sender_device_keys` property to the plaintext of *all*
olm-encrypted events. 03d4a30eb added the field to `DecryptedOlmV1Event`, but
due to Reasons, there is an almost-parallel struct `ToDeviceCustomEvent` which
is used for event types other than the 4 we have content types for.

To complete the set, let's add the field to `ToDeviceCustomEvent`.
2025-04-11 11:01:22 +01:00
664 changed files with 79230 additions and 28821 deletions
+9
View File
@@ -2,3 +2,12 @@
retries = { backoff = "exponential", count = 3, delay = "1s", jitter = true }
# kill the slow tests if they still aren't up after 180s
slow-timeout = { period = "60s", terminate-after = 3 }
[profile.ci]
retries = { backoff = "exponential", count = 4, delay = "1s", jitter = true }
# kill the slow tests if they still aren't up after 180s
slow-timeout = { period = "60s", terminate-after = 3 }
[profile.ci.junit]
path = "junit.xml"
store-success-output = true
+2 -12
View File
@@ -17,6 +17,7 @@ version = 2
allow = [
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"CDLA-Permissive-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"BSL-1.0",
@@ -28,15 +29,6 @@ allow = [
]
exceptions = [
{ allow = ["Unicode-DFS-2016"], crate = "unicode-ident" },
{ allow = ["CDDL-1.0"], crate = "inferno" },
{ allow = ["LicenseRef-ring"], crate = "ring" },
]
[[licenses.clarify]]
name = "ring"
expression = "LicenseRef-ring"
license-files = [
{ path = "LICENSE", hash = 0xbd0eed23 },
]
[bans]
@@ -51,9 +43,7 @@ unknown-git = "deny"
allow-git = [
# A patch override for the bindings fixing a bug for Android before upstream
# releases a new version.
"https://github.com/element-hq/tracing.git",
# Sam as for the tracing dependency.
"https://github.com/element-hq/paranoid-android.git",
"https://github.com/tokio-rs/tracing.git",
# Well, it's Ruma.
"https://github.com/ruma/ruma",
# A patch override for the bindings: https://github.com/rodrimati1992/const_panic/pull/10
+26 -40
View File
@@ -1,54 +1,40 @@
name: Benchmarks
on:
push:
branches:
- "main"
pull_request:
workflow_dispatch:
jobs:
benchmarks:
name: Run Benchmarks
runs-on: ubuntu-latest
environment: matrix-rust-bot
if: github.event_name == 'push'
strategy:
matrix:
benchmark:
- crypto_bench
- event_cache
- linked_chunk
- store_bench
- timeline
steps:
- name: Checkout the repo
uses: actions/checkout@v4
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8
- name: Install Rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly-2025-02-20
components: rustfmt
- name: Setup rust toolchain, cache and cargo-codspeed binary
uses: moonrepo/setup-rust@ede6de059f8046a5e236c94046823e2af11ca670
with:
channel: stable
cache-target: release
bins: cargo-codspeed
- name: Run Benchmarks
run: cargo bench | tee benchmark-output.txt
- name: Build the benchmark target(s)
run: cargo codspeed build -p benchmarks ${{ matrix.benchmark }} --features codspeed
- name: Check benchmark result for PR
if: github.event_name == 'pull_request'
uses: benchmark-action/github-action-benchmark@v1
with:
name: Rust Benchmark
tool: 'cargo'
output-file-path: benchmark-output.txt
auto-push: false
# comment to alert the user this has gone bad
github-token: ${{ secrets.MRB_ACCESS_TOKEN }}
alert-threshold: '120%'
comment-on-alert: true
fail-threshold: '150%'
fail-on-alert: true
- name: Store benchmark result
if: github.event_name != 'pull_request'
uses: benchmark-action/github-action-benchmark@v1
with:
name: Rust Benchmark
tool: 'cargo'
output-file-path: benchmark-output.txt
github-token: ${{ secrets.GITHUB_TOKEN }}
auto-push: true
# Show alert with commit comment on detecting possible performance regression
alert-threshold: '150%'
comment-on-alert: true
fail-on-alert: true
alert-comment-cc-users: '@gnunicornBen,@jplatte,@poljar'
- name: Run the benchmarks
uses: CodSpeedHQ/action@76578c2a7ddd928664caa737f0e962e3085d4e7c
with:
run: cargo codspeed run
token: ${{ secrets.CODSPEED_TOKEN }}
+7 -7
View File
@@ -31,7 +31,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install protoc
uses: taiki-e/install-action@v2
@@ -69,17 +69,17 @@ jobs:
steps:
- name: Checkout Rust SDK
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Checkout Kotlin Rust Components project
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
repository: matrix-org/matrix-rust-components-kotlin
path: rust-components-kotlin
ref: main
- name: Use JDK 17
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: 'temurin' # See 'Supported distributions' for available options
java-version: '17'
@@ -136,7 +136,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
# install protoc in case we end up rebuilding opentelemetry-proto
- name: Install protoc
@@ -175,7 +175,7 @@ jobs:
run: swift test
- name: Build Framework
run: target/debug/xtask swift build-framework --target=aarch64-apple-ios --profile=reldbg
run: target/debug/xtask swift build-framework --target=aarch64-apple-ios --profile=dev --ios-deployment-target=18.0
complement-crypto:
name: "Run Complement Crypto tests"
@@ -191,7 +191,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
# install protoc in case we end up rebuilding opentelemetry-proto
- name: Install protoc
+24 -23
View File
@@ -6,11 +6,6 @@ on:
branches: [main]
pull_request:
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -39,14 +34,16 @@ jobs:
- no-sqlite
- no-encryption-and-sqlite
- sqlite-cryptostore
- experimental-encrypted-state-events
- rustls-tls
- markdown
- socks
- sso-login
- search
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
@@ -88,7 +85,7 @@ jobs:
steps:
- name: Checkout the repo
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
@@ -119,7 +116,7 @@ jobs:
steps:
- name: Checkout the repo
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install libsqlite
run: |
@@ -170,7 +167,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install protoc
uses: taiki-e/install-action@v2
@@ -242,7 +239,7 @@ jobs:
steps:
- name: Checkout the repo
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
@@ -251,10 +248,10 @@ jobs:
components: clippy
- name: Install wasm-pack
uses: qmaru/wasm-pack-action@v0.5.0
uses: qmaru/wasm-pack-action@v0.5.1
if: '!matrix.check_only'
with:
version: v0.10.3
version: v0.13.1
- name: Load cache
uses: Swatinem/rust-cache@v2
@@ -292,10 +289,10 @@ jobs:
steps:
- name: Checkout Actions Repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Check the spelling of the files in our repo
uses: crate-ci/typos@v1.31.1
uses: crate-ci/typos@v1.35.7
lint:
name: Lint
@@ -304,7 +301,7 @@ jobs:
steps:
- name: Checkout the repo
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install protoc
uses: taiki-e/install-action@v2
@@ -314,7 +311,7 @@ jobs:
- name: Install Rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly-2025-02-20
toolchain: nightly-2025-08-08
components: clippy, rustfmt
- name: Load cache
@@ -338,8 +335,7 @@ jobs:
target/debug/xtask ci clippy
integration-tests:
name: Integration test
name: 'Integration test (features: ${{ matrix.feature }})'
runs-on: ubuntu-latest
# run several docker containers with the same networking stack so the hostname 'synapse'
@@ -355,9 +351,16 @@ jobs:
ports:
- 8008:8008
strategy:
fail-fast: true
matrix:
feature:
- "default"
- "experimental-encrypted-state-events"
steps:
- name: Checkout the repo
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install libsqlite
run: |
@@ -380,9 +383,8 @@ jobs:
RUST_LOG: "info,matrix_sdk=trace"
HOMESERVER_URL: "http://localhost:8008"
HOMESERVER_DOMAIN: "synapse"
SLIDING_SYNC_PROXY_URL: "http://localhost:8118"
run: |
cargo nextest run -p matrix-sdk-integration-testing
cargo nextest run -p matrix-sdk-integration-testing --features "${{ matrix.feature }}"
compile-bench:
name: 🚄 Compile benchmarks
@@ -390,7 +392,7 @@ jobs:
steps:
- name: Checkout the repo
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
@@ -403,4 +405,3 @@ jobs:
- name: Compile benchmarks (no run)
run: |
cargo bench --profile dev --no-run
+89 -20
View File
@@ -5,11 +5,6 @@ on:
branches: [main]
pull_request:
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -22,8 +17,12 @@ env:
RUST_LOG: info,matrix_sdk=trace
jobs:
xtask:
uses: ./.github/workflows/xtask.yml
code_coverage:
name: Code Coverage
needs: xtask
runs-on: "ubuntu-latest"
# run several docker containers with the same networking stack so the hostname 'synapse'
@@ -40,8 +39,65 @@ jobs:
- 8008:8008
steps:
# This CI workflow can run into space issue, so we're cleaning up some
# space here.
- name: Create some more space
run: |
echo "Disk space before cleanup"
df -h
cd /opt
find . -maxdepth 1 -mindepth 1 '!' -path ./containerd '!' -path ./actionarchivecache '!' -path ./runner '!' -path ./runner-cache -exec rm -rf '{}' ';'
rm -rf /opt/hostedtoolcache
# Get rid of binaries and libs we're not interested in.
sudo rm -rf \
/usr/local/julia* \
/usr/local/aws*
sudo rm -rf \
/usr/local/bin/minikube \
/usr/local/bin/node \
/usr/local/bin/stack \
/usr/local/bin/bicep \
/usr/local/bin/pulumi* \
/usr/local/bin/helm \
/usr/local/bin/azcopy \
/usr/local/bin/packer \
/usr/local/bin/cmake-gui \
/usr/local/bin/cpack
sudo rm -rf \
/usr/local/share/powershell \
/usr/local/share/chromium
sudo rm -rf /usr/local/lib/android
echo "::group::/usr/local/bin/*"
du -hsc /usr/local/bin/* | sort -h
echo "::endgroup::"
echo "::group::/usr/local/share/*"
du -hsc /usr/local/share/* | sort -h
echo "::endgroup::"
echo "::group::/usr/local/*"
du -hsc /usr/local/* | sort -h
echo "::endgroup::"
echo "::group::/usr/local/lib/*"
du -hsc /usr/local/lib/* | sort -h
echo "::endgroup::"
echo "::group::/opt/*"
du -hsc /opt/* | sort -h
echo "::endgroup::"
echo "Disk space after cleanup"
df -h
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
ref: ${{ github.event.pull_request.head.sha }}
@@ -49,6 +105,8 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install libsqlite3-dev
sudo apt-get clean
sudo rm -rf /var/lib/apt/lists/*
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
@@ -61,29 +119,34 @@ jobs:
- name: Load cache
uses: Swatinem/rust-cache@v2
with:
prefix-key: "coverage"
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Install tarpaulin
uses: taiki-e/install-action@v2
with:
tool: cargo-tarpaulin
- name: Install cargo-llvm-cov
uses: taiki-e/install-action@cargo-llvm-cov
# set up backend for integration tests
- uses: actions/setup-python@v5
with:
python-version: 3.8
- name: Install nextest
uses: taiki-e/install-action@nextest
- name: Run tarpaulin
- name: Get xtask
uses: actions/cache/restore@v4
with:
path: target/debug/xtask
key: "${{ needs.xtask.outputs.cachekey-linux }}"
fail-on-cache-miss: true
- name: Check total disk space before running
run: |
rustup run stable cargo tarpaulin \
--skip-clean --profile cov --out xml \
--features experimental-widgets,testing
df -h
- name: Create the coverage report
run: |
target/debug/xtask ci coverage -o codecov
env:
CARGO_PROFILE_COV_INHERITS: 'dev'
CARGO_PROFILE_COV_DEBUG: 1
HOMESERVER_URL: "http://localhost:8008"
HOMESERVER_DOMAIN: "synapse"
SLIDING_SYNC_PROXY_URL: "http://localhost:8118"
# Copied with minimal adjustments, source:
# https://github.com/google/mdbook-i18n-helpers/blob/2168b9cea1f4f76b55426591a9bcc308a620194f/.github/workflows/test.yml
@@ -95,6 +158,11 @@ jobs:
echo "Storing commit SHA ${{ github.event.pull_request.head.sha }}"
echo "${{ github.event.pull_request.head.sha }}" > commit_sha.txt
- name: Move the JUnit file into the root directory
shell: bash
run: |
mv target/nextest/ci/junit.xml ./junit.xml
# This stores the coverage report and metadata in artifacts.
# The actual upload to Codecov is executed by a different workflow `upload_coverage.yml`.
# The reason for this split is because `on.pull_request` workflows don't have access to secrets.
@@ -103,7 +171,8 @@ jobs:
with:
name: codecov_report
path: |
cobertura.xml
coverage.xml
junit.xml
pr_number.txt
commit_sha.txt
if-no-files-found: error
+1 -1
View File
@@ -10,5 +10,5 @@ jobs:
cargo-deny:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: EmbarkStudios/cargo-deny-action@v2
+2 -7
View File
@@ -7,11 +7,6 @@ on:
workflow_dispatch:
pull_request: # focus on the changed files in current PR
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -22,10 +17,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Check for changed files
id: changed-files
uses: tj-actions/changed-files@6f67ee9ac810f0192ea7b3d2086406f97847bcf9 # v45
uses: tj-actions/changed-files@v46.0.5
- name: Detect long path
env:
ALL_CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }} # ignore the deleted files
@@ -7,6 +7,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Machete
uses: bnjbvr/cargo-machete@v0.8.0
uses: bnjbvr/cargo-machete@v0.9.1
+3 -8
View File
@@ -4,11 +4,6 @@ on:
push:
branches: [main]
pull_request:
types:
- opened
- reopened
- synchronize
- ready_for_review
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -26,7 +21,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install protoc
uses: taiki-e/install-action@v2
@@ -36,7 +31,7 @@ jobs:
- name: Install Rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly-2025-02-20
toolchain: nightly-2025-08-08
- name: Install Node.js
uses: actions/setup-node@v4
@@ -57,7 +52,7 @@ jobs:
- name: Upload artifact
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: actions/upload-pages-artifact@v3
uses: actions/upload-pages-artifact@v4
with:
path: './target/doc/'
+1 -1
View File
@@ -7,6 +7,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Block Fixup Commit Merge
uses: 13rac1/block-fixup-merge-action@v2.0.0
+1 -6
View File
@@ -6,16 +6,11 @@ on:
branches: [main]
pull_request:
branches: [main]
types:
- opened
- reopened
- synchronize
- ready_for_review
jobs:
msrv:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: taiki-e/install-action@cargo-hack
- run: cargo hack check --rust-version --workspace --all-targets --ignore-private
+18 -1
View File
@@ -58,7 +58,7 @@ jobs:
echo "override_commit=$(<commit_sha.txt)" >> "$GITHUB_OUTPUT"
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
ref: ${{ steps.parse_previous_artifacts.outputs.override_commit || '' }}
path: repo_root
@@ -77,3 +77,20 @@ jobs:
working-directory: ${{ github.workspace }}/repo_root
# Location where coverage report files are searched for
directory: ${{ github.workspace }}
- name: Upload test results to Codecov
uses: codecov/test-results-action@v1
with:
token: ${{ secrets.CODECOV_UPLOAD_TOKEN }}
fail_ci_if_error: true
# Manual overrides for these parameters are needed because automatic detection
# in codecov-action does not work for non-`pull_request` workflows.
# In `main` branch push, these default to empty strings since we want to run
# the analysis on HEAD.
override_commit: ${{ steps.parse_previous_artifacts.outputs.override_commit || '' }}
override_pr: ${{ steps.parse_previous_artifacts.outputs.override_pr || '' }}
working-directory: ${{ github.workspace }}/repo_root
# Location where coverage report files are searched for
directory: ${{ github.workspace }}
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
steps:
- name: Checkout repo
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Calculate cache key
id: cachekey
+1
View File
@@ -4,6 +4,7 @@ master.zip
emsdk-*
.idea/
.env
.envrc
.build
.swiftpm
/Package.swift
+17
View File
@@ -57,6 +57,23 @@ cargo insta test
cargo insta review
```
### Intermittent failure policy
While we strive to add test coverage for as many features as we can, it sometimes happens that the
tests will be intermittently failing in CI (such tests are sometimes called "flaky"). This can be
caused by race conditions of all sorts, either in the test code itself, but sometimes in the
underlying feature being tested too, and as such, it requires some investigation, usually from the
original author of the test.
Whenever such an intermittent failure happens, we try to open an issue to track the failures,
adding the
[`intermittent-failure`](https://github.com/matrix-org/matrix-rust-sdk/issues?q=is%3Aissue%20state%3Aopen%20label%3Aintermittent-failure)
label to it, and commenting with links to CI runs where the failure happened.
If a test has been intermittently failing for **two weeks** or more, and no one is actively working
on fixing it, then we might decide to mark the test as `ignored` until it is fixed, to not cause
unrelated failures in other contributors' pull requests and pushes.
## Pull requests
Ideally, a PR should have a *proper title*, with *atomic logical commits*, and
Generated
+1531 -670
View File
File diff suppressed because it is too large Load Diff
+98 -78
View File
@@ -4,35 +4,40 @@ members = [
"bindings/matrix-sdk-crypto-ffi",
"bindings/matrix-sdk-ffi",
"crates/*",
"testing/*",
"examples/*",
"labs/*",
"testing/*",
"uniffi-bindgen",
"xtask",
]
exclude = [
"testing/data",
]
exclude = ["testing/data"]
# xtask, testing and the bindings should only be built when invoked explicitly.
default-members = ["benchmarks", "crates/*", "labs/*"]
resolver = "2"
[workspace.package]
rust-version = "1.85"
rust-version = "1.88"
[workspace.dependencies]
anyhow = "1.0.95"
anyhow = "1.0.99"
aquamarine = "0.6.0"
as_variant = "1.3.0"
assert-json-diff = "2.0.2"
assert_matches = "1.5.0"
assert_matches2 = "0.1.2"
async-compat = "0.2.5"
async-rx = "0.1.3"
# Bumping this to 0.3.6 produces a test failure because the semantic between the
# versions changed subtly.
async-stream = "0.3.5"
async-trait = "0.1.85"
as_variant = "1.3.0"
async-trait = "0.1.89"
base64 = "0.22.1"
bitflags = "2.9.3"
byteorder = "1.5.0"
chrono = "0.4.39"
cfg-if = "1.0.3"
clap = "4.5.46"
chrono = "0.4.41"
dirs = "6.0.0"
eyeball = { version = "0.8.8", features = ["tracing"] }
eyeball-im = { version = "0.7.0", features = ["tracing"] }
eyeball-im-util = "0.9.0"
@@ -44,74 +49,114 @@ gloo-timers = "0.3.0"
growable-bloom-filter = "2.1.1"
hkdf = "0.12.4"
hmac = "0.12.1"
http = "1.2.0"
http = "1.3.1"
imbl = "5.0.0"
indexmap = "2.7.1"
insta = { version = "1.42.1", features = ["json", "redactions"] }
indexmap = "2.11.0"
insta = { version = "1.43.1", features = ["json", "redactions"] }
itertools = "0.14.0"
js-sys = "0.3.69"
js-sys = "0.3.77"
mime = "0.3.17"
once_cell = "1.20.2"
oauth2 = { version = "5.0.0", default-features = false, features = ["reqwest", "timing-resistant-secret-traits"] }
once_cell = "1.21.3"
pbkdf2 = { version = "0.12.2" }
pin-project-lite = "0.2.16"
proptest = { version = "1.6.0", default-features = false, features = ["std"] }
rand = "0.8.5"
reqwest = { version = "0.12.12", default-features = false }
reqwest = { version = "0.12.23", default-features = false }
rmp-serde = "1.3.0"
# Be careful to use commits from the https://github.com/ruma/ruma/tree/ruma-0.12
# branch until a proper release with breaking changes happens.
ruma = { version = "0.12.2", features = [
ruma = { version = "0.13.0", features = [
"client-api-c",
"compat-upload-signatures",
"compat-user-id",
"compat-arbitrary-length-ids",
"compat-tag-info",
"compat-encrypted-stickers",
"compat-lax-room-create-deser",
"compat-lax-room-topic-deser",
"unstable-msc3401",
"unstable-msc3266",
"unstable-msc3488",
"unstable-msc3489",
"unstable-msc4075",
"unstable-msc4140",
"unstable-msc4143",
"unstable-msc4171",
"unstable-msc4222",
"unstable-msc4278",
"unstable-msc4286",
"unstable-msc4306",
"unstable-msc4308"
] }
ruma-common = "0.15.2"
serde = "1.0.217"
sentry = { version = "0.42.0", default-features = false }
sentry-tracing = "0.42.0"
serde = { version = "1.0.219", features = ["rc"] }
serde_html_form = "0.2.7"
serde_json = "1.0.138"
sha2 = "0.10.8"
similar-asserts = "1.6.1"
serde_json = "1.0.143"
sha2 = "0.10.9"
similar-asserts = "1.7.0"
stream_assert = "0.1.1"
tempfile = "3.16.0"
thiserror = "2.0.11"
tokio = { version = "1.43.0", default-features = false, features = ["sync"] }
tempfile = "3.21.0"
thiserror = "2.0.16"
tokio = { version = "1.47.1", default-features = false, features = ["sync"] }
tokio-stream = "0.1.17"
tracing = { version = "0.1.40", default-features = false, features = ["std"] }
tracing-core = "0.1.32"
tracing-subscriber = "0.3.18"
tracing = { version = "0.1.41", default-features = false, features = ["std"] }
tracing-appender = "0.2.3"
tracing-core = "0.1.34"
tracing-subscriber = "0.3.20"
unicode-normalization = "0.1.24"
uniffi = { version = "0.28.0" }
uniffi_bindgen = { version = "0.28.0" }
url = "2.5.4"
uuid = "1.12.1"
url = "2.5.7"
uuid = "1.18.0"
vergen-gitcl = "1.0.8"
vodozemac = { version = "0.9.0", features = ["insecure-pk-encryption"] }
wasm-bindgen = "0.2.84"
wasm-bindgen-test = "0.3.33"
wasm-bindgen-test = "0.3.50"
web-sys = "0.3.69"
wiremock = "0.6.2"
wiremock = "0.6.5"
zeroize = "1.8.1"
matrix-sdk = { path = "crates/matrix-sdk", version = "0.11.0", default-features = false }
matrix-sdk-base = { path = "crates/matrix-sdk-base", version = "0.11.0" }
matrix-sdk-common = { path = "crates/matrix-sdk-common", version = "0.11.0" }
matrix-sdk-crypto = { path = "crates/matrix-sdk-crypto", version = "0.11.0" }
matrix-sdk = { path = "crates/matrix-sdk", version = "0.14.0", default-features = false }
matrix-sdk-base = { path = "crates/matrix-sdk-base", version = "0.14.0" }
matrix-sdk-common = { path = "crates/matrix-sdk-common", version = "0.14.0" }
matrix-sdk-crypto = { path = "crates/matrix-sdk-crypto", version = "0.14.0" }
matrix-sdk-ffi-macros = { path = "bindings/matrix-sdk-ffi-macros", version = "0.7.0" }
matrix-sdk-indexeddb = { path = "crates/matrix-sdk-indexeddb", version = "0.11.0", default-features = false }
matrix-sdk-qrcode = { path = "crates/matrix-sdk-qrcode", version = "0.11.0" }
matrix-sdk-sqlite = { path = "crates/matrix-sdk-sqlite", version = "0.11.0", default-features = false }
matrix-sdk-store-encryption = { path = "crates/matrix-sdk-store-encryption", version = "0.11.0" }
matrix-sdk-test = { path = "testing/matrix-sdk-test", version = "0.11.0" }
matrix-sdk-ui = { path = "crates/matrix-sdk-ui", version = "0.11.0", default-features = false }
matrix-sdk-indexeddb = { path = "crates/matrix-sdk-indexeddb", version = "0.14.0", default-features = false }
matrix-sdk-qrcode = { path = "crates/matrix-sdk-qrcode", version = "0.14.0" }
matrix-sdk-sqlite = { path = "crates/matrix-sdk-sqlite", version = "0.14.0", default-features = false }
matrix-sdk-store-encryption = { path = "crates/matrix-sdk-store-encryption", version = "0.14.0" }
matrix-sdk-test = { path = "testing/matrix-sdk-test", version = "0.14.0" }
matrix-sdk-test-utils = { path = "testing/matrix-sdk-test-utils", version = "0.14.0" }
matrix-sdk-ui = { path = "crates/matrix-sdk-ui", version = "0.14.0", default-features = false }
matrix-sdk-search = { path = "crates/matrix-sdk-search", version = "0.14.0" }
[workspace.lints.rust]
rust_2018_idioms = "warn"
semicolon_in_expressions_from_macros = "warn"
unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(tarpaulin_include)', # Used by tarpaulin (code coverage)
'cfg(ruma_unstable_exhaustive_types)', # Used by Ruma's EventContent derive macro
] }
unused_extern_crates = "warn"
unused_import_braces = "warn"
unused_qualifications = "warn"
trivial_casts = "warn"
trivial_numeric_casts = "warn"
[workspace.lints.clippy]
assigning_clones = "allow"
box_default = "allow"
cloned_instead_of_copied = "warn"
dbg_macro = "warn"
inefficient_to_string = "warn"
macro_use_imports = "warn"
manual_let_else = "warn"
mut_mut = "warn"
needless_borrow = "warn"
nonstandard_macro_braces = "warn"
redundant_clone = "warn"
str_to_string = "warn"
todo = "warn"
unnecessary_semicolon = "warn"
unused_async = "warn"
# Default development profile; default for most Cargo commands, otherwise
# selected with `--debug`
@@ -146,40 +191,15 @@ lto = false
# Get symbol names for profiling purposes.
debug = true
[profile.bench]
inherits = "release"
lto = false
[patch.crates-io]
async-compat = { git = "https://github.com/element-hq/async-compat", rev = "5a27c8b290f1f1dcfc0c4ec22c464e38528aa591" }
const_panic = { git = "https://github.com/jplatte/const_panic", rev = "9024a4cb3eac45c1d2d980f17aaee287b17be498" }
# Needed to fix rotation log issue on Android (https://github.com/tokio-rs/tracing/issues/2937)
tracing = { git = "https://github.com/element-hq/tracing.git", rev = "ca9431f74d37c9d3b5e6a9f35b2c706711dab7dd" }
tracing-core = { git = "https://github.com/element-hq/tracing.git", rev = "ca9431f74d37c9d3b5e6a9f35b2c706711dab7dd" }
tracing-subscriber = { git = "https://github.com/element-hq/tracing.git", rev = "ca9431f74d37c9d3b5e6a9f35b2c706711dab7dd" }
tracing-appender = { git = "https://github.com/element-hq/tracing.git", rev = "ca9431f74d37c9d3b5e6a9f35b2c706711dab7dd" }
paranoid-android = { git = "https://github.com/element-hq/paranoid-android.git", rev = "69388ac5b4afeed7be4401c70ce17f6d9a2cf19b" }
[workspace.lints.rust]
rust_2018_idioms = "warn"
semicolon_in_expressions_from_macros = "warn"
unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(tarpaulin_include)', # Used by tarpaulin (code coverage)
'cfg(ruma_unstable_exhaustive_types)', # Used by Ruma's EventContent derive macro
] }
unused_extern_crates = "warn"
unused_import_braces = "warn"
unused_qualifications = "warn"
trivial_casts = "warn"
trivial_numeric_casts = "warn"
[workspace.lints.clippy]
assigning_clones = "allow"
box_default = "allow"
cloned_instead_of_copied = "warn"
dbg_macro = "warn"
inefficient_to_string = "warn"
macro_use_imports = "warn"
mut_mut = "warn"
needless_borrow = "warn"
nonstandard_macro_braces = "warn"
str_to_string = "warn"
todo = "warn"
unused_async = "warn"
redundant_clone = "warn"
tracing = { git = "https://github.com/tokio-rs/tracing.git", rev = "20f5b3d8ba057ca9c4ae00ad30dda3dce8a71c05" }
tracing-core = { git = "https://github.com/tokio-rs/tracing.git", rev = "20f5b3d8ba057ca9c4ae00ad30dda3dce8a71c05" }
tracing-subscriber = { git = "https://github.com/tokio-rs/tracing.git", rev = "20f5b3d8ba057ca9c4ae00ad30dda3dce8a71c05" }
tracing-appender = { git = "https://github.com/tokio-rs/tracing.git", rev = "20f5b3d8ba057ca9c4ae00ad30dda3dce8a71c05" }
+48 -27
View File
@@ -1,38 +1,55 @@
<h1 align="center">Matrix Rust SDK</h1>
<div align="center">
<i>Your all-in-one toolkit for creating Matrix clients with Rust, from simple bots to full-featured apps.</i>
<br/><br/>
<img src="contrib/logo.svg">
<br>
<hr>
<a href="https://github.com/matrix-org/matrix-rust-sdk/releases">
<img src="https://img.shields.io/github/v/release/matrix-org/matrix-rust-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=GitHub&logoColor=white"></a>
<a href="https://crates.io/crates/matrix-sdk/">
<img src="https://img.shields.io/crates/v/matrix-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=Rust&logoColor=white"></a>
<a href="https://codecov.io/gh/matrix-org/matrix-rust-sdk">
<img src="https://img.shields.io/codecov/c/gh/matrix-org/matrix-rust-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=Codecov&logoColor=white"></a>
<br>
<a href="https://docs.rs/matrix-sdk/">
<img src="https://img.shields.io/docsrs/matrix-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=Rust&logoColor=white"></a>
<a href="https://github.com/matrix-org/matrix-rust-sdk/actions/workflows/ci.yml">
<img src="https://img.shields.io/github/actions/workflow/status/matrix-org/matrix-rust-sdk/ci.yml?style=flat&labelColor=1C2E27&color=66845F&logo=GitHub%20Actions&logoColor=white"></a>
<br>
<br>
<em>Your all-in-one toolkit for creating Matrix clients with Rust, from simple bots to full-featured apps.</em>
<br />
<img src="contrib/logo.svg">
<hr />
<a href="https://github.com/matrix-org/matrix-rust-sdk/releases">
<img src="https://img.shields.io/github/v/release/matrix-org/matrix-rust-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=GitHub&logoColor=white"></a>
<a href="https://crates.io/crates/matrix-sdk/">
<img src="https://img.shields.io/crates/v/matrix-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=Rust&logoColor=white"></a>
<a href="https://codecov.io/gh/matrix-org/matrix-rust-sdk">
<img src="https://img.shields.io/codecov/c/gh/matrix-org/matrix-rust-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=Codecov&logoColor=white"></a>
<br />
<a href="https://docs.rs/matrix-sdk/">
<img src="https://img.shields.io/docsrs/matrix-sdk?style=flat&labelColor=1C2E27&color=66845F&logo=Rust&logoColor=white"></a>
<a href="https://github.com/matrix-org/matrix-rust-sdk/actions/workflows/ci.yml">
<img src="https://img.shields.io/github/actions/workflow/status/matrix-org/matrix-rust-sdk/ci.yml?style=flat&labelColor=1C2E27&color=66845F&logo=GitHub%20Actions&logoColor=white"></a>
</div>
<div align="center">
The Matrix Rust SDK is a collection of libraries that make it easier to build
[Matrix] clients in [Rust]. It takes care of the low-level details like encryption,
The Matrix Rust SDK is a collection of libraries that make it easier to build [Matrix] clients in [Rust].
<br />
<br />
<picture>
<source srcset="contrib/element-logo-light.png" media="(prefers-color-scheme: dark)">
<source srcset="contrib/element-logo-dark.png" media="(prefers-color-scheme: light)">
<img src="contrib/element-logo-fallback.png" alt="Element logo">
</picture>
<br />
<br />
Development of the SDK is proudly sponsored and maintained by [Element](https://element.io). Element uses the SDK in their next-generation mobile apps Element X on [iOS](https://github.com/element-hq/element-x-ios) and [Android](https://github.com/element-hq/element-x-android) and has plans to introduce it to the web and desktop clients as well.
The SDK is also the basis for multiple Matrix projects and we welcome contributions from all.
</div>
## Purpose
The SDK takes care of the low-level details like encryption,
syncing, and room state, so you can focus on your app's logic and UI. Whether
you're writing a small bot, a desktop client, or something in between, the SDK
is designed to be flexible, async-friendly, and ready to use out of the box.
[Matrix]: https://matrix.org/
[Rust]: https://www.rust-lang.org/
## Project structure
The Matrix Rust SDK is made up of several crates that build on top of each other. Here are the key ones:
The Matrix Rust SDK is made up of several crates that build on top of each
other. The following crates are expected to be usable as direct dependencies:
- [matrix-sdk-ui](https://docs.rs/matrix-sdk-ui/latest/matrix_sdk_ui/) A high-level client library that makes it easy to build
full-featured UI clients with minimal setup. Check out our reference client,
@@ -45,6 +62,9 @@ The Matrix Rust SDK is made up of several crates that build on top of each other
See the [crypto tutorial](https://docs.rs/matrix-sdk-crypto/latest/matrix_sdk_crypto/tutorial/index.html)
for a step-by-step introduction.
All other crates are effectively internal-only and only structured as crates
for organizational purposes and to improve compilation times. Direct usage of them is discouraged.
## Status
The library is considered production ready and backs multiple client
@@ -54,9 +74,6 @@ implementations such as Element X
[Fractal](https://gitlab.gnome.org/World/fractal) and [iamb](https://github.com/ulyssa/iamb). Client developers should feel
confident to build upon it.
Development of the SDK has been primarily sponsored by Element though accepts
contributions from all.
## Bindings
The higher-level crates of the Matrix Rust SDK can be embedded in other
@@ -67,3 +84,7 @@ into your language of choice.
## License
[Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0)
[Matrix]: https://matrix.org/
[Rust]: https://www.rust-lang.org/
+24 -20
View File
@@ -1,29 +1,32 @@
[package]
name = "benchmarks"
description = "Matrix SDK benchmarks"
edition = "2021"
edition = "2024"
license = "Apache-2.0"
rust-version = { workspace = true }
rust-version.workspace = true
version = "1.0.0"
publish = false
[dependencies]
criterion = { version = "0.5.1", features = ["async", "async_tokio", "html_reports"] }
matrix-sdk-base = { workspace = true }
matrix-sdk-crypto = { workspace = true }
matrix-sdk-sqlite = { workspace = true, features = ["crypto-store"] }
matrix-sdk-test = { workspace = true }
matrix-sdk-ui = { workspace = true }
matrix-sdk = { workspace = true, features = ["native-tls", "e2e-encryption", "sqlite", "testing"] }
ruma = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tempfile = "3.3.0"
tokio = { workspace = true, default-features = false, features = ["rt-multi-thread"] }
wiremock = { workspace = true }
[package.metadata.release]
release = false
[target.'cfg(target_os = "linux")'.dependencies]
pprof = { version = "0.14.0", features = ["flamegraph", "criterion"] }
[features]
codspeed = []
[dependencies]
criterion = { version = "3.0.5", features = ["async", "async_tokio", "html_reports"], package = "codspeed-criterion-compat" }
matrix-sdk = { workspace = true, features = ["native-tls", "e2e-encryption", "sqlite", "testing"] }
matrix-sdk-base.workspace = true
matrix-sdk-crypto.workspace = true
matrix-sdk-sqlite = { workspace = true, features = ["crypto-store"] }
matrix-sdk-test.workspace = true
matrix-sdk-ui.workspace = true
ruma.workspace = true
serde.workspace = true
serde_json.workspace = true
tempfile.workspace = true
tokio = { workspace = true, default-features = false, features = ["rt-multi-thread"] }
wiremock.workspace = true
[[bench]]
name = "crypto_bench"
@@ -45,5 +48,6 @@ harness = false
name = "timeline"
harness = false
[package.metadata.release]
release = false
[[bench]]
name = "event_cache"
harness = false
+93 -69
View File
@@ -1,15 +1,16 @@
use std::{ops::Deref, sync::Arc};
use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use matrix_sdk_crypto::{EncryptionSettings, OlmMachine};
use matrix_sdk_sqlite::SqliteCryptoStore;
use matrix_sdk_test::ruma_response_from_json;
use ruma::{
DeviceId, OwnedUserId, TransactionId, UserId,
api::client::{
keys::{claim_keys, get_keys},
to_device::send_event_to_device::v3::Response as ToDeviceResponse,
},
device_id, room_id, user_id, DeviceId, OwnedUserId, TransactionId, UserId,
device_id, room_id, user_id,
};
use serde_json::Value;
use tokio::runtime::Builder;
@@ -58,10 +59,14 @@ pub fn keys_query(c: &mut Criterion) {
// Benchmark memory store.
group.bench_with_input(BenchmarkId::new("memory store", &name), &response, |b, response| {
b.to_async(&runtime)
.iter(|| async { machine.mark_request_as_sent(&txn_id, response).await.unwrap() })
});
group.bench_with_input(
BenchmarkId::new("Device keys query [memory]", &name),
&response,
|b, response| {
b.to_async(&runtime)
.iter(|| async { machine.mark_request_as_sent(&txn_id, response).await.unwrap() })
},
);
// Benchmark sqlite store.
@@ -71,10 +76,14 @@ pub fn keys_query(c: &mut Criterion) {
.block_on(OlmMachine::with_store(alice_id(), alice_device_id(), store, None))
.unwrap();
group.bench_with_input(BenchmarkId::new("sqlite store", &name), &response, |b, response| {
b.to_async(&runtime)
.iter(|| async { machine.mark_request_as_sent(&txn_id, response).await.unwrap() })
});
group.bench_with_input(
BenchmarkId::new("Device keys query [SQLite]", &name),
&response,
|b, response| {
b.to_async(&runtime)
.iter(|| async { machine.mark_request_as_sent(&txn_id, response).await.unwrap() })
},
);
{
let _guard = runtime.enter();
@@ -84,6 +93,8 @@ pub fn keys_query(c: &mut Criterion) {
group.finish()
}
/// This test panics on the CI, not sure why so we're disabling it for now.
#[cfg(not(feature = "codspeed"))]
pub fn keys_claiming(c: &mut Criterion) {
let runtime = Builder::new_multi_thread().build().expect("Can't create runtime");
@@ -99,49 +110,65 @@ pub fn keys_claiming(c: &mut Criterion) {
let name = format!("{count} one-time keys");
group.bench_with_input(BenchmarkId::new("memory store", &name), &response, |b, response| {
b.iter_batched(
|| {
let machine = runtime.block_on(OlmMachine::new(alice_id(), alice_device_id()));
runtime
.block_on(machine.mark_request_as_sent(&txn_id, &keys_query_response))
.unwrap();
(machine, &runtime, &txn_id)
},
move |(machine, runtime, txn_id)| {
runtime.block_on(async {
machine.mark_request_as_sent(txn_id, response).await.unwrap();
group.bench_with_input(
BenchmarkId::new("One-time keys claiming [memory]", &name),
&response,
|b, response| {
b.iter_batched(
|| {
let machine = runtime.block_on(OlmMachine::new(alice_id(), alice_device_id()));
runtime
.block_on(machine.mark_request_as_sent(&txn_id, &keys_query_response))
.unwrap();
(machine, &runtime, &txn_id)
},
move |(machine, runtime, txn_id)| {
runtime.block_on(async {
machine.mark_request_as_sent(txn_id, response).await.unwrap();
drop(machine);
})
},
criterion::BatchSize::SmallInput,
)
},
);
group.bench_with_input(
BenchmarkId::new("One-time keys claiming [SQLite]", &name),
&response,
|b, response| {
b.iter_batched(
|| {
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(
runtime.block_on(SqliteCryptoStore::open(dir.path(), None)).unwrap(),
);
let machine = runtime
.block_on(OlmMachine::with_store(
alice_id(),
alice_device_id(),
store,
None,
))
.unwrap();
runtime
.block_on(machine.mark_request_as_sent(&txn_id, &keys_query_response))
.unwrap();
(machine, &runtime, &txn_id)
},
move |(machine, runtime, txn_id)| {
runtime.block_on(async {
machine.mark_request_as_sent(txn_id, response).await.unwrap();
});
let _ = runtime.enter();
drop(machine);
})
},
BatchSize::SmallInput,
)
});
group.bench_with_input(BenchmarkId::new("sqlite store", &name), &response, |b, response| {
b.iter_batched(
|| {
let dir = tempfile::tempdir().unwrap();
let store =
Arc::new(runtime.block_on(SqliteCryptoStore::open(dir.path(), None)).unwrap());
let machine = runtime
.block_on(OlmMachine::with_store(alice_id(), alice_device_id(), store, None))
.unwrap();
runtime
.block_on(machine.mark_request_as_sent(&txn_id, &keys_query_response))
.unwrap();
(machine, &runtime, &txn_id)
},
move |(machine, runtime, txn_id)| {
runtime.block_on(async {
machine.mark_request_as_sent(txn_id, response).await.unwrap();
drop(machine)
})
},
BatchSize::SmallInput,
)
});
},
criterion::BatchSize::SmallInput,
)
},
);
group.finish()
}
@@ -169,7 +196,7 @@ pub fn room_key_sharing(c: &mut Criterion) {
// Benchmark memory store.
group.bench_function(BenchmarkId::new("memory store", &name), |b| {
group.bench_function(BenchmarkId::new("Room key sharing [memory]", &name), |b| {
b.to_async(&runtime).iter(|| async {
let requests = machine
.share_room_key(
@@ -201,7 +228,7 @@ pub fn room_key_sharing(c: &mut Criterion) {
runtime.block_on(machine.mark_request_as_sent(&txn_id, &keys_query_response)).unwrap();
runtime.block_on(machine.mark_request_as_sent(&txn_id, &response)).unwrap();
group.bench_function(BenchmarkId::new("sqlite store", &name), |b| {
group.bench_function(BenchmarkId::new("Room key sharing [SQLite]", &name), |b| {
b.to_async(&runtime).iter(|| async {
let requests = machine
.share_room_key(
@@ -249,7 +276,7 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) {
// Benchmark memory store.
group.bench_function(BenchmarkId::new("memory store", &name), |b| {
group.bench_function(BenchmarkId::new("Devices collecting [memory]", &name), |b| {
b.to_async(&runtime).iter_with_large_drop(|| async {
machine.get_missing_sessions(users.iter().map(Deref::deref)).await.unwrap()
})
@@ -266,7 +293,7 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) {
runtime.block_on(machine.mark_request_as_sent(&txn_id, &response)).unwrap();
group.bench_function(BenchmarkId::new("sqlite store", &name), |b| {
group.bench_function(BenchmarkId::new("Devices collecting [SQLite]", &name), |b| {
b.to_async(&runtime).iter(|| async {
machine.get_missing_sessions(users.iter().map(Deref::deref)).await.unwrap()
})
@@ -280,21 +307,18 @@ pub fn devices_missing_sessions_collecting(c: &mut Criterion) {
group.finish()
}
fn criterion() -> Criterion {
#[cfg(target_os = "linux")]
let criterion = Criterion::default().with_profiler(pprof::criterion::PProfProfiler::new(
100,
pprof::criterion::Output::Flamegraph(None),
));
#[cfg(not(target_os = "linux"))]
let criterion = Criterion::default();
criterion
}
#[cfg(not(feature = "codspeed"))]
criterion_group! {
name = benches;
config = criterion();
config = Criterion::default();
targets = keys_query, keys_claiming, room_key_sharing, devices_missing_sessions_collecting,
}
#[cfg(feature = "codspeed")]
criterion_group! {
name = benches;
config = Criterion::default();
targets = keys_query, room_key_sharing, devices_missing_sessions_collecting,
}
criterion_main!(benches);
+353
View File
@@ -0,0 +1,353 @@
use std::{pin::Pin, sync::Arc};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use matrix_sdk::{
RoomInfo, RoomState, SqliteEventCacheStore, StateStore,
store::StoreConfig,
sync::{JoinedRoomUpdate, RoomUpdates},
test_utils::client::MockClientBuilder,
};
use matrix_sdk_base::event_cache::store::{DynEventCacheStore, IntoEventCacheStore, MemoryStore};
use matrix_sdk_test::{ALICE, event_factory::EventFactory};
use ruma::{
EventId, RoomId, event_id,
events::{relation::RelationType, room::message::RoomMessageEventContentWithoutRelation},
room_id,
};
use tempfile::tempdir;
use tokio::runtime::Builder;
type StoreBuilder = Box<dyn Fn() -> Pin<Box<dyn Future<Output = Arc<DynEventCacheStore>>>>>;
fn handle_room_updates(c: &mut Criterion) {
// Create a new asynchronous runtime.
let runtime = Builder::new_multi_thread()
.enable_time()
.enable_io()
.build()
.expect("Failed to create an asynchronous runtime");
let mut group = c.benchmark_group("Event cache room updates");
group.sample_size(10);
const NUM_EVENTS: usize = 1000;
for num_rooms in [1, 10, 100] {
// Add some joined rooms, each with NUM_EVENTS in it, to the sync response.
let mut room_updates = RoomUpdates::default();
let mut changes = matrix_sdk::StateChanges::default();
for i in 0..num_rooms {
let room_id = RoomId::parse(format!("!room{i}:example.com")).unwrap();
let event_factory = EventFactory::new().room(&room_id).sender(&ALICE);
let mut joined_room_update = JoinedRoomUpdate::default();
for j in 0..NUM_EVENTS {
let event_id = EventId::parse(format!("$ev{i}_{j}")).unwrap();
let event =
event_factory.text_msg(format!("Message {j}")).event_id(&event_id).into();
joined_room_update.timeline.events.push(event);
}
room_updates.joined.insert(room_id.clone(), joined_room_update);
changes.add_room(RoomInfo::new(&room_id, RoomState::Joined));
}
// Declare new stores for this set of events.
let temp_dir = Arc::new(tempdir().unwrap());
let store_builders: Vec<(_, StoreBuilder)> = vec![
(
"memory",
Box::new(|| Box::pin(async { MemoryStore::default().into_event_cache_store() })),
),
(
"SQLite",
Box::new(move || {
let temp_dir = temp_dir.clone();
Box::pin(async move {
// Remove all the files in the temp_dir, to reset the event cache state.
for entry in temp_dir.path().read_dir().unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
// If it's a directory, remove it recursively.
std::fs::remove_dir_all(path).unwrap();
} else {
std::fs::remove_file(path).unwrap();
}
}
// Recreate a new store.
SqliteEventCacheStore::open(temp_dir.path().join("bench"), None)
.await
.unwrap()
.into_event_cache_store()
})
}),
),
];
let state_store = runtime.block_on(async {
let state_store = matrix_sdk::MemoryStore::new();
state_store.save_changes(&changes).await.unwrap();
Arc::new(state_store)
});
for (store_name, store_builder) in &store_builders {
let client = runtime.block_on(async {
let event_cache_store = store_builder().await;
let client = MockClientBuilder::new(None)
.on_builder(|builder| {
builder.store_config(
StoreConfig::new("cross-process-store-locks-holder-name".to_owned())
.state_store(state_store.clone())
.event_cache_store(event_cache_store.clone()),
)
})
.build()
.await;
client.event_cache().subscribe().unwrap();
client
});
// Define a state store with all rooms known in it.
// Define the throughput.
group.throughput(Throughput::Elements(num_rooms));
// Bench the handling of room updates.
group.bench_function(
BenchmarkId::new(
format!("Event cache room updates[{store_name}]"),
format!("room count: {num_rooms}"),
),
|bencher| {
bencher.to_async(&runtime).iter(
// The routine itself.
|| {
let room_updates = room_updates.clone();
let client = client.clone();
async move {
client.event_cache().clear_all_rooms().await.unwrap();
client
.event_cache()
.handle_room_updates(room_updates.clone())
.await
.unwrap();
}
},
)
},
);
}
}
group.finish()
}
fn find_event_relations(c: &mut Criterion) {
// Number of other events to saturate the DB, but that will not be affected by
// the benchmark. A small multiple of this number will be added.
// When running locally, run with more events than in Codespeed CI.
#[cfg(feature = "codspeed")]
const NUM_OTHER_EVENTS: usize = 100;
#[cfg(not(feature = "codspeed"))]
const NUM_OTHER_EVENTS: usize = 1000;
// Create a new asynchronous runtime.
let runtime = Builder::new_multi_thread()
.enable_time()
.enable_io()
.build()
.expect("Failed to create an asynchronous runtime");
let mut group = c.benchmark_group("Event cache room updates");
group.sample_size(10);
let room_id = room_id!("!room:ben.ch");
let other_room_id = room_id!("!other-room:ben.ch");
// Make the state store aware of the room, so that `client.get_room()` works
// with it.
let mut changes = matrix_sdk::StateChanges::default();
changes.add_room(RoomInfo::new(room_id, RoomState::Joined));
changes.add_room(RoomInfo::new(other_room_id, RoomState::Joined));
let state_store = runtime.block_on(async {
let state_store = matrix_sdk::MemoryStore::new();
state_store.save_changes(&changes).await.unwrap();
Arc::new(state_store)
});
for num_related_events in [10, 100, 1000] {
// Prefill the event cache store with one event and N related events.
let mut room_updates = RoomUpdates::default();
let event_factory = EventFactory::new().room(room_id).sender(&ALICE);
let mut joined_room_update = JoinedRoomUpdate::default();
// Add the target event.
let target_event_id = event_id!("$target");
let target_event =
event_factory.text_msg("hello world").event_id(target_event_id).into_event();
joined_room_update.timeline.events.push(target_event);
// Add the numerous edits.
for i in 0..num_related_events {
let event_id = EventId::parse(format!("$edit{i}")).unwrap();
let event = event_factory
.text_msg(format!("* edit {i}"))
.edit(
target_event_id,
RoomMessageEventContentWithoutRelation::text_plain(format!("edit {i}")),
)
.event_id(&event_id)
.into();
joined_room_update.timeline.events.push(event);
}
// Add other events, in the same room, without a relation.
for i in 0..NUM_OTHER_EVENTS {
let event_id = EventId::parse(format!("$msg{i}")).unwrap();
let event =
event_factory.text_msg(format!("unrelated message {i}")).event_id(&event_id).into();
joined_room_update.timeline.events.push(event);
}
// Add other events, in the same room, related to other events.
let other_target_event_id = event_id!("$other_target");
let other_target_event =
event_factory.text_msg("hello world").event_id(other_target_event_id).into_event();
joined_room_update.timeline.events.push(other_target_event);
for i in 0..NUM_OTHER_EVENTS {
let event_id = EventId::parse(format!("$unrelated{i}")).unwrap();
let event =
event_factory.reaction(other_target_event_id, "👍").event_id(&event_id).into();
joined_room_update.timeline.events.push(event);
}
room_updates.joined.insert(room_id.to_owned(), joined_room_update);
// Add other events, in another room.
let mut other_joined_room_update = JoinedRoomUpdate::default();
let event_factory = event_factory.room(other_room_id);
for i in 0..NUM_OTHER_EVENTS {
let event_id = EventId::parse(format!("$other_room{i}")).unwrap();
let event = event_factory.text_msg(format!("hi {i}")).event_id(&event_id).into();
other_joined_room_update.timeline.events.push(event);
}
room_updates.joined.insert(other_room_id.to_owned(), other_joined_room_update);
changes.add_room(RoomInfo::new(room_id, RoomState::Joined));
// Declare new stores for this set of events.
let temp_dir = Arc::new(tempdir().unwrap());
let stores = vec![
("memory", MemoryStore::default().into_event_cache_store()),
(
"SQLite",
runtime.block_on(async {
SqliteEventCacheStore::open(temp_dir.path().join("bench"), None)
.await
.unwrap()
.into_event_cache_store()
}),
),
];
for (store_name, event_cache_store) in stores {
let (client, room_event_cache, _drop_handles) = runtime.block_on(async {
let client = MockClientBuilder::new(None)
.on_builder(|builder| {
builder.store_config(
StoreConfig::new("cross-process-store-locks-holder-name".to_owned())
.state_store(state_store.clone())
.event_cache_store(event_cache_store),
)
})
.build()
.await;
client.event_cache().subscribe().unwrap();
// Sync the updates before starting the benchmark.
let mut update_recv = client.event_cache().subscribe_to_room_generic_updates();
client.event_cache().handle_room_updates(room_updates.clone()).await.unwrap();
// Wait for the event cache to notify us of the room updates.
let update = update_recv.recv().await.unwrap();
assert!(update.room_id == room_id || update.room_id == other_room_id);
let update = update_recv.recv().await.unwrap();
assert!(update.room_id == room_id || update.room_id == other_room_id);
let room = client.get_room(room_id).unwrap();
let room_event_cache = room.event_cache().await.unwrap();
(client, room_event_cache.0, room_event_cache.1)
});
// Define the throughput.
group.throughput(Throughput::Elements(num_related_events));
for filter in [None, Some(vec![RelationType::Replacement])] {
group.bench_function(
BenchmarkId::new(
format!("Event cache find_event_relations[{store_name}]"),
format!(
"{num_related_events} events, {} filter",
if filter.is_some() { "edits" } else { "#no" },
),
),
|bencher| {
bencher.to_async(&runtime).iter_batched(
// The setup.
|| (room_event_cache.clone(), filter.clone()),
// The routine itself.
|(room_event_cache, filter)| async move {
let (target, relations) = room_event_cache
.find_event_with_relations(target_event_id, filter)
.await
.unwrap();
assert_eq!(target.event_id().as_deref().unwrap(), target_event_id);
assert_eq!(relations.len(), num_related_events as usize);
},
criterion::BatchSize::PerIteration,
)
},
);
}
{
let _guard = runtime.enter();
drop(room_event_cache);
drop(client);
drop(_drop_handles);
}
}
}
{
let _guard = runtime.enter();
drop(state_store);
}
group.finish()
}
criterion_group! {
name = event_cache;
config = Criterion::default();
targets = handle_room_updates, find_event_relations,
}
criterion_main!(event_cache);
+65 -47
View File
@@ -1,16 +1,16 @@
use std::{sync::Arc, time::Duration};
use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput};
use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use matrix_sdk::{
linked_chunk::{lazy_loader, LinkedChunk, Update},
SqliteEventCacheStore,
linked_chunk::{LinkedChunk, LinkedChunkId, Update, lazy_loader},
};
use matrix_sdk_base::event_cache::{
store::{DynEventCacheStore, IntoEventCacheStore, MemoryStore, DEFAULT_CHUNK_CAPACITY},
Event, Gap,
store::{DEFAULT_CHUNK_CAPACITY, DynEventCacheStore, IntoEventCacheStore, MemoryStore},
};
use matrix_sdk_test::{event_factory::EventFactory, ALICE};
use ruma::{room_id, EventId};
use matrix_sdk_test::{ALICE, event_factory::EventFactory};
use ruma::{EventId, room_id};
use tempfile::tempdir;
use tokio::runtime::Builder;
@@ -20,6 +20,11 @@ enum Operation {
PushGapBack(Gap),
}
#[cfg(not(feature = "codspeed"))]
const NUMBER_OF_EVENTS: &[u64] = &[10, 100, 1000, 10_000, 100_000];
#[cfg(feature = "codspeed")]
const NUMBER_OF_EVENTS: &[u64] = &[10, 100, 1000];
fn writing(c: &mut Criterion) {
// Create a new asynchronous runtime.
let runtime = Builder::new_multi_thread()
@@ -29,12 +34,13 @@ fn writing(c: &mut Criterion) {
.expect("Failed to create an asynchronous runtime");
let room_id = room_id!("!foo:bar.baz");
let linked_chunk_id = LinkedChunkId::Room(room_id);
let event_factory = EventFactory::new().room(room_id).sender(&ALICE);
let mut group = c.benchmark_group("writing");
let mut group = c.benchmark_group("Linked chunk writing");
group.sample_size(10).measurement_time(Duration::from_secs(30));
for number_of_events in [10, 100, 1000, 10_000, 100_000] {
for &number_of_events in NUMBER_OF_EVENTS {
let sqlite_temp_dir = tempdir().unwrap();
// Declare new stores for this set of events.
@@ -95,7 +101,7 @@ fn writing(c: &mut Criterion) {
// Get a bencher.
group.bench_with_input(
BenchmarkId::new(store_name, number_of_events),
BenchmarkId::new(format!("Linked chunk writing [{store_name}]"), number_of_events),
&operations,
|bencher, operations| {
// Bench the routine.
@@ -115,9 +121,9 @@ fn writing(c: &mut Criterion) {
if let Some(store) = &store {
let updates = linked_chunk.updates().unwrap().take();
store.handle_linked_chunk_updates(room_id, updates).await.unwrap();
store.handle_linked_chunk_updates(linked_chunk_id, updates).await.unwrap();
// Empty the store.
store.handle_linked_chunk_updates(room_id, vec![Update::Clear]).await.unwrap();
store.handle_linked_chunk_updates(linked_chunk_id, vec![Update::Clear]).await.unwrap();
}
},
@@ -145,12 +151,13 @@ fn reading(c: &mut Criterion) {
.expect("Failed to create an asynchronous runtime");
let room_id = room_id!("!foo:bar.baz");
let linked_chunk_id = LinkedChunkId::Room(room_id);
let event_factory = EventFactory::new().room(room_id).sender(&ALICE);
let mut group = c.benchmark_group("reading");
let mut group = c.benchmark_group("Linked chunk reading");
group.sample_size(10);
for num_events in [10, 100, 1000, 10_000, 100_000] {
for &num_events in NUMBER_OF_EVENTS {
let sqlite_temp_dir = tempdir().unwrap();
// Declare new stores for this set of events.
@@ -185,45 +192,68 @@ fn reading(c: &mut Criterion) {
while events.peek().is_some() {
let events_chunk = events.by_ref().take(80).collect::<Vec<_>>();
if events_chunk.is_empty() {
break;
}
lc.push_items_back(events_chunk);
lc.push_gap_back(Gap { prev_token: format!("gap{num_gaps}") });
num_gaps += 1;
}
// Now persist the updates to recreate this full linked chunk.
let updates = lc.updates().unwrap().take();
runtime.block_on(store.handle_linked_chunk_updates(room_id, updates)).unwrap();
runtime
.block_on(store.handle_linked_chunk_updates(linked_chunk_id, updates))
.unwrap();
}
// Define the throughput.
group.throughput(Throughput::Elements(num_events));
// Get a bencher.
group.bench_function(BenchmarkId::new(store_name, num_events), |bencher| {
// Bench the routine.
bencher.to_async(&runtime).iter(|| async {
// Load the last chunk first,
let (last_chunk, chunk_id_gen) = store.load_last_chunk(room_id).await.unwrap();
// Bench the lazy loader.
group.bench_function(
BenchmarkId::new(format!("Linked chunk lazy loader[{store_name}]"), num_events),
|bencher| {
// Bench the routine.
bencher.to_async(&runtime).iter(|| async {
// Load the last chunk first,
let (last_chunk, chunk_id_gen) =
store.load_last_chunk(linked_chunk_id).await.unwrap();
let mut lc =
lazy_loader::from_last_chunk::<128, _, _>(last_chunk, chunk_id_gen)
.expect("no error when reconstructing the linked chunk")
.expect("there is a linked chunk in the store");
let mut lc =
lazy_loader::from_last_chunk::<128, _, _>(last_chunk, chunk_id_gen)
.expect("no error when reconstructing the linked chunk")
.expect("there is a linked chunk in the store");
// Then load until the start of the linked chunk.
let mut cur_chunk_id = lc.chunks().next().unwrap().identifier();
while let Some(prev) =
store.load_previous_chunk(room_id, cur_chunk_id).await.unwrap()
{
cur_chunk_id = prev.identifier;
lazy_loader::insert_new_first_chunk(&mut lc, prev)
.expect("no error when linking the previous lazy-loaded chunk");
}
})
});
// Then load until the start of the linked chunk.
let mut cur_chunk_id = lc.chunks().next().unwrap().identifier();
while let Some(prev) =
store.load_previous_chunk(linked_chunk_id, cur_chunk_id).await.unwrap()
{
cur_chunk_id = prev.identifier;
lazy_loader::insert_new_first_chunk(&mut lc, prev)
.expect("no error when linking the previous lazy-loaded chunk");
}
})
},
);
// Bench the metadata loader.
group.bench_function(
BenchmarkId::new(format!("Linked chunk metadata loader[{store_name}]"), num_events),
|bencher| {
// Bench the routine.
bencher.to_async(&runtime).iter(|| async {
let _metadata = store
.load_all_chunks_metadata(linked_chunk_id)
.await
.expect("metadata must load");
})
},
);
{
let _guard = runtime.enter();
@@ -235,21 +265,9 @@ fn reading(c: &mut Criterion) {
group.finish()
}
fn criterion() -> Criterion {
#[cfg(target_os = "linux")]
let criterion = Criterion::default().with_profiler(pprof::criterion::PProfProfiler::new(
100,
pprof::criterion::Output::Flamegraph(None),
));
#[cfg(not(target_os = "linux"))]
let criterion = Criterion::default();
criterion
}
criterion_group! {
name = event_cache;
config = criterion();
config = Criterion::default();
targets = writing, reading,
}
+15 -27
View File
@@ -1,20 +1,22 @@
use std::time::Duration;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use matrix_sdk::{store::RoomLoadSettings, test_utils::mocks::MatrixMockServer};
use matrix_sdk_base::{
store::StoreConfig, BaseClient, RoomInfo, RoomState, SessionMeta, StateChanges, StateStore,
BaseClient, RoomInfo, RoomState, SessionMeta, StateChanges, StateStore, ThreadingSupport,
store::StoreConfig,
};
use matrix_sdk_sqlite::SqliteStateStore;
use matrix_sdk_test::{event_factory::EventFactory, JoinedRoomBuilder, StateTestEvent};
use matrix_sdk_ui::{timeline::TimelineFocus, Timeline};
use matrix_sdk_test::{JoinedRoomBuilder, StateTestEvent, event_factory::EventFactory};
use matrix_sdk_ui::timeline::{TimelineBuilder, TimelineFocus};
use ruma::{
EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId,
api::client::membership::get_member_events,
device_id,
events::room::member::{MembershipState, RoomMemberEvent},
mxc_uri, owned_room_id, owned_user_id,
serde::Raw,
user_id, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId,
user_id,
};
use serde_json::json;
use tokio::runtime::Builder;
@@ -29,7 +31,7 @@ pub fn receive_all_members_benchmark(c: &mut Criterion) {
let f = EventFactory::new().room(&room_id);
let mut member_events: Vec<Raw<RoomMemberEvent>> = Vec::with_capacity(MEMBERS_IN_ROOM);
for i in 0..MEMBERS_IN_ROOM {
let user_id = OwnedUserId::try_from(format!("@user_{}:matrix.org", i)).unwrap();
let user_id = OwnedUserId::try_from(format!("@user_{i}:matrix.org")).unwrap();
let event = f
.member(&user_id)
.membership(MembershipState::Join)
@@ -58,6 +60,7 @@ pub fn receive_all_members_benchmark(c: &mut Criterion) {
let base_client = BaseClient::new(
StoreConfig::new("cross-process-store-locks-holder-name".to_owned())
.state_store(sqlite_store),
ThreadingSupport::Disabled,
);
runtime
@@ -82,7 +85,7 @@ pub fn receive_all_members_benchmark(c: &mut Criterion) {
group.throughput(Throughput::Elements(count as u64));
group.sample_size(50);
group.bench_function(BenchmarkId::new("receive_members", name), |b| {
group.bench_function(BenchmarkId::new("Handle /members request [SQLite]", name), |b| {
b.to_async(&runtime).iter(|| async {
base_client.receive_all_members(&room_id, &request, &response).await.unwrap();
});
@@ -162,11 +165,11 @@ pub fn load_pinned_events_benchmark(c: &mut Criterion) {
let count = PINNED_EVENTS_COUNT;
let name = format!("{count} pinned events");
let mut group = c.benchmark_group("Test");
let mut group = c.benchmark_group("Load pinned events");
group.throughput(Throughput::Elements(count as u64));
group.sample_size(10);
group.bench_function(BenchmarkId::new("load_pinned_events", name), |b| {
group.bench_function(BenchmarkId::new("Load pinned events [memory]", name), |b| {
b.to_async(&runtime).iter(|| async {
let pinned_event_ids = room.pinned_event_ids().unwrap_or_default();
assert!(!pinned_event_ids.is_empty());
@@ -178,11 +181,11 @@ pub fn load_pinned_events_benchmark(c: &mut Criterion) {
.lock()
.await
.unwrap()
.clear_all_rooms_chunks()
.clear_all_linked_chunks()
.await
.unwrap();
let timeline = Timeline::builder(&room)
let timeline = TimelineBuilder::new(&room)
.with_focus(TimelineFocus::PinnedEvents {
max_events_to_load: 100,
max_concurrent_requests: 10,
@@ -205,24 +208,9 @@ pub fn load_pinned_events_benchmark(c: &mut Criterion) {
group.finish();
}
fn criterion() -> Criterion {
#[cfg(target_os = "linux")]
{
Criterion::default().with_profiler(pprof::criterion::PProfProfiler::new(
100,
pprof::criterion::Output::Flamegraph(None),
))
}
#[cfg(not(target_os = "linux"))]
{
Criterion::default()
}
}
criterion_group! {
name = room;
config = criterion();
config = Criterion::default();
targets = receive_all_members_benchmark, load_pinned_events_benchmark,
}
criterion_main!(room);
+9 -24
View File
@@ -1,28 +1,15 @@
use std::sync::Arc;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use matrix_sdk::{
authentication::matrix::MatrixSession, config::StoreConfig, Client, RoomInfo, RoomState,
SessionTokens, StateChanges,
Client, RoomInfo, RoomState, SessionTokens, StateChanges,
authentication::matrix::MatrixSession, config::StoreConfig,
};
use matrix_sdk_base::{store::MemoryStore, SessionMeta, StateStore as _};
use matrix_sdk_base::{SessionMeta, StateStore as _, store::MemoryStore};
use matrix_sdk_sqlite::SqliteStateStore;
use ruma::{device_id, user_id, RoomId};
use ruma::{RoomId, device_id, user_id};
use tokio::runtime::Builder;
fn criterion() -> Criterion {
#[cfg(target_os = "linux")]
let criterion = Criterion::default().with_profiler(pprof::criterion::PProfProfiler::new(
100,
pprof::criterion::Output::Flamegraph(None),
));
#[cfg(not(target_os = "linux"))]
let criterion = Criterion::default();
criterion
}
/// Number of joined rooms in the benchmark.
const NUM_JOINED_ROOMS: usize = 10000;
@@ -30,7 +17,7 @@ const NUM_JOINED_ROOMS: usize = 10000;
const NUM_STRIPPED_JOINED_ROOMS: usize = 10000;
pub fn restore_session(c: &mut Criterion) {
let runtime = Builder::new_multi_thread().build().expect("Can't create runtime");
let runtime = Builder::new_multi_thread().enable_time().build().expect("Can't create runtime");
// Create a fake list of changes, and a session to recover from.
let mut changes = StateChanges::default();
@@ -58,13 +45,11 @@ pub fn restore_session(c: &mut Criterion) {
let mut group = c.benchmark_group("Client reload");
group.throughput(Throughput::Elements(100));
const NAME: &str = "restore a session";
// Memory
let mem_store = Arc::new(MemoryStore::new());
runtime.block_on(mem_store.save_changes(&changes)).expect("initial filling of mem failed");
group.bench_with_input(BenchmarkId::new("memory store", NAME), &mem_store, |b, store| {
group.bench_with_input("Restore session [memory store]", &mem_store, |b, store| {
b.to_async(&runtime).iter(|| async {
let client = Client::builder()
.homeserver_url("https://matrix.example.com")
@@ -92,7 +77,7 @@ pub fn restore_session(c: &mut Criterion) {
.expect("initial filling of sqlite failed");
group.bench_with_input(
BenchmarkId::new(format!("sqlite store {encrypted_suffix}"), NAME),
BenchmarkId::new("Restore session [SQLite]", encrypted_suffix),
&sqlite_store,
|b, store| {
b.to_async(&runtime).iter(|| async {
@@ -124,7 +109,7 @@ pub fn restore_session(c: &mut Criterion) {
criterion_group! {
name = benches;
config = criterion();
config = Criterion::default();
targets = restore_session
}
criterion_main!(benches);
+9 -24
View File
@@ -1,10 +1,10 @@
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use matrix_sdk::test_utils::mocks::MatrixMockServer;
use matrix_sdk_test::{event_factory::EventFactory, JoinedRoomBuilder, StateTestEvent};
use matrix_sdk_ui::Timeline;
use matrix_sdk_test::{JoinedRoomBuilder, StateTestEvent, event_factory::EventFactory};
use matrix_sdk_ui::timeline::TimelineBuilder;
use ruma::{
events::room::message::RoomMessageEventContentWithoutRelation, owned_room_id, owned_user_id,
EventId,
EventId, events::room::message::RoomMessageEventContentWithoutRelation, owned_room_id,
owned_user_id,
};
use tokio::runtime::Builder;
@@ -94,15 +94,15 @@ pub fn create_timeline_with_initial_events(c: &mut Criterion) {
room
});
let mut group = c.benchmark_group("Test");
let mut group = c.benchmark_group("Create a timeline");
group.throughput(Throughput::Elements(NUM_EVENTS as _));
group.sample_size(10);
group.bench_function(
BenchmarkId::new("create_timeline_with_initial_events", format!("{NUM_EVENTS} events")),
BenchmarkId::new("Create a timeline with initial events", format!("{NUM_EVENTS} events")),
|b| {
b.to_async(&runtime).iter(|| async {
let timeline = Timeline::builder(&room)
let timeline = TimelineBuilder::new(&room)
.track_read_marker_and_receipts()
.build()
.await
@@ -117,24 +117,9 @@ pub fn create_timeline_with_initial_events(c: &mut Criterion) {
group.finish();
}
fn criterion() -> Criterion {
#[cfg(target_os = "linux")]
{
Criterion::default().with_profiler(pprof::criterion::PProfProfiler::new(
100,
pprof::criterion::Output::Flamegraph(None),
))
}
#[cfg(not(target_os = "linux"))]
{
Criterion::default()
}
}
criterion_group! {
name = room;
config = criterion();
config = Criterion::default();
targets = create_timeline_with_initial_events
}
criterion_main!(room);
+27 -21
View File
@@ -3,12 +3,15 @@ name = "matrix-sdk-crypto-ffi"
version = "0.1.0"
authors = ["Damir Jelić <poljar@termina.org.uk>"]
edition = "2021"
rust-version = { workspace = true }
rust-version.workspace = true
description = "Uniffi based bindings for the Rust SDK crypto crate"
repository = "https://github.com/matrix-org/matrix-rust-sdk"
license = "Apache-2.0"
publish = false
[package.metadata.release]
release = false
[lib]
crate-type = ["cdylib", "staticlib"]
@@ -20,24 +23,30 @@ path = "uniffi-bindgen.rs"
default = ["bundled-sqlite"]
bundled-sqlite = ["matrix-sdk-sqlite/bundled"]
# Enable experimental support for encrypting state events; see
# https://github.com/matrix-org/matrix-rust-sdk/issues/5397.
experimental-encrypted-state-events = [
"matrix-sdk-crypto/experimental-encrypted-state-events",
]
[dependencies]
anyhow = { workspace = true }
futures-util = { workspace = true }
hmac = "0.12.1"
http = { workspace = true }
anyhow.workspace = true
futures-util.workspace = true
hmac.workspace = true
http.workspace = true
matrix-sdk-common = { workspace = true, features = ["uniffi"] }
matrix-sdk-ffi-macros = { workspace = true }
pbkdf2 = "0.12.2"
rand = { workspace = true }
ruma = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
thiserror = { workspace = true }
matrix-sdk-ffi-macros.workspace = true
pbkdf2.workspace = true
rand.workspace = true
ruma.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
tracing-subscriber = { workspace = true, features = ["env-filter"] }
# keep in sync with uniffi dependency in matrix-sdk-ffi, and uniffi_bindgen in ffi CI job
uniffi = { workspace = true, features = ["cli"] }
vodozemac = { workspace = true }
vodozemac.workspace = true
zeroize = { workspace = true, features = ["zeroize_derive"] }
[dependencies.js_int]
@@ -53,20 +62,17 @@ workspace = true
features = ["crypto-store"]
[dependencies.tokio]
version = "1.33.0"
workspace = true
default-features = false
features = ["rt-multi-thread"]
[build-dependencies]
vergen = { version = "8.2.5", features = ["build", "git", "gitcl"] }
uniffi = { workspace = true, features = ["build"] }
vergen-gitcl = { workspace = true, features = ["build"] }
[dev-dependencies]
tempfile = "3.8.0"
assert_matches2 = { workspace = true }
assert_matches2.workspace = true
tempfile.workspace = true
[lints]
workspace = true
[package.metadata.release]
release = false
+3 -2
View File
@@ -5,7 +5,7 @@ use std::{
process::Command,
};
use vergen::EmitBuilder;
use vergen_gitcl::{Emitter, GitclBuilder};
/// Adds a temporary workaround for an issue with the Rust compiler and Android
/// in x86_64 devices: https://github.com/rust-lang/rust/issues/109717.
@@ -59,7 +59,8 @@ fn get_clang_major_version(clang_path: &Path) -> String {
fn main() -> Result<(), Box<dyn Error>> {
setup_x86_64_android_workaround();
EmitBuilder::builder().git_sha(true).git_describe(true, false, None).emit()?;
let git_config = GitclBuilder::default().sha(true).describe(true, false, None).build()?;
Emitter::default().add_instructions(&git_config)?.emit()?;
Ok(())
}
@@ -3,7 +3,7 @@ use std::{collections::HashMap, iter, ops::DerefMut, sync::Arc};
use hmac::Hmac;
use matrix_sdk_crypto::{
backups::DecryptionError,
store::{BackupDecryptionKey, CryptoStoreError as InnerStoreError},
store::{types::BackupDecryptionKey, CryptoStoreError as InnerStoreError},
};
use pbkdf2::pbkdf2;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
@@ -1,15 +1,16 @@
use std::{mem::ManuallyDrop, sync::Arc};
use matrix_sdk_common::executor::Handle;
use matrix_sdk_crypto::{
dehydrated_devices::{
DehydratedDevice as InnerDehydratedDevice, DehydratedDevices as InnerDehydratedDevices,
RehydratedDevice as InnerRehydratedDevice,
},
store::DehydratedDeviceKey as InnerDehydratedDeviceKey,
store::types::DehydratedDeviceKey as InnerDehydratedDeviceKey,
DecryptionSettings,
};
use ruma::{api::client::dehydrated_device, events::AnyToDeviceEvent, serde::Raw, OwnedDeviceId};
use serde_json::json;
use tokio::runtime::Handle;
use crate::{CryptoStoreError, DehydratedDeviceKey};
@@ -154,9 +155,13 @@ impl Drop for RehydratedDevice {
#[matrix_sdk_ffi_macros::export]
impl RehydratedDevice {
pub fn receive_events(&self, events: String) -> Result<(), crate::CryptoStoreError> {
pub fn receive_events(
&self,
events: String,
decryption_settings: &DecryptionSettings,
) -> Result<(), crate::CryptoStoreError> {
let events: Vec<Raw<AnyToDeviceEvent>> = serde_json::from_str(&events)?;
self.runtime.block_on(self.inner.receive_events(events))?;
self.runtime.block_on(self.inner.receive_events(events, decryption_settings))?;
Ok(())
}
+3 -3
View File
@@ -78,10 +78,10 @@ pub enum DecryptionError {
impl From<MegolmError> for DecryptionError {
fn from(value: MegolmError) -> Self {
match value {
match &value {
MegolmError::MissingRoomKey(withheld_code) => Self::MissingRoomKey {
error: "Withheld Inbound group session".to_owned(),
withheld_code: withheld_code.map(|w| w.as_str().to_owned()),
error: value.to_string(),
withheld_code: withheld_code.as_ref().map(|w| w.as_str().to_owned()),
},
_ => Self::Megolm { error: value.to_string() },
}
+29 -8
View File
@@ -37,8 +37,11 @@ use matrix_sdk_common::deserialized_responses::{ShieldState as RustShieldState,
use matrix_sdk_crypto::{
olm::{IdentityKeys, InboundGroupSession, SenderData, Session},
store::{
Changes, CryptoStore, DehydratedDeviceKey as InnerDehydratedDeviceKey, PendingChanges,
RoomSettings as RustRoomSettings,
types::{
Changes, DehydratedDeviceKey as InnerDehydratedDeviceKey, PendingChanges,
RoomSettings as RustRoomSettings,
},
CryptoStore,
},
types::{
DeviceKey, DeviceKeys, EventEncryptionAlgorithm as RustEventEncryptionAlgorithm, SigningKey,
@@ -221,7 +224,7 @@ async fn migrate_data(
passphrase: Option<String>,
progress_listener: Box<dyn ProgressListener>,
) -> anyhow::Result<()> {
use matrix_sdk_crypto::{olm::PrivateCrossSigningIdentity, store::BackupDecryptionKey};
use matrix_sdk_crypto::{olm::PrivateCrossSigningIdentity, store::types::BackupDecryptionKey};
use vodozemac::olm::Account;
use zeroize::Zeroize;
@@ -662,6 +665,9 @@ impl From<HistoryVisibility> for RustHistoryVisibility {
pub struct EncryptionSettings {
/// The encryption algorithm that should be used in the room.
pub algorithm: EventEncryptionAlgorithm,
/// Whether state event encryption is enabled.
#[cfg(feature = "experimental-encrypted-state-events")]
pub encrypt_state_events: bool,
/// How long can the room key be used before it should be rotated. Time in
/// seconds.
pub rotation_period: u64,
@@ -691,6 +697,8 @@ impl From<EncryptionSettings> for RustEncryptionSettings {
RustEncryptionSettings {
algorithm: v.algorithm.into(),
#[cfg(feature = "experimental-encrypted-state-events")]
encrypt_state_events: false,
rotation_period: Duration::from_secs(v.rotation_period),
rotation_period_msgs: v.rotation_period_msgs,
history_visibility: v.history_visibility.into(),
@@ -818,10 +826,10 @@ impl BackupKeys {
}
}
impl TryFrom<matrix_sdk_crypto::store::BackupKeys> for BackupKeys {
impl TryFrom<matrix_sdk_crypto::store::types::BackupKeys> for BackupKeys {
type Error = ();
fn try_from(keys: matrix_sdk_crypto::store::BackupKeys) -> Result<Self, Self::Error> {
fn try_from(keys: matrix_sdk_crypto::store::types::BackupKeys) -> Result<Self, Self::Error> {
Ok(Self {
recovery_key: BackupRecoveryKey {
inner: keys.decryption_key.ok_or(())?,
@@ -866,8 +874,8 @@ impl From<InnerDehydratedDeviceKey> for DehydratedDeviceKey {
}
}
impl From<matrix_sdk_crypto::store::RoomKeyCounts> for RoomKeyCounts {
fn from(count: matrix_sdk_crypto::store::RoomKeyCounts) -> Self {
impl From<matrix_sdk_crypto::store::types::RoomKeyCounts> for RoomKeyCounts {
fn from(count: matrix_sdk_crypto::store::types::RoomKeyCounts) -> Self {
Self { total: count.total as i64, backed_up: count.backed_up as i64 }
}
}
@@ -907,6 +915,10 @@ impl From<matrix_sdk_crypto::CrossSigningStatus> for CrossSigningStatus {
pub struct RoomSettings {
/// The encryption algorithm that should be used in the room.
pub algorithm: EventEncryptionAlgorithm,
/// Whether state event encryption is enabled.
#[cfg(feature = "experimental-encrypted-state-events")]
#[serde(default)]
pub encrypt_state_events: bool,
/// Should untrusted devices receive the room key, or should they be
/// excluded from the conversation.
pub only_allow_trusted_devices: bool,
@@ -917,7 +929,12 @@ impl TryFrom<RustRoomSettings> for RoomSettings {
fn try_from(value: RustRoomSettings) -> Result<Self, Self::Error> {
let algorithm = value.algorithm.try_into()?;
Ok(Self { algorithm, only_allow_trusted_devices: value.only_allow_trusted_devices })
Ok(Self {
algorithm,
#[cfg(feature = "experimental-encrypted-state-events")]
encrypt_state_events: value.encrypt_state_events,
only_allow_trusted_devices: value.only_allow_trusted_devices,
})
}
}
@@ -1170,6 +1187,8 @@ mod tests {
assert_eq!(
Some(RoomSettings {
algorithm: EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
#[cfg(feature = "experimental-encrypted-state-events")]
encrypt_state_events: false,
only_allow_trusted_devices: true
}),
settings1
@@ -1179,6 +1198,8 @@ mod tests {
assert_eq!(
Some(RoomSettings {
algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
#[cfg(feature = "experimental-encrypted-state-events")]
encrypt_state_events: false,
only_allow_trusted_devices: false
}),
settings2
+51 -35
View File
@@ -16,9 +16,10 @@ use matrix_sdk_crypto::{
},
decrypt_room_key_export, encrypt_room_key_export,
olm::ExportedRoomKey,
store::{BackupDecryptionKey, Changes},
store::types::{BackupDecryptionKey, Changes},
types::requests::ToDeviceRequest,
DecryptionSettings, LocalTrust, OlmMachine as InnerMachine, UserIdentity as SdkUserIdentity,
CollectStrategy, DecryptionSettings, LocalTrust, OlmMachine as InnerMachine,
UserIdentity as SdkUserIdentity,
};
use ruma::{
api::{
@@ -38,7 +39,7 @@ use ruma::{
},
events::{
key::verification::VerificationMethod, room::message::MessageType, AnyMessageLikeEvent,
AnySyncMessageLikeEvent, MessageLikeEvent,
AnySyncMessageLikeEvent, AnyTimelineEvent, MessageLikeEvent,
},
serde::Raw,
to_device::DeviceIdOrAllDevices,
@@ -96,8 +97,8 @@ pub struct RoomKeyInfo {
pub session_id: String,
}
impl From<matrix_sdk_crypto::store::RoomKeyInfo> for RoomKeyInfo {
fn from(value: matrix_sdk_crypto::store::RoomKeyInfo) -> Self {
impl From<matrix_sdk_crypto::store::types::RoomKeyInfo> for RoomKeyInfo {
fn from(value: matrix_sdk_crypto::store::types::RoomKeyInfo) -> Self {
Self {
algorithm: value.algorithm.to_string(),
room_id: value.room_id.to_string(),
@@ -354,7 +355,7 @@ impl OlmMachine {
.map(|d| d.into()))
}
/// Manually the device of the given user with the given device ID.
/// Manually verify the device of the given user with the given device ID.
///
/// This method will attempt to sign the device using our private cross
/// signing key.
@@ -526,6 +527,7 @@ impl OlmMachine {
key_counts: HashMap<String, i32>,
unused_fallback_keys: Option<Vec<String>>,
next_batch_token: String,
decryption_settings: &DecryptionSettings,
) -> Result<SyncChangesResult, CryptoStoreError> {
let to_device: ToDevice = serde_json::from_str(&events)?;
let device_changes: RumaDeviceLists = device_changes.into();
@@ -544,18 +546,22 @@ impl OlmMachine {
let unused_fallback_keys: Option<Vec<OneTimeKeyAlgorithm>> =
unused_fallback_keys.map(|u| u.into_iter().map(OneTimeKeyAlgorithm::from).collect());
let (to_device_events, room_key_infos) = self.runtime.block_on(
self.inner.receive_sync_changes(matrix_sdk_crypto::EncryptionSyncChanges {
to_device_events: to_device.events,
changed_devices: &device_changes,
one_time_keys_counts: &key_counts,
unused_fallback_keys: unused_fallback_keys.as_deref(),
next_batch_token: Some(next_batch_token),
}),
)?;
let (to_device_events, room_key_infos) =
self.runtime.block_on(self.inner.receive_sync_changes(
matrix_sdk_crypto::EncryptionSyncChanges {
to_device_events: to_device.events,
changed_devices: &device_changes,
one_time_keys_counts: &key_counts,
unused_fallback_keys: unused_fallback_keys.as_deref(),
next_batch_token: Some(next_batch_token),
},
decryption_settings,
))?;
let to_device_events =
to_device_events.into_iter().map(|event| event.json().get().to_owned()).collect();
let to_device_events = to_device_events
.into_iter()
.map(|event| event.to_raw().json().get().to_owned())
.collect();
let room_key_infos = room_key_infos.into_iter().map(|info| info.into()).collect();
Ok(SyncChangesResult { to_device_events, room_key_infos })
@@ -827,6 +833,7 @@ impl OlmMachine {
device_id: String,
event_type: String,
content: String,
share_strategy: CollectStrategy,
) -> Result<Option<Request>, CryptoStoreError> {
let user_id = parse_user_id(&user_id)?;
let device_id = device_id.as_str().into();
@@ -835,8 +842,11 @@ impl OlmMachine {
let device = self.runtime.block_on(self.inner.get_device(&user_id, device_id, None))?;
if let Some(device) = device {
let encrypted_content =
self.runtime.block_on(device.encrypt_event_raw(&event_type, &content))?;
let encrypted_content = self.runtime.block_on(device.encrypt_event_raw(
&event_type,
&content,
share_strategy,
))?;
let request = ToDeviceRequest::new(
user_id.as_ref(),
@@ -892,7 +902,7 @@ impl OlmMachine {
))?;
if handle_verification_events {
if let Ok(e) = decrypted.event.deserialize() {
if let Ok(AnyTimelineEvent::MessageLike(e)) = decrypted.event.deserialize() {
match &e {
AnyMessageLikeEvent::RoomMessage(MessageLikeEvent::Original(
original_event,
@@ -915,20 +925,25 @@ impl OlmMachine {
let event_json: Event<'_> = serde_json::from_str(decrypted.event.json().get())?;
Ok(match &encryption_info.algorithm_info {
AlgorithmInfo::MegolmV1AesSha2 { curve25519_key, sender_claimed_keys } => {
DecryptedEvent {
clear_event: serde_json::to_string(&event_json)?,
sender_curve25519_key: curve25519_key.to_owned(),
claimed_ed25519_key: sender_claimed_keys
.get(&DeviceKeyAlgorithm::Ed25519)
.cloned(),
forwarding_curve25519_chain: vec![],
shield_state: if strict_shields {
encryption_info.verification_state.to_shield_state_strict().into()
} else {
encryption_info.verification_state.to_shield_state_lax().into()
},
}
AlgorithmInfo::MegolmV1AesSha2 {
curve25519_key,
sender_claimed_keys,
session_id: _,
} => DecryptedEvent {
clear_event: serde_json::to_string(&event_json)?,
sender_curve25519_key: curve25519_key.to_owned(),
claimed_ed25519_key: sender_claimed_keys.get(&DeviceKeyAlgorithm::Ed25519).cloned(),
forwarding_curve25519_chain: vec![],
shield_state: if strict_shields {
encryption_info.verification_state.to_shield_state_strict().into()
} else {
encryption_info.verification_state.to_shield_state_lax().into()
},
},
AlgorithmInfo::OlmV1Curve25519AesSha2 { .. } => {
// cannot happen because `decrypt_room_event` would have fail to decrypt olm for
// a room (EventError::UnsupportedAlgorithm)
panic!("Unsupported olm algorithm in room")
}
})
}
@@ -1335,7 +1350,8 @@ impl OlmMachine {
let (sas, request) = self.runtime.block_on(device.start_verification())?;
Some(StartSasResult {
sas: Sas { inner: sas, runtime: self.runtime.handle().to_owned() }.into(),
sas: Sas { inner: Box::new(sas), runtime: self.runtime.handle().to_owned() }
.into(),
request: request.into(),
})
} else {
@@ -27,7 +27,7 @@ use ruma::{
to_device::send_event_to_device::v3::Response as ToDeviceResponse,
},
assign,
events::EventContent,
events::MessageLikeEventContent,
OwnedTransactionId, UserId,
};
use serde_json::json;
@@ -224,8 +224,8 @@ impl From<&ToDeviceRequest> for Request {
}
}
impl From<&RoomMessageRequest> for Request {
fn from(r: &RoomMessageRequest) -> Self {
impl From<&Box<RoomMessageRequest>> for Request {
fn from(r: &Box<RoomMessageRequest>) -> Self {
Self::RoomMessage {
request_id: r.txn_id.to_string(),
room_id: r.room_id.to_string(),
@@ -1,6 +1,7 @@
use std::sync::Arc;
use futures_util::{Stream, StreamExt};
use matrix_sdk_common::executor::Handle;
use matrix_sdk_crypto::{
matrix_sdk_qrcode::QrVerificationData, CancelInfo as RustCancelInfo, QrVerification as InnerQr,
QrVerificationState, Sas as InnerSas, SasState as RustSasState,
@@ -8,7 +9,6 @@ use matrix_sdk_crypto::{
VerificationRequestState as RustVerificationRequestState,
};
use ruma::events::key::verification::VerificationMethod;
use tokio::runtime::Handle;
use vodozemac::{base64_decode, base64_encode};
use crate::{CryptoStoreError, OutgoingVerificationRequest, SignatureUploadRequest};
@@ -88,7 +88,7 @@ impl Verification {
/// returns `None` if the verification is not a `Sas` verification.
pub fn as_sas(&self) -> Option<Arc<Sas>> {
if let InnerVerification::SasV1(sas) = &self.inner {
Some(Sas { inner: sas.to_owned(), runtime: self.runtime.to_owned() }.into())
Some(Sas { inner: sas.clone(), runtime: self.runtime.to_owned() }.into())
} else {
None
}
@@ -98,7 +98,7 @@ impl Verification {
/// returns `None` if the verification is not a `QrCode` verification.
pub fn as_qr(&self) -> Option<Arc<QrCode>> {
if let InnerVerification::QrV1(qr) = &self.inner {
Some(QrCode { inner: qr.to_owned(), runtime: self.runtime.to_owned() }.into())
Some(QrCode { inner: qr.clone(), runtime: self.runtime.to_owned() }.into())
} else {
None
}
@@ -108,7 +108,7 @@ impl Verification {
/// The `m.sas.v1` verification flow.
#[derive(uniffi::Object)]
pub struct Sas {
pub(crate) inner: InnerSas,
pub(crate) inner: Box<InnerSas>,
pub(crate) runtime: Handle,
}
@@ -324,7 +324,7 @@ impl From<QrVerificationState> for QrCodeState {
/// verification flow.
#[derive(uniffi::Object)]
pub struct QrCode {
pub(crate) inner: InnerQr,
pub(crate) inner: Box<InnerQr>,
pub(crate) runtime: Handle,
}
@@ -669,7 +669,7 @@ impl VerificationRequest {
/// verification flow.
pub fn start_sas_verification(&self) -> Result<Option<StartSasResult>, CryptoStoreError> {
Ok(self.runtime.block_on(self.inner.start_sas())?.map(|(sas, r)| StartSasResult {
sas: Arc::new(Sas { inner: sas, runtime: self.runtime.clone() }),
sas: Arc::new(Sas { inner: Box::new(sas), runtime: self.runtime.clone() }),
request: r.into(),
}))
}
@@ -690,7 +690,7 @@ impl VerificationRequest {
Ok(self
.runtime
.block_on(self.inner.generate_qr_code())?
.map(|qr| QrCode { inner: qr, runtime: self.runtime.clone() }.into()))
.map(|qr| QrCode { inner: Box::new(qr), runtime: self.runtime.clone() }.into()))
}
/// Pass data from a scanned QR code to an active verification request and
@@ -717,7 +717,7 @@ impl VerificationRequest {
let request = qr.reciprocate()?;
Some(ScanResult {
qr: QrCode { inner: qr, runtime: self.runtime.clone() }.into(),
qr: QrCode { inner: Box::new(qr), runtime: self.runtime.clone() }.into(),
request: request.into(),
})
} else {
+1 -1
View File
@@ -7,7 +7,7 @@ license = "Apache-2.0"
name = "matrix-sdk-ffi-macros"
readme = "README.md"
repository = "https://github.com/matrix-org/matrix-rust-sdk"
rust-version = { workspace = true }
rust-version.workspace = true
version = "0.7.0"
publish = false
+6 -1
View File
@@ -51,7 +51,12 @@ pub fn export(attr: TokenStream, item: TokenStream) -> TokenStream {
let res = match syn::parse(item) {
Ok(item) => match has_async_fn(item) {
true => quote! { #[uniffi::export(async_runtime = "tokio", #attr2)] },
true => {
quote! {
#[cfg_attr(target_family = "wasm", uniffi::export(#attr2))]
#[cfg_attr(not(target_family = "wasm"), uniffi::export(async_runtime = "tokio", #attr2))]
}
}
false => quote! { #[uniffi::export(#attr2)] },
},
Err(e) => e.into_compile_error(),
+174 -4
View File
@@ -6,6 +6,173 @@ All notable changes to this project will be documented in this file.
## [Unreleased] - ReleaseDate
## [0.14.0] - 2025-09-04
### Features:
- Add `LowPriority` and `NonLowPriority` variants to `RoomListEntriesDynamicFilterKind` for filtering
rooms based on their low priority status. These filters allow clients to show only low priority rooms
or exclude low priority rooms from the room list.
([#5508](https://github.com/matrix-org/matrix-rust-sdk/pull/5508))
- Add `room_version` and `privileged_creators_role` to `RoomInfo` ([#5449](https://github.com/matrix-org/matrix-rust-sdk/pull/5449)).
- The [`unstable-hydra`] feature has been enabled, which enables room v12 changes in the SDK.
([#5450](https://github.com/matrix-org/matrix-rust-sdk/pull/5450)).
- Add experimental support for
[MSC4306](https://github.com/matrix-org/matrix-spec-proposals/pull/4306), with the
`Room::fetch_thread_subscription()` and `Room::set_thread_subscription()` methods.
([#5442](https://github.com/matrix-org/matrix-rust-sdk/pull/5442))
- [**breaking**] [`GalleryUploadParameters::reply`] and [`UploadParameters::reply`] have been both
replaced with a new optional `in_reply_to` field, that's a string which will be parsed into an
`OwnedEventId` when sending the event. The thread relationship will be automatically filled in,
based on the timeline focus.
([5427](https://github.com/matrix-org/matrix-rust-sdk/pull/5427))
- [**breaking**] [`Timeline::send_reply()`] now automatically fills in the thread relationship,
based on the timeline focus. As a result, it only takes an `OwnedEventId` parameter, instead of
the `Reply` type. The proper way to start a thread is now thus to create a threaded-focused
timeline, and then use `Timeline::send()`.
([5427](https://github.com/matrix-org/matrix-rust-sdk/pull/5427))
- Add `HomeserverLoginDetails::supports_sso_login` for legacy SSO support information.
This is primarily for Element X to give a dedicated error message in case
it connects a homeserver with only this method available.
([#5222](https://github.com/matrix-org/matrix-rust-sdk/pull/5222))
### Breaking changes:
- The timeline will now always use the send queue to upload medias, so the
`UploadParameters::use_send_queue` bool has been removed. Make sure to listen to the send queue's
error updates, and to handle send queue restarts.
([#5525](https://github.com/matrix-org/matrix-rust-sdk/pull/5525))
- Support for the legacy media upload progress has been disabled. Media upload progress is
available through the send queue, and can be enabled thanks to
`Client::enable_send_queue_upload_progress()`.
([#5525](https://github.com/matrix-org/matrix-rust-sdk/pull/5525))
- `TimelineDiff` is now exported as a true `uniffi::Enum` instead of the weird `uniffi::Object` hybrid. This matches
both `RoomDirectorySearchEntryUpdate` and `RoomListEntriesUpdate` and can be used in the same way.
([#5474](https://github.com/matrix-org/matrix-rust-sdk/pull/5474))
- The `creator` field of `RoomInfo` has been renamed to `creators` and can now contain a list of
user IDs, to reflect that a room can now have several creators, as introduced in room version 12.
([#5436](https://github.com/matrix-org/matrix-rust-sdk/pull/5436))
- The `PowerLevel` type was introduced to represent power levels instead of `i64` to differentiate
the infinite power level of creators, as introduced in room version 12. It is used in
`suggested_role_for_power_level`, `suggested_power_level_for_role` and `RoomMember`.
([#5436](https://github.com/matrix-org/matrix-rust-sdk/pull/5436))
- `Client::get_url` now returns a `Vec<u8>` instead of a `String`. It also throws an error when the
response isn't status code 200 OK, instead of providing the error in the response body.
([#5438](https://github.com/matrix-org/matrix-rust-sdk/pull/5438))
- `RoomPreview::info()` doesn't return a result anymore. All unknown join rules are handled in the
`JoinRule::Custom` variant.
([#5337](https://github.com/matrix-org/matrix-rust-sdk/pull/5337))
- The `reason` argument of `Room::report_room` is now required, do to a clarification in the spec.
([#5337](https://github.com/matrix-org/matrix-rust-sdk/pull/5337))
- `PublicRoomJoinRule` has more variants, supporting all the known values from the spec.
([#5337](https://github.com/matrix-org/matrix-rust-sdk/pull/5337))
- The fields of `MediaPreviewConfig` are both optional, allowing to use the type for room account
data as well as global account data.
([#5337](https://github.com/matrix-org/matrix-rust-sdk/pull/5337))
- The `event_id` field of `PredecessorRoom` was removed, due to its removal in the Matrix
specification with MSC4291.
([#5419](https://github.com/matrix-org/matrix-rust-sdk/pull/5419))
- `Client::url_for_oidc` now allows requesting additional scopes for the OAuth2 authorization code grant.
([#5395](https://github.com/matrix-org/matrix-rust-sdk/pull/5395))
- `Client::url_for_oidc` now allows passing an optional existing device id from a previous login call.
([#5394](https://github.com/matrix-org/matrix-rust-sdk/pull/5394))
- `ClientBuilder::build_with_qr_code` has been removed. Instead, the Client should be built by passing
`QrCodeData::server_name` to `ClientBuilder::server_name_or_homeserver_url`, after which QR login can be performed by
calling `Client::login_with_qr_code`. ([#5388](https://github.com/matrix-org/matrix-rust-sdk/pull/5388))
- The MSRV has been bumped to Rust 1.88.
([#5431](https://github.com/matrix-org/matrix-rust-sdk/pull/5431))
- `Room::send_call_notification` and `Room::send_call_notification_if_needed` have been removed, since the event type they send is outdated, and `Client` is not actually supposed to be able to join MatrixRTC sessions (yet). In practice, users of these methods probably already rely on another MatrixRTC implementation to participate in sessions, and such an implementation should be capable of sending notifications itself.
- The `GalleryItemInfo` variants now take an `UploadSource` rather than a `String` path to enable uploading
from bytes directly.
([#5529](https://github.com/matrix-org/matrix-rust-sdk/pull/5529))
- Media and gallery uploads now use `UploadSource` to specify the thumbnail.
([#5530](https://github.com/matrix-org/matrix-rust-sdk/pull/5530))
## [0.13.0] - 2025-07-10
### Features
- Add `NotificationRoomInfo::topic` to the `NotificationRoomInfo` struct, which
contains the topic of the room. This is useful for displaying the room topic
in notifications. ([#5300](https://github.com/matrix-org/matrix-rust-sdk/pull/5300))
- Add `EmbeddedEventDetails::timestamp` and `EmbeddedEventDetails::event_or_transaction_id`
which are already available in regular timeline items.
([#5331](https://github.com/matrix-org/matrix-rust-sdk/pull/5331))
- `RoomListService::subscribe_to_rooms` becomes `async` and automatically calls
`matrix_sdk::latest_events::LatestEvents::listen_to_room`
([#5369](https://github.com/matrix-org/matrix-rust-sdk/pull/5369))
### Refactor
- Adjust features in the `matrix-sdk-ffi` crate to expose more platform-specific knobs.
Previously the `matrix-sdk-ffi` was configured primarily by target configs, choosing
between the tls flavor (`rustls-tls` or `native-tls`) and features like `sentry` based
purely on the target. As we work to add an additional Wasm target to this crate,
the cross product of target specific features has become somewhat chaotic, and we
have shifted to externalize these choices as feature flags.
To maintain existing compatibility on the major platforms, these features should be used:
Android: `"bundled-sqlite,unstable-msc4274,rustls-tls,sentry"`
iOS: `"bundled-sqlite,unstable-msc4274,native-tls,sentry"`
Javascript/Wasm: `"unstable-msc4274,native-tls"`
In the future additional choices (such as session storage, `sqlite` and `indexeddb`)
will likely be added as well.
Breaking changes:
- `Client::reset_server_capabilities` has been renamed to `Client::reset_server_info`.
([#5167](https://github.com/matrix-org/matrix-rust-sdk/pull/5167))
- `RoomPreview::join_rule`, `NotificationItem::join_rule`, `RoomInfo::is_public`, and
`Room::is_public()` return values are now optional. They will be set to `None` if the join rule
state event is missing for a given room. `NotificationRoomInfo::is_public` has been removed;
callers can inspect the value of `NotificationItem::join_rule` to determine if the room is public
(i.e. if the join rule is `Public`).
([#5278](https://github.com/matrix-org/matrix-rust-sdk/pull/5278))
## [0.12.0] - 2025-06-10
Breaking changes:
- `Client::send_call_notification_if_needed` now returns `Result<bool>` instead of `Result<()>` so we can check if
the event was sent.
- `Client::upload_avatar` and `Timeline::send_attachment` now may fail if a file too large for the homeserver media
config is uploaded.
- `UploadParameters` replaces field `filename: String` with `source: UploadSource`.
`UploadSource` is an enum which may take a filename or a filename and bytes, which
allows a foreign language to read file contents natively and then pass those contents to
the foreign function when uploading a file through the `Timeline`.
([#4948](https://github.com/matrix-org/matrix-rust-sdk/pull/4948))
- `RoomInfo` replaces its field `is_tombstoned: bool` with `tombstone: Option<RoomTombstoneInfo>`,
containing the data needed to implement the room migration UI, a message and the replacement room id.
([#5027](https://github.com/matrix-org/matrix-rust-sdk/pull/5027))
Additions:
- `Client::subscribe_to_room_info` allows clients to subscribe to room info updates in rooms which may not be known yet.
This is useful when displaying a room preview for an unknown room, so when we receive any membership change for it,
we can automatically update the UI.
- `Client::get_max_media_upload_size` to get the max size of a request sent to the homeserver so we can tweak our media
uploads by compressing/transcoding the media.
- Add `ClientBuilder::enable_share_history_on_invite` to enable experimental support for sharing encrypted room history
on invite, per [MSC4268](https://github.com/matrix-org/matrix-spec-proposals/pull/4268).
([#5141](https://github.com/matrix-org/matrix-rust-sdk/pull/5141))
- Support for adding a Sentry layer to the FFI bindings has been added. Only `tracing` statements with
the field `sentry=true` will be forwarded to Sentry, in addition to default Sentry filters.
- Add room topic string to `StateEventContent`
- Add `UploadSource` for representing upload data - this is analogous to `matrix_sdk_ui::timeline::AttachmentSource`
- Add `Client::observe_account_data_event` and `Client::observe_room_account_data_event` to
subscribe to global and room account data changes.
([#4994](https://github.com/matrix-org/matrix-rust-sdk/pull/4994))
- Add `Timeline::send_gallery` to send MSC4274-style galleries.
([#5163](https://github.com/matrix-org/matrix-rust-sdk/pull/5163))
- Add `reply_params` to `GalleryUploadParameters` to allow sending galleries as (threaded) replies.
([#5173](https://github.com/matrix-org/matrix-rust-sdk/pull/5173))
Breaking changes:
- `contacts` has been removed from `OidcConfiguration` (it was unused since the switch to OAuth).
## [0.11.0] - 2025-04-11
Breaking changes:
@@ -20,7 +187,7 @@ Breaking changes:
programs can set it to `true`.
- Matrix client API errors coming from API responses will now be mapped to `ClientError::MatrixApi`, containing both the
original message and the associated error code and kind.
original message and the associated error code and kind.
- `EventSendState` now has two additional variants: `CrossSigningNotSetup` and
`SendingFromUnverifiedDevice`. These indicate that your own device is not
@@ -81,7 +248,8 @@ Breaking changes:
- The `dynamic_registrations_file` field of `OidcConfiguration` was removed.
Clients are supposed to re-register with the homeserver for every login.
- `RoomPreview::own_membership_details` is now `RoomPreview::member_with_sender_info`, takes any user id and returns an `Option<RoomMemberWithSenderInfo>`.
- `RoomPreview::own_membership_details` is now `RoomPreview::member_with_sender_info`, takes any user id and returns an
`Option<RoomMemberWithSenderInfo>`.
Additions:
@@ -96,9 +264,11 @@ Additions:
- Add `Timeline::send_thread_reply` for clients that need to start threads
themselves.
([4819](https://github.com/matrix-org/matrix-rust-sdk/pull/4819))
- Add `ClientBuilder::session_pool_max_size`, `::session_cache_size` and `::session_journal_size_limit` to control the stores configuration, especially their memory consumption
- Add `ClientBuilder::session_pool_max_size`, `::session_cache_size` and `::session_journal_size_limit` to control the
stores configuration, especially their memory consumption
([#4870](https://github.com/matrix-org/matrix-rust-sdk/pull/4870/))
- Add `ClientBuilder::system_is_memory_constrained` to indicate that the system
has less memory available than the current standard
([#4894](https://github.com/matrix-org/matrix-rust-sdk/pull/4894))
- Add `Room::member_with_sender_info` to get both a room member's info and for the user who sent the `m.room.member` event the `RoomMember` is based on.
- Add `Room::member_with_sender_info` to get both a room member's info and for the user who sent the `m.room.member`
event the `RoomMember` is based on.
+72 -53
View File
@@ -1,84 +1,103 @@
[package]
name = "matrix-sdk-ffi"
version = "0.11.0"
version = "0.14.0"
edition = "2021"
homepage = "https://github.com/matrix-org/matrix-rust-sdk"
keywords = ["matrix", "chat", "messaging", "ffi"]
license = "Apache-2.0"
readme = "README.md"
rust-version = { workspace = true }
rust-version.workspace = true
repository = "https://github.com/matrix-org/matrix-rust-sdk"
publish = false
[package.metadata.release]
release = true
[lib]
crate-type = ["cdylib", "staticlib"]
crate-type = [
# Needed by uniffi for Android bindings
"cdylib",
# Needed by uniffi for iOS bindings
"staticlib",
# Needed by uniffi for JS/Wasm bindings, which use rust as an intermediate language
"lib"
]
[features]
default = ["bundled-sqlite"]
default = ["bundled-sqlite", "unstable-msc4274"]
bundled-sqlite = ["matrix-sdk/bundled-sqlite"]
[build-dependencies]
uniffi = { workspace = true, features = ["build"] }
vergen = { version = "8.1.3", features = ["build", "git", "gitcl"] }
unstable-msc4274 = ["matrix-sdk-ui/unstable-msc4274"]
# Required when targeting a Javascript environment, like Wasm in a browser.
js = ["matrix-sdk-ui/js"]
# Use the TLS implementation provided by the host system, necessary on iOS and Wasm platforms.
native-tls = ["matrix-sdk/native-tls", "sentry?/native-tls"]
# Use Rustls as the TLS implementation, necessary on Android platforms.
rustls-tls = ["matrix-sdk/rustls-tls", "sentry?/rustls"]
# Enable sentry error monitoring, not compatible with Wasm platforms.
sentry = ["dep:sentry", "dep:sentry-tracing"]
[dependencies]
anyhow = { workspace = true }
as_variant = { workspace = true }
async-compat = "0.2.4"
eyeball-im = { workspace = true }
anyhow.workspace = true
extension-trait = "1.0.1"
futures-util = { workspace = true }
eyeball-im.workspace = true
futures-util.workspace = true
language-tags = "0.3.2"
log-panics = { version = "2", features = ["with-backtrace"] }
matrix-sdk-ffi-macros = { workspace = true }
matrix-sdk = { workspace = true, features = [
"anyhow",
"e2e-encryption",
"experimental-widgets",
"markdown",
"socks",
"sqlite",
"uniffi",
] }
matrix-sdk-common.workspace = true
matrix-sdk-ffi-macros.workspace = true
matrix-sdk-ui = { workspace = true, features = ["uniffi"] }
mime = "0.3.16"
once_cell = { workspace = true }
ruma = { workspace = true, features = ["html", "unstable-unspecified", "unstable-msc3488", "compat-unset-avatar", "unstable-msc3245-v1-compat"] }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
tracing-core = { workspace = true }
once_cell.workspace = true
ruma = { workspace = true, features = ["html", "unstable-msc3488", "compat-unset-avatar", "unstable-msc3245-v1-compat", "unstable-msc4278", "unstable-hydra"] }
serde.workspace = true
serde_json.workspace = true
sentry = { workspace = true, optional = true, default-features = false, features = [
# Most default features enabled otherwise.
"backtrace",
"contexts",
"panic",
"reqwest",
"sentry-debug-images",
] }
sentry-tracing = { workspace = true, optional = true }
thiserror.workspace = true
tracing.workspace = true
tracing-appender.workspace = true
tracing-core.workspace = true
tracing-subscriber = { workspace = true, features = ["env-filter"] }
tracing-appender = { version = "0.2.2" }
url.workspace = true
uuid = { version = "1.4.1", features = ["v4"] }
zeroize.workspace = true
oauth2.workspace = true
[target.'cfg(target_family = "wasm")'.dependencies]
console_error_panic_hook = "0.1.7"
tokio = { workspace = true, features = ["sync", "macros"] }
uniffi.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dependencies]
async-compat.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
uniffi = { workspace = true, features = ["tokio"] }
url = { workspace = true }
zeroize = { workspace = true }
uuid = { version = "1.4.1", features = ["v4"] }
language-tags = "0.3.2"
[target.'cfg(target_os = "android")'.dependencies]
paranoid-android = "0.2.1"
[target.'cfg(target_os = "android")'.dependencies.matrix-sdk]
workspace = true
features = [
"anyhow",
"e2e-encryption",
"experimental-widgets",
"markdown",
"rustls-tls", # note: differ from block below
"socks",
"sqlite",
"uniffi",
]
[dev-dependencies]
similar-asserts.workspace = true
[target.'cfg(not(target_os = "android"))'.dependencies.matrix-sdk]
workspace = true
features = [
"anyhow",
"e2e-encryption",
"experimental-widgets",
"markdown",
"native-tls", # note: differ from block above
"socks",
"sqlite",
"uniffi",
]
[build-dependencies]
uniffi = { workspace = true, features = ["build"] }
vergen-gitcl = { workspace = true, features = ["build"] }
[lints]
workspace = true
[package.metadata.release]
release = true
+20
View File
@@ -2,8 +2,28 @@
This uses [`uniffi`](https://mozilla.github.io/uniffi-rs/Overview.html) to build the matrix bindings for native support and wasm-bindgen for web-browser assembly support. Please refer to the specific section to figure out how to build and use the bindings for your platform.
## Features
Given the number of platforms targeted, we have broken out a number of features
### Platform specific
- `rustls-tls`: Use Rustls as the TLS implementation, necessary on Android platforms.
- `native-tls`: Use the TLS implementation provided by the host system, necessary on iOS and Wasm platforms.
### Functionality
- `sentry`: Enable error monitoring using Sentry, not supports on Wasm platforms.
- `bundled-sqlite`: Use an embedded version of sqlite instead of the system provided one.
### Unstable specs
- `unstable-msc4274`: Adds support for gallery message types, which contain multiple media elements.
## Platforms
Each supported target should use features to select the relevant TLS system. Here are some suggested feature flags for the major platforms:
- Android: `"bundled-sqlite,unstable-msc4274,rustls-tls,sentry"`
- iOS: `"bundled-sqlite,unstable-msc4274,native-tls,sentry"`
- Javascript/Wasm: `"unstable-msc4274,native-tls"`
### Swift/iOS sync
+5 -2
View File
@@ -5,7 +5,7 @@ use std::{
process::Command,
};
use vergen::EmitBuilder;
use vergen_gitcl::{Emitter, GitclBuilder};
/// Adds a temporary workaround for an issue with the Rust compiler and Android
/// in x86_64 devices: https://github.com/rust-lang/rust/issues/109717.
@@ -59,6 +59,9 @@ fn get_clang_major_version(clang_path: &Path) -> String {
fn main() -> Result<(), Box<dyn Error>> {
setup_x86_64_android_workaround();
uniffi::generate_scaffolding("./src/api.udl").expect("Building the UDL file failed");
EmitBuilder::builder().git_sha(true).emit()?;
let git_config = GitclBuilder::default().sha(true).build()?;
Emitter::default().add_instructions(&git_config)?.emit()?;
Ok(())
}
@@ -23,6 +23,7 @@ pub struct HomeserverLoginDetails {
pub(crate) sliding_sync_version: SlidingSyncVersion,
pub(crate) supports_oidc_login: bool,
pub(crate) supported_oidc_prompts: Vec<OidcPrompt>,
pub(crate) supports_sso_login: bool,
pub(crate) supports_password_login: bool,
}
@@ -43,6 +44,11 @@ impl HomeserverLoginDetails {
self.supports_oidc_login
}
/// Whether the current homeserver supports login using legacy SSO.
pub fn supports_sso_login(&self) -> bool {
self.supports_sso_login
}
/// The prompts advertised by the authentication issuer for use in the login
/// URL.
pub fn supported_oidc_prompts(&self) -> Vec<OidcPrompt> {
@@ -119,8 +125,6 @@ pub struct OidcConfiguration {
pub tos_uri: Option<String>,
/// A URI that contains the client's privacy policy.
pub policy_uri: Option<String>,
/// An array of e-mail addresses of people responsible for this client.
pub contacts: Option<Vec<String>>,
/// Pre-configured registrations for use with homeservers that don't support
/// dynamic client registration.
@@ -173,7 +177,7 @@ impl OidcConfiguration {
.iter()
.filter_map(|(issuer, client_id)| {
let Ok(issuer) = Url::parse(issuer) else {
tracing::error!("Failed to parse {:?}", issuer);
tracing::error!("Failed to parse {issuer:?}");
return None;
};
Some((issuer, ClientId::new(client_id.clone())))
File diff suppressed because it is too large Load Diff
+162 -321
View File
@@ -1,33 +1,25 @@
use std::{fs, num::NonZeroUsize, path::Path, sync::Arc, time::Duration};
use async_compat::get_runtime_handle;
use futures_util::StreamExt;
#[cfg(not(target_family = "wasm"))]
use matrix_sdk::reqwest::Certificate;
use matrix_sdk::{
authentication::oauth::qrcode::{self, DeviceCodeErrorResponseType, LoginFailureReason},
crypto::{
types::qr_login::{LoginQrCodeDecodeError, QrCodeModeData},
CollectStrategy, TrustRequirement,
},
crypto::{CollectStrategy, DecryptionSettings, TrustRequirement},
encryption::{BackupDownloadStrategy, EncryptionSettings},
event_cache::EventCacheError,
reqwest::Certificate,
ruma::{ServerName, UserId},
sliding_sync::{
Error as MatrixSlidingSyncError, VersionBuilder as MatrixSlidingSyncVersionBuilder,
VersionBuilderError,
},
Client as MatrixClient, ClientBuildError as MatrixClientBuildError, HttpError, IdParseError,
RumaApiError, SqliteStoreConfig,
RumaApiError, SqliteStoreConfig, ThreadingSupport,
};
use ruma::api::error::{DeserializationError, FromHttpResponseError};
use tracing::{debug, error};
use zeroize::Zeroizing;
use super::client::Client;
use crate::{
authentication::OidcConfiguration, client::ClientSessionDelegate, error::ClientError,
helpers::unwrap_or_clone_arc, task_handle::TaskHandle,
};
use crate::{client::ClientSessionDelegate, error::ClientError, helpers::unwrap_or_clone_arc};
/// A list of bytes containing a certificate in DER or PEM form.
pub type CertificateBytes = Vec<u8>;
@@ -39,152 +31,6 @@ enum HomeserverConfig {
ServerNameOrUrl(String),
}
/// Data for the QR code login mechanism.
///
/// The [`QrCodeData`] can be serialized and encoded as a QR code or it can be
/// decoded from a QR code.
#[derive(Debug, uniffi::Object)]
pub struct QrCodeData {
inner: qrcode::QrCodeData,
}
#[matrix_sdk_ffi_macros::export]
impl QrCodeData {
/// Attempt to decode a slice of bytes into a [`QrCodeData`] object.
///
/// The slice of bytes would generally be returned by a QR code decoder.
#[uniffi::constructor]
pub fn from_bytes(bytes: Vec<u8>) -> Result<Arc<Self>, QrCodeDecodeError> {
Ok(Self { inner: qrcode::QrCodeData::from_bytes(&bytes)? }.into())
}
}
/// Error type for the decoding of the [`QrCodeData`].
#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi(flat_error)]
pub enum QrCodeDecodeError {
#[error("Error decoding QR code: {error:?}")]
Crypto {
#[from]
error: LoginQrCodeDecodeError,
},
}
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum HumanQrLoginError {
#[error("Linking with this device is not supported.")]
LinkingNotSupported,
#[error("The sign in was cancelled.")]
Cancelled,
#[error("The sign in was not completed in the required time.")]
Expired,
#[error("A secure connection could not have been established between the two devices.")]
ConnectionInsecure,
#[error("The sign in was declined.")]
Declined,
#[error("An unknown error has happened.")]
Unknown,
#[error("The homeserver doesn't provide sliding sync in its configuration.")]
SlidingSyncNotAvailable,
#[error("Unable to use OIDC as the supplied client metadata is invalid.")]
OidcMetadataInvalid,
#[error("The other device is not signed in and as such can't sign in other devices.")]
OtherDeviceNotSignedIn,
}
impl From<qrcode::QRCodeLoginError> for HumanQrLoginError {
fn from(value: qrcode::QRCodeLoginError) -> Self {
use qrcode::{QRCodeLoginError, SecureChannelError};
match value {
QRCodeLoginError::LoginFailure { reason, .. } => match reason {
LoginFailureReason::UnsupportedProtocol => HumanQrLoginError::LinkingNotSupported,
LoginFailureReason::AuthorizationExpired => HumanQrLoginError::Expired,
LoginFailureReason::UserCancelled => HumanQrLoginError::Cancelled,
_ => HumanQrLoginError::Unknown,
},
QRCodeLoginError::OAuth(e) => {
if let Some(e) = e.as_request_token_error() {
match e {
DeviceCodeErrorResponseType::AccessDenied => HumanQrLoginError::Declined,
DeviceCodeErrorResponseType::ExpiredToken => HumanQrLoginError::Expired,
_ => HumanQrLoginError::Unknown,
}
} else {
HumanQrLoginError::Unknown
}
}
QRCodeLoginError::SecureChannel(e) => match e {
SecureChannelError::Utf8(_)
| SecureChannelError::MessageDecode(_)
| SecureChannelError::Json(_)
| SecureChannelError::RendezvousChannel(_) => HumanQrLoginError::Unknown,
SecureChannelError::SecureChannelMessage { .. }
| SecureChannelError::Ecies(_)
| SecureChannelError::InvalidCheckCode => HumanQrLoginError::ConnectionInsecure,
SecureChannelError::InvalidIntent => HumanQrLoginError::OtherDeviceNotSignedIn,
},
QRCodeLoginError::UnexpectedMessage { .. }
| QRCodeLoginError::CrossProcessRefreshLock(_)
| QRCodeLoginError::DeviceKeyUpload(_)
| QRCodeLoginError::SessionTokens(_)
| QRCodeLoginError::UserIdDiscovery(_)
| QRCodeLoginError::SecretImport(_) => HumanQrLoginError::Unknown,
}
}
}
/// Enum describing the progress of the QR-code login.
#[derive(Debug, Default, Clone, uniffi::Enum)]
pub enum QrLoginProgress {
/// The login process is starting.
#[default]
Starting,
/// We established a secure channel with the other device.
EstablishingSecureChannel {
/// The check code that the device should display so the other device
/// can confirm that the channel is secure as well.
check_code: u8,
/// The string representation of the check code, will be guaranteed to
/// be 2 characters long, preserving the leading zero if the
/// first digit is a zero.
check_code_string: String,
},
/// We are waiting for the login and for the OAuth 2.0 authorization server
/// to give us an access token.
WaitingForToken { user_code: String },
/// The login has successfully finished.
Done,
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait QrLoginProgressListener: Sync + Send {
fn on_update(&self, state: QrLoginProgress);
}
impl From<qrcode::LoginProgress> for QrLoginProgress {
fn from(value: qrcode::LoginProgress) -> Self {
use qrcode::LoginProgress;
match value {
LoginProgress::Starting => Self::Starting,
LoginProgress::EstablishingSecureChannel { check_code } => {
let check_code = check_code.to_digit();
Self::EstablishingSecureChannel {
check_code,
check_code_string: format!("{check_code:02}"),
}
}
LoginProgress::WaitingForToken { user_code } => Self::WaitingForToken { user_code },
LoginProgress::Done => Self::Done,
}
}
}
#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi(flat_error)]
pub enum ClientBuildError {
@@ -262,26 +108,36 @@ pub struct ClientBuilder {
system_is_memory_constrained: bool,
username: Option<String>,
homeserver_cfg: Option<HomeserverConfig>,
user_agent: Option<String>,
sliding_sync_version_builder: SlidingSyncVersionBuilder,
proxy: Option<String>,
disable_ssl_verification: bool,
disable_automatic_token_refresh: bool,
cross_process_store_locks_holder_name: Option<String>,
enable_oidc_refresh_lock: bool,
session_delegate: Option<Arc<dyn ClientSessionDelegate>>,
additional_root_certificates: Vec<Vec<u8>>,
disable_built_in_root_certificates: bool,
encryption_settings: EncryptionSettings,
room_key_recipient_strategy: CollectStrategy,
decryption_trust_requirement: TrustRequirement,
decryption_settings: DecryptionSettings,
enable_share_history_on_invite: bool,
request_config: Option<RequestConfig>,
/// Whether to enable use of the event cache store, for reloading events
/// when building timelines et al.
use_event_cache_persistent_storage: bool,
#[cfg(not(target_family = "wasm"))]
user_agent: Option<String>,
#[cfg(not(target_family = "wasm"))]
proxy: Option<String>,
#[cfg(not(target_family = "wasm"))]
disable_ssl_verification: bool,
#[cfg(not(target_family = "wasm"))]
disable_built_in_root_certificates: bool,
#[cfg(not(target_family = "wasm"))]
additional_root_certificates: Vec<Vec<u8>>,
threading_support: ThreadingSupport,
}
/// The timeout applies to each read operation, and resets after a successful
/// read. This is more appropriate for detecting stalled connections when the
/// size isnt known beforehand.
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(60);
#[matrix_sdk_ffi_macros::export]
impl ClientBuilder {
#[uniffi::constructor]
@@ -312,29 +168,15 @@ impl ClientBuilder {
auto_enable_backups: false,
},
room_key_recipient_strategy: Default::default(),
decryption_trust_requirement: TrustRequirement::Untrusted,
decryption_settings: DecryptionSettings {
sender_device_trust_requirement: TrustRequirement::Untrusted,
},
enable_share_history_on_invite: false,
request_config: Default::default(),
use_event_cache_persistent_storage: false,
threading_support: ThreadingSupport::Disabled,
})
}
/// Whether to use the event cache persistent storage or not.
///
/// This is a temporary feature flag, for testing the event cache's
/// persistent storage. Follow new developments in https://github.com/matrix-org/matrix-rust-sdk/issues/3280.
///
/// This is disabled by default. When disabled, a one-time cleanup is
/// performed when creating the client, and it will clear all the events
/// previously stored in the event cache.
///
/// When enabled, it will attempt to store events in the event cache as
/// they're received, and reuse them when reconstructing timelines.
pub fn use_event_cache_persistent_storage(self: Arc<Self>, value: bool) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.use_event_cache_persistent_storage = value;
Arc::new(builder)
}
pub fn cross_process_store_locks_holder_name(
self: Arc<Self>,
holder_name: String,
@@ -463,12 +305,6 @@ impl ClientBuilder {
Arc::new(builder)
}
pub fn user_agent(self: Arc<Self>, user_agent: String) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.user_agent = Some(user_agent);
Arc::new(builder)
}
pub fn sliding_sync_version_builder(
self: Arc<Self>,
version_builder: SlidingSyncVersionBuilder,
@@ -478,43 +314,12 @@ impl ClientBuilder {
Arc::new(builder)
}
pub fn proxy(self: Arc<Self>, url: String) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.proxy = Some(url);
Arc::new(builder)
}
pub fn disable_ssl_verification(self: Arc<Self>) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.disable_ssl_verification = true;
Arc::new(builder)
}
pub fn disable_automatic_token_refresh(self: Arc<Self>) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.disable_automatic_token_refresh = true;
Arc::new(builder)
}
pub fn add_root_certificates(
self: Arc<Self>,
certificates: Vec<CertificateBytes>,
) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.additional_root_certificates = certificates;
Arc::new(builder)
}
/// Don't trust any system root certificates, only trust the certificates
/// provided through
/// [`add_root_certificates`][ClientBuilder::add_root_certificates].
pub fn disable_built_in_root_certificates(self: Arc<Self>) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.disable_built_in_root_certificates = true;
Arc::new(builder)
}
pub fn auto_enable_cross_signing(
self: Arc<Self>,
auto_enable_cross_signing: bool,
@@ -553,12 +358,25 @@ impl ClientBuilder {
}
/// Set the trust requirement to be used when decrypting events.
pub fn room_decryption_trust_requirement(
pub fn decryption_settings(
self: Arc<Self>,
trust_requirement: TrustRequirement,
decryption_settings: DecryptionSettings,
) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.decryption_trust_requirement = trust_requirement;
builder.decryption_settings = decryption_settings;
Arc::new(builder)
}
/// Set whether to enable the experimental support for sending and receiving
/// encrypted room history on invite, per [MSC4268].
///
/// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
pub fn enable_share_history_on_invite(
self: Arc<Self>,
enable_share_history_on_invite: bool,
) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.enable_share_history_on_invite = enable_share_history_on_invite;
Arc::new(builder)
}
@@ -569,6 +387,23 @@ impl ClientBuilder {
Arc::new(builder)
}
/// Whether the client should support threads client-side or not, and enable
/// experimental support for MSC4306 (threads subscriptions) or not.
pub fn threads_enabled(
self: Arc<Self>,
enabled: bool,
thread_subscriptions: bool,
) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
let support = if enabled {
ThreadingSupport::Enabled { with_subscriptions: thread_subscriptions }
} else {
ThreadingSupport::Disabled
};
builder.threading_support = support;
Arc::new(builder)
}
pub async fn build(self: Arc<Self>) -> Result<Arc<Client>, ClientBuildError> {
let builder = unwrap_or_clone_arc(self);
let mut inner_builder = MatrixClient::builder();
@@ -578,14 +413,16 @@ impl ClientBuilder {
inner_builder.cross_process_store_locks_holder_name(holder_name.clone());
}
if let Some(session_paths) = &builder.session_paths {
let store_path = if let Some(session_paths) = &builder.session_paths {
// This is the path where both the state store and the crypto store will live.
let data_path = Path::new(&session_paths.data_path);
// This is the path where the event cache store will live.
let cache_path = Path::new(&session_paths.cache_path);
debug!(
data_path = %data_path.to_string_lossy(),
cache_path = %cache_path.to_string_lossy(),
"Creating directories for data and cache stores.",
event_cache_path = %cache_path.to_string_lossy(),
"Creating directories for data (state and crypto) and cache stores.",
);
fs::create_dir_all(data_path)?;
@@ -614,9 +451,12 @@ impl ClientBuilder {
inner_builder = inner_builder
.sqlite_store_with_config_and_cache_path(sqlite_store_config, Some(cache_path));
Some(data_path.to_owned())
} else {
debug!("Not using a store path.");
}
None
};
// Determine server either from URL, server name or user ID.
inner_builder = match builder.homeserver_cfg {
@@ -640,52 +480,56 @@ impl ClientBuilder {
}
};
let mut certificates = Vec::new();
#[cfg(not(target_family = "wasm"))]
{
let mut certificates = Vec::new();
for certificate in builder.additional_root_certificates {
// We don't really know what type of certificate we may get here, so let's try
// first one type, then the other.
match Certificate::from_der(&certificate) {
Ok(cert) => {
certificates.push(cert);
}
Err(der_error) => {
let cert = Certificate::from_pem(&certificate).map_err(|pem_error| {
ClientBuildError::Generic {
message: format!("Failed to add a root certificate as DER ({der_error:?}) or PEM ({pem_error:?})"),
}
})?;
certificates.push(cert);
for certificate in builder.additional_root_certificates {
// We don't really know what type of certificate we may get here, so let's try
// first one type, then the other.
match Certificate::from_der(&certificate) {
Ok(cert) => {
certificates.push(cert);
}
Err(der_error) => {
let cert = Certificate::from_pem(&certificate).map_err(|pem_error| {
ClientBuildError::Generic {
message: format!("Failed to add a root certificate as DER ({der_error:?}) or PEM ({pem_error:?})"),
}
})?;
certificates.push(cert);
}
}
}
}
inner_builder = inner_builder.add_root_certificates(certificates);
inner_builder = inner_builder.add_root_certificates(certificates);
if builder.disable_built_in_root_certificates {
inner_builder = inner_builder.disable_built_in_root_certificates();
}
if builder.disable_built_in_root_certificates {
inner_builder = inner_builder.disable_built_in_root_certificates();
}
if let Some(proxy) = builder.proxy {
inner_builder = inner_builder.proxy(proxy);
}
if let Some(proxy) = builder.proxy {
inner_builder = inner_builder.proxy(proxy);
}
if builder.disable_ssl_verification {
inner_builder = inner_builder.disable_ssl_verification();
if builder.disable_ssl_verification {
inner_builder = inner_builder.disable_ssl_verification();
}
if let Some(user_agent) = builder.user_agent {
inner_builder = inner_builder.user_agent(user_agent);
}
}
if !builder.disable_automatic_token_refresh {
inner_builder = inner_builder.handle_refresh_tokens();
}
if let Some(user_agent) = builder.user_agent {
inner_builder = inner_builder.user_agent(user_agent);
}
inner_builder = inner_builder
.with_encryption_settings(builder.encryption_settings)
.with_room_key_recipient_strategy(builder.room_key_recipient_strategy)
.with_decryption_trust_requirement(builder.decryption_trust_requirement);
.with_decryption_settings(builder.decryption_settings)
.with_enable_share_history_on_invite(builder.enable_share_history_on_invite);
match builder.sliding_sync_version_builder {
SlidingSyncVersionBuilder::None => {
@@ -711,6 +555,7 @@ impl ClientBuilder {
if let Some(timeout) = config.timeout {
updated_config = updated_config.timeout(Duration::from_millis(timeout));
}
updated_config = updated_config.read_timeout(DEFAULT_READ_TIMEOUT);
if let Some(max_concurrent_requests) = config.max_concurrent_requests {
if max_concurrent_requests > 0 {
updated_config = updated_config.max_concurrent_requests(NonZeroUsize::new(
@@ -725,79 +570,75 @@ impl ClientBuilder {
inner_builder = inner_builder.request_config(updated_config);
}
inner_builder = inner_builder.with_threading_support(builder.threading_support);
let sdk_client = inner_builder.build().await?;
if builder.use_event_cache_persistent_storage {
// Enable the persistent storage \o/
sdk_client.event_cache().enable_storage()?;
// Disable retries for this request to prevent it from being retried
// indefinitely
let config = sdk_client.request_config().disable_retry();
// Log server version information at info level.
if let Ok(server_info) = sdk_client.server_vendor_info(Some(config)).await {
tracing::info!(
server_name = %server_info.server_name,
version = %server_info.version,
"Connected to Matrix server"
);
} else {
// Get rid of all the previous events, if any.
let store = sdk_client
.event_cache_store()
.lock()
.await
.map_err(EventCacheError::LockingStorage)?;
store.clear_all_rooms_chunks().await.map_err(EventCacheError::Storage)?;
tracing::warn!("Could not retrieve server version information");
}
Ok(Arc::new(
Client::new(sdk_client, builder.enable_oidc_refresh_lock, builder.session_delegate)
.await?,
Client::new(
sdk_client,
builder.enable_oidc_refresh_lock,
builder.session_delegate,
store_path,
)
.await?,
))
}
}
/// Finish the building of the client and attempt to log in using the
/// provided [`QrCodeData`].
///
/// This method will build the client and immediately attempt to log the
/// client in using the provided [`QrCodeData`] using the login
/// mechanism described in [MSC4108]. As such this methods requires OAuth
/// 2.0 support as well as sliding sync support.
///
/// The usage of the progress_listener is required to transfer the
/// [`CheckCode`] to the existing client.
///
/// [MSC4108]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108
pub async fn build_with_qr_code(
#[cfg(not(target_family = "wasm"))]
#[matrix_sdk_ffi_macros::export]
impl ClientBuilder {
pub fn proxy(self: Arc<Self>, url: String) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.proxy = Some(url);
Arc::new(builder)
}
pub fn disable_ssl_verification(self: Arc<Self>) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.disable_ssl_verification = true;
Arc::new(builder)
}
pub fn add_root_certificates(
self: Arc<Self>,
qr_code_data: &QrCodeData,
oidc_configuration: &OidcConfiguration,
progress_listener: Box<dyn QrLoginProgressListener>,
) -> Result<Arc<Client>, HumanQrLoginError> {
let QrCodeModeData::Reciprocate { server_name } = &qr_code_data.inner.mode_data else {
return Err(HumanQrLoginError::OtherDeviceNotSignedIn);
};
certificates: Vec<CertificateBytes>,
) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.additional_root_certificates = certificates;
let builder = self.server_name_or_homeserver_url(server_name.to_owned());
Arc::new(builder)
}
let client = builder.build().await.map_err(|e| match e {
ClientBuildError::SlidingSync(_) => HumanQrLoginError::SlidingSyncNotAvailable,
_ => {
error!("Couldn't build the client {e:?}");
HumanQrLoginError::Unknown
}
})?;
/// Don't trust any system root certificates, only trust the certificates
/// provided through
/// [`add_root_certificates`][ClientBuilder::add_root_certificates].
pub fn disable_built_in_root_certificates(self: Arc<Self>) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.disable_built_in_root_certificates = true;
Arc::new(builder)
}
let registration_data = oidc_configuration
.registration_data()
.map_err(|_| HumanQrLoginError::OidcMetadataInvalid)?;
let oauth = client.inner.oauth();
let login = oauth.login_with_qr_code(&qr_code_data.inner, Some(&registration_data));
let mut progress = login.subscribe_to_progress();
// We create this task, which will get cancelled once it's dropped, just in case
// the progress stream doesn't end.
let _progress_task = TaskHandle::new(get_runtime_handle().spawn(async move {
while let Some(state) = progress.next().await {
progress_listener.on_update(state.into());
}
}));
login.await?;
Ok(client)
pub fn user_agent(self: Arc<Self>, user_agent: String) -> Arc<Self> {
let mut builder = unwrap_or_clone_arc(self);
builder.user_agent = Some(user_agent);
Arc::new(builder)
}
}
-22
View File
@@ -1,22 +0,0 @@
use serde::Deserialize;
use crate::ClientError;
/// Well-known settings specific to ElementCall
#[derive(Deserialize, uniffi::Record)]
pub struct ElementCallWellKnown {
widget_url: String,
}
/// Element specific well-known settings
#[derive(Deserialize, uniffi::Record)]
pub struct ElementWellKnown {
call: Option<ElementCallWellKnown>,
registration_helper_url: Option<String>,
}
/// Helper function to parse a string into a ElementWellKnown struct
#[matrix_sdk_ffi_macros::export]
pub fn make_element_well_known(string: String) -> Result<ElementWellKnown, ClientError> {
serde_json::from_str(&string).map_err(ClientError::new)
}
+16 -20
View File
@@ -1,16 +1,19 @@
use std::sync::Arc;
use async_compat::get_runtime_handle;
use futures_util::StreamExt;
use matrix_sdk::{
encryption,
encryption::{backups, recovery},
};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use thiserror::Error;
use tracing::{error, info};
use zeroize::Zeroize;
use crate::{client::Client, error::ClientError, ruma::AuthData, task_handle::TaskHandle};
use crate::{
client::Client, error::ClientError, ruma::AuthData, runtime::get_runtime_handle,
task_handle::TaskHandle,
};
#[derive(uniffi::Object)]
pub struct Encryption {
@@ -25,22 +28,22 @@ pub struct Encryption {
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait BackupStateListener: Sync + Send {
pub trait BackupStateListener: SyncOutsideWasm + SendOutsideWasm {
fn on_update(&self, status: BackupState);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait BackupSteadyStateListener: Sync + Send {
pub trait BackupSteadyStateListener: SyncOutsideWasm + SendOutsideWasm {
fn on_update(&self, status: BackupUploadState);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RecoveryStateListener: Sync + Send {
pub trait RecoveryStateListener: SyncOutsideWasm + SendOutsideWasm {
fn on_update(&self, status: RecoveryState);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait VerificationStateListener: Sync + Send {
pub trait VerificationStateListener: SyncOutsideWasm + SendOutsideWasm {
fn on_update(&self, status: VerificationState);
}
@@ -164,7 +167,7 @@ impl From<recovery::RecoveryState> for RecoveryState {
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait EnableRecoveryProgressListener: Sync + Send {
pub trait EnableRecoveryProgressListener: SyncOutsideWasm + SendOutsideWasm {
fn on_update(&self, status: EnableRecoveryProgress);
}
@@ -369,12 +372,8 @@ impl Encryption {
/// Completely reset the current user's crypto identity: reset the cross
/// signing keys, delete the existing backup and recovery key.
pub async fn reset_identity(&self) -> Result<Option<Arc<IdentityResetHandle>>, ClientError> {
if let Some(reset_handle) = self
.inner
.recovery()
.reset_identity()
.await
.map_err(|e| ClientError::Generic { msg: e.to_string() })?
if let Some(reset_handle) =
self.inner.recovery().reset_identity().await.map_err(ClientError::from_err)?
{
return Ok(Some(Arc::new(IdentityResetHandle { inner: reset_handle })));
}
@@ -441,9 +440,9 @@ impl Encryption {
info!("No identity found in the store.");
}
Err(error) => {
error!("Failed fetching identity from the store: {}", error);
error!("Failed fetching identity from the store: {error}");
}
};
}
info!("Requesting identity from the server.");
@@ -541,12 +540,9 @@ impl IdentityResetHandle {
/// 4. Finally, re-enable key backups only if they were enabled before
pub async fn reset(&self, auth: Option<AuthData>) -> Result<(), ClientError> {
if let Some(auth) = auth {
self.inner
.reset(Some(auth.into()))
.await
.map_err(|e| ClientError::Generic { msg: e.to_string() })
self.inner.reset(Some(auth.into())).await.map_err(ClientError::from_err)
} else {
self.inner.reset(None).await.map_err(|e| ClientError::Generic { msg: e.to_string() })
self.inner.reset(None).await.map_err(ClientError::from_err)
}
}
+65 -37
View File
@@ -1,13 +1,21 @@
use std::{collections::HashMap, fmt, fmt::Display, time::SystemTime};
use std::{collections::HashMap, error::Error, fmt, fmt::Display};
use matrix_sdk::{
authentication::oauth::OAuthError, encryption::CryptoStoreError, event_cache::EventCacheError,
reqwest, room::edit::EditError, send_queue::RoomSendQueueError, HttpError, IdParseError,
NotificationSettingsError as SdkNotificationSettingsError,
authentication::oauth::OAuthError,
encryption::{identities::RequestVerificationError, CryptoStoreError},
event_cache::EventCacheError,
reqwest,
room::edit::EditError,
send_queue::RoomSendQueueError,
HttpError, IdParseError, NotificationSettingsError as SdkNotificationSettingsError,
QueueWedgeError as SdkQueueWedgeError, StoreError,
};
use matrix_sdk_ui::{encryption_sync_service, notification_client, sync_service, timeline};
use ruma::api::client::error::{ErrorBody, ErrorKind as RumaApiErrorKind, RetryAfter};
use ruma::{
api::client::error::{ErrorBody, ErrorKind as RumaApiErrorKind, RetryAfter},
MilliSecondsSinceUnixEpoch,
};
use tracing::warn;
use uniffi::UnexpectedUniFFICallbackError;
use crate::{room_list::RoomListError, timeline::FocusEventError};
@@ -15,32 +23,39 @@ use crate::{room_list::RoomListError, timeline::FocusEventError};
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum ClientError {
#[error("client error: {msg}")]
Generic { msg: String },
Generic { msg: String, details: Option<String> },
#[error("api error {code}: {msg}")]
MatrixApi { kind: ErrorKind, code: String, msg: String },
MatrixApi { kind: ErrorKind, code: String, msg: String, details: Option<String> },
}
impl ClientError {
pub(crate) fn new<E: Display>(error: E) -> Self {
Self::Generic { msg: error.to_string() }
pub(crate) fn from_str<E: Display>(error: E, details: Option<String>) -> Self {
warn!("Error: {error}");
Self::Generic { msg: error.to_string(), details }
}
pub(crate) fn from_err<E: Error>(e: E) -> Self {
let details = Some(format!("{e:?}"));
Self::from_str(e, details)
}
}
impl From<anyhow::Error> for ClientError {
fn from(e: anyhow::Error) -> ClientError {
ClientError::Generic { msg: format!("{e:#}") }
let details = format!("{e:?}");
ClientError::Generic { msg: format!("{e:#}"), details: Some(details) }
}
}
impl From<reqwest::Error> for ClientError {
fn from(e: reqwest::Error) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<UnexpectedUniFFICallbackError> for ClientError {
fn from(e: UnexpectedUniFFICallbackError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
@@ -53,135 +68,146 @@ impl From<matrix_sdk::Error> for ClientError {
let code = kind.errcode().to_string();
let Ok(kind) = kind.to_owned().try_into() else {
// We couldn't parse the API error, so we return a generic one instead
return Self::Generic { msg: message.to_string() };
return (*http_error).into();
};
return Self::MatrixApi {
kind,
code,
msg: message.to_owned(),
details: Some(format!("{api_error:?}")),
};
return Self::MatrixApi { kind, code, msg: message.to_owned() };
}
}
Self::Generic { msg: http_error.to_string() }
(*http_error).into()
}
_ => Self::Generic { msg: e.to_string() },
_ => Self::from_err(e),
}
}
}
impl From<StoreError> for ClientError {
fn from(e: StoreError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<CryptoStoreError> for ClientError {
fn from(e: CryptoStoreError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<HttpError> for ClientError {
fn from(e: HttpError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<IdParseError> for ClientError {
fn from(e: IdParseError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<serde_json::Error> for ClientError {
fn from(e: serde_json::Error) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<url::ParseError> for ClientError {
fn from(e: url::ParseError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<mime::FromStrError> for ClientError {
fn from(e: mime::FromStrError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<encryption_sync_service::Error> for ClientError {
fn from(e: encryption_sync_service::Error) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<timeline::Error> for ClientError {
fn from(e: timeline::Error) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<timeline::UnsupportedEditItem> for ClientError {
fn from(e: timeline::UnsupportedEditItem) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<notification_client::Error> for ClientError {
fn from(e: notification_client::Error) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<sync_service::Error> for ClientError {
fn from(e: sync_service::Error) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<OAuthError> for ClientError {
fn from(e: OAuthError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<RoomError> for ClientError {
fn from(e: RoomError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<RoomListError> for ClientError {
fn from(e: RoomListError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<EventCacheError> for ClientError {
fn from(e: EventCacheError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<EditError> for ClientError {
fn from(e: EditError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<RoomSendQueueError> for ClientError {
fn from(e: RoomSendQueueError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<NotYetImplemented> for ClientError {
fn from(_: NotYetImplemented) -> Self {
Self::new("This functionality is not implemented yet.")
Self::from_str("This functionality is not implemented yet.", None)
}
}
impl From<FocusEventError> for ClientError {
fn from(e: FocusEventError) -> Self {
Self::new(e)
Self::from_err(e)
}
}
impl From<RequestVerificationError> for ClientError {
fn from(e: RequestVerificationError) -> Self {
Self::from_err(e)
}
}
@@ -736,7 +762,9 @@ impl TryFrom<RumaApiErrorKind> for ErrorKind {
let retry_after_ms = match retry_after {
Some(RetryAfter::Delay(duration)) => Some(duration.as_millis() as u64),
Some(RetryAfter::DateTime(system_time)) => {
let duration = system_time.duration_since(SystemTime::now()).ok();
let duration = MilliSecondsSinceUnixEpoch::now()
.to_system_time()
.and_then(|now| system_time.duration_since(now).ok());
duration.map(|duration| duration.as_millis() as u64)
}
None => None,
+33 -7
View File
@@ -1,3 +1,5 @@
use std::ops::Deref;
use anyhow::{bail, Context};
use matrix_sdk::IdParseError;
use matrix_sdk_ui::timeline::TimelineEventItemId;
@@ -22,7 +24,7 @@ use crate::{
};
#[derive(uniffi::Object)]
pub struct TimelineEvent(pub(crate) AnySyncTimelineEvent);
pub struct TimelineEvent(pub(crate) Box<AnySyncTimelineEvent>);
#[matrix_sdk_ffi_macros::export]
impl TimelineEvent {
@@ -39,7 +41,7 @@ impl TimelineEvent {
}
pub fn event_type(&self) -> Result<TimelineEventType, ClientError> {
let event_type = match &self.0 {
let event_type = match self.0.deref() {
AnySyncTimelineEvent::MessageLike(event) => {
TimelineEventType::MessageLike { content: event.clone().try_into()? }
}
@@ -53,11 +55,19 @@ impl TimelineEvent {
impl From<AnyTimelineEvent> for TimelineEvent {
fn from(event: AnyTimelineEvent) -> Self {
Self(event.into())
Self(Box::new(event.into()))
}
}
#[derive(uniffi::Enum)]
// A note about this `allow(clippy::large_enum_variant)`.
// In order to reduce the size of `TimelineEventType`, we would need to
// put some parts in a `Box`, or an `Arc`. Sadly, it doesn't play well with
// UniFFI. We would need to change the `uniffi::Record` of the subtypes into
// `uniffi::Object`, which is a radical change. It would simplify the memory
// usage, but it would slow down the performance around the FFI border. Thus,
// let's consider this is a false-positive lint in this particular case.
#[allow(clippy::large_enum_variant)]
pub enum TimelineEventType {
MessageLike { content: MessageLikeEventContent },
State { content: StateEventContent },
@@ -83,7 +93,7 @@ pub enum StateEventContent {
RoomServerAcl,
RoomThirdPartyInvite,
RoomTombstone,
RoomTopic,
RoomTopic { topic: String },
SpaceChild,
SpaceParent,
}
@@ -118,16 +128,28 @@ impl TryFrom<AnySyncStateEvent> for StateEventContent {
AnySyncStateEvent::RoomServerAcl(_) => StateEventContent::RoomServerAcl,
AnySyncStateEvent::RoomThirdPartyInvite(_) => StateEventContent::RoomThirdPartyInvite,
AnySyncStateEvent::RoomTombstone(_) => StateEventContent::RoomTombstone,
AnySyncStateEvent::RoomTopic(_) => StateEventContent::RoomTopic,
AnySyncStateEvent::RoomTopic(content) => {
let content = get_state_event_original_content(content)?;
StateEventContent::RoomTopic { topic: content.topic }
}
AnySyncStateEvent::SpaceChild(_) => StateEventContent::SpaceChild,
AnySyncStateEvent::SpaceParent(_) => StateEventContent::SpaceParent,
_ => bail!("Unsupported state event"),
_ => bail!("Unsupported state event: {:?}", value.event_type()),
};
Ok(event)
}
}
#[derive(uniffi::Enum)]
// A note about this `allow(clippy::large_enum_variant)`.
// In order to reduce the size of `MessageLineEventContent`, we would need to
// put some parts in a `Box`, or an `Arc`. Sadly, it doesn't play well with
// UniFFI. We would need to change the `uniffi::Record` of the subtypes into
// `uniffi::Object`, which is a radical change. It would simplify the memory
// usage, but it would slow down the performance around the FFI border. Thus,
// let's consider this is a false-positive lint in this particular case.
#[allow(clippy::large_enum_variant)]
pub enum MessageLikeEventContent {
CallAnswer,
CallInvite,
@@ -222,7 +244,7 @@ impl TryFrom<AnySyncMessageLikeEvent> for MessageLikeEventContent {
MessageLikeEventContent::RoomRedaction { redacted_event_id, reason }
}
AnySyncMessageLikeEvent::Sticker(_) => MessageLikeEventContent::Sticker,
_ => bail!("Unsupported Event Type"),
_ => bail!("Unsupported Event Type: {:?}", value.event_type()),
};
Ok(content)
}
@@ -365,6 +387,8 @@ pub enum RoomMessageEventMessageType {
Audio,
Emote,
File,
#[cfg(feature = "unstable-msc4274")]
Gallery,
Image,
Location,
Notice,
@@ -381,6 +405,8 @@ impl From<RumaMessageType> for RoomMessageEventMessageType {
RumaMessageType::Audio { .. } => Self::Audio,
RumaMessageType::Emote { .. } => Self::Emote,
RumaMessageType::File { .. } => Self::File,
#[cfg(feature = "unstable-msc4274")]
RumaMessageType::Gallery { .. } => Self::Gallery,
RumaMessageType::Image { .. } => Self::Image,
RumaMessageType::Location { .. } => Self::Location,
RumaMessageType::Notice { .. } => Self::Notice,
+6 -6
View File
@@ -1,14 +1,11 @@
// TODO: target-os conditional would be good.
#![allow(unused_qualifications, clippy::new_without_default)]
#![allow(clippy::empty_line_after_doc_comments)] // Needed because uniffi macros contain empty
// lines after docs.
// Needed because uniffi macros contain empty lines after docs.
#![allow(clippy::empty_line_after_doc_comments)]
mod authentication;
mod chunk_iterator;
mod client;
mod client_builder;
mod element;
mod encryption;
mod error;
mod event;
@@ -18,19 +15,22 @@ mod live_location_share;
mod notification;
mod notification_settings;
mod platform;
mod qr_code;
mod room;
mod room_alias;
mod room_directory_search;
mod room_info;
mod room_list;
mod room_member;
mod room_preview;
mod ruma;
mod runtime;
mod session_verification;
mod spaces;
mod sync_service;
mod task_handle;
mod timeline;
mod tracing;
mod utd;
mod utils;
mod widget;
+130 -18
View File
@@ -1,14 +1,16 @@
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};
use matrix_sdk_ui::notification_client::{
NotificationClient as MatrixNotificationClient, NotificationItem as MatrixNotificationItem,
NotificationClient as SdkNotificationClient, NotificationEvent as SdkNotificationEvent,
NotificationItem as SdkNotificationItem, NotificationStatus as SdkNotificationStatus,
};
use ruma::{EventId, RoomId};
use ruma::{EventId, OwnedEventId, OwnedRoomId, RoomId};
use crate::{
client::{Client, JoinRule},
error::ClientError,
event::TimelineEvent,
room::Room,
};
#[derive(uniffi::Enum)]
@@ -29,11 +31,11 @@ pub struct NotificationRoomInfo {
pub display_name: String,
pub avatar_url: Option<String>,
pub canonical_alias: Option<String>,
pub topic: Option<String>,
pub join_rule: Option<JoinRule>,
pub joined_members_count: u64,
pub is_encrypted: Option<bool>,
pub is_direct: bool,
pub is_public: bool,
}
#[derive(uniffi::Record)]
@@ -52,12 +54,12 @@ pub struct NotificationItem {
}
impl NotificationItem {
fn from_inner(item: MatrixNotificationItem) -> Self {
fn from_inner(item: SdkNotificationItem) -> Self {
let event = match item.event {
matrix_sdk_ui::notification_client::NotificationEvent::Timeline(event) => {
SdkNotificationEvent::Timeline(event) => {
NotificationEvent::Timeline { event: Arc::new(TimelineEvent(event)) }
}
matrix_sdk_ui::notification_client::NotificationEvent::Invite(event) => {
SdkNotificationEvent::Invite(event) => {
NotificationEvent::Invite { sender: event.sender.to_string() }
}
};
@@ -72,11 +74,11 @@ impl NotificationItem {
display_name: item.room_computed_display_name,
avatar_url: item.room_avatar_url,
canonical_alias: item.room_canonical_alias,
join_rule: item.room_join_rule.try_into().ok(),
topic: item.room_topic,
join_rule: item.room_join_rule.map(TryInto::try_into).transpose().ok().flatten(),
joined_members_count: item.joined_members_count,
is_encrypted: item.is_room_encrypted,
is_direct: item.is_direct_message_room,
is_public: item.is_room_public,
},
is_noisy: item.is_noisy,
has_mention: item.has_mention,
@@ -85,37 +87,147 @@ impl NotificationItem {
}
}
#[allow(clippy::large_enum_variant)]
#[derive(uniffi::Enum)]
pub enum NotificationStatus {
/// The event has been found and was not filtered out.
Event { item: NotificationItem },
/// The event couldn't be found in the network queries used to find it.
EventNotFound,
/// The event has been filtered out, either because of the user's push
/// rules, or because the user which triggered it is ignored by the
/// current user.
EventFilteredOut,
}
impl From<SdkNotificationStatus> for NotificationStatus {
fn from(item: SdkNotificationStatus) -> Self {
match item {
SdkNotificationStatus::Event(item) => {
NotificationStatus::Event { item: NotificationItem::from_inner(*item) }
}
SdkNotificationStatus::EventNotFound => NotificationStatus::EventNotFound,
SdkNotificationStatus::EventFilteredOut => NotificationStatus::EventFilteredOut,
}
}
}
#[allow(clippy::large_enum_variant)]
#[derive(uniffi::Enum)]
pub enum BatchNotificationResult {
/// We have more detailed information about the notification.
Ok { status: NotificationStatus },
/// An error occurred while trying to fetch the notification.
Error {
/// The error message observed while handling a specific notification.
message: String,
},
}
#[derive(uniffi::Object)]
pub struct NotificationClient {
pub(crate) inner: MatrixNotificationClient,
pub(crate) inner: SdkNotificationClient,
/// A reference to the FFI client.
///
/// Note: we do this to make it so that the FFI `NotificationClient` keeps
/// the FFI `Client` and thus the SDK `Client` alive. Otherwise, we
/// would need to repeat the hack done in the FFI `Client::drop` method.
pub(crate) _client: Arc<Client>,
pub(crate) client: Arc<Client>,
}
#[matrix_sdk_ffi_macros::export]
impl NotificationClient {
/// See also documentation of
/// `MatrixNotificationClient::get_notification`.
/// Fetches a room by its ID using the in-memory state store backed client.
///
/// Useful to retrieve room information after running the limited
/// notification client sliding sync loop.
pub fn get_room(&self, room_id: String) -> Result<Option<Arc<Room>>, ClientError> {
let room_id = RoomId::parse(room_id)?;
let sdk_room = self.inner.get_room(&room_id);
let room = sdk_room
.map(|room| Arc::new(Room::new(room, self.client.utd_hook_manager.get().cloned())));
Ok(room)
}
/// Fetches the content of a notification.
///
/// This will first try to get the notification using a short-lived sliding
/// sync, and if the sliding-sync can't find the event, then it'll use a
/// `/context` query to find the event with associated member information.
///
/// An error result means that we couldn't resolve the notification; in that
/// case, a dummy notification may be displayed instead.
pub async fn get_notification(
&self,
room_id: String,
event_id: String,
) -> Result<Option<NotificationItem>, ClientError> {
) -> Result<NotificationStatus, ClientError> {
let room_id = RoomId::parse(room_id)?;
let event_id = EventId::parse(event_id)?;
let item =
self.inner.get_notification(&room_id, &event_id).await.map_err(ClientError::from)?;
if let Some(item) = item {
Ok(Some(NotificationItem::from_inner(item)))
} else {
Ok(None)
Ok(item.into())
}
/// Get several notification items in a single batch.
///
/// Returns an error if the flow failed when preparing to fetch the
/// notifications, and a [`HashMap`] containing either a
/// [`BatchNotificationResult`], that indicates if the notification was
/// successfully fetched (in which case, it's a [`NotificationStatus`]), or
/// an error message if it couldn't be fetched.
pub async fn get_notifications(
&self,
requests: Vec<NotificationItemsRequest>,
) -> Result<HashMap<String, BatchNotificationResult>, ClientError> {
let requests =
requests.into_iter().map(TryInto::try_into).collect::<Result<Vec<_>, _>>()?;
let items = self.inner.get_notifications(&requests).await?;
let mut batch_result = HashMap::new();
for (key, value) in items.into_iter() {
let result = match value {
Ok(status) => BatchNotificationResult::Ok { status: status.into() },
Err(error) => BatchNotificationResult::Error { message: error.to_string() },
};
batch_result.insert(key.to_string(), result);
}
Ok(batch_result)
}
}
/// A request for notification items grouped by their room.
#[derive(uniffi::Record)]
pub struct NotificationItemsRequest {
room_id: String,
event_ids: Vec<String>,
}
impl NotificationItemsRequest {
/// The parsed [`OwnedRoomId`] to use with the SDK crates.
pub fn room_id(&self) -> Result<OwnedRoomId, ClientError> {
RoomId::parse(&self.room_id).map_err(ClientError::from)
}
/// The parsed [`OwnedEventId`] list to use with the SDK crates.
pub fn event_ids(&self) -> Result<Vec<OwnedEventId>, ClientError> {
self.event_ids
.iter()
.map(|id| EventId::parse(id).map_err(ClientError::from))
.collect::<Result<Vec<_>, _>>()
}
}
impl TryFrom<NotificationItemsRequest>
for matrix_sdk_ui::notification_client::NotificationItemsRequest
{
type Error = ClientError;
fn try_from(value: NotificationItemsRequest) -> Result<Self, Self::Error> {
Ok(Self { room_id: value.room_id()?, event_ids: value.event_ids()? })
}
}
@@ -9,6 +9,7 @@ use matrix_sdk::{
ruma::events::push_rules::PushRulesEvent,
Client as MatrixClient,
};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use ruma::{
push::{
Action as SdkAction, ComparisonOperator as SdkComparisonOperator, PredefinedOverrideRuleId,
@@ -161,7 +162,7 @@ pub enum PushCondition {
}
impl TryFrom<SdkPushCondition> for PushCondition {
type Error = ();
type Error = String;
fn try_from(value: SdkPushCondition) -> Result<Self, Self::Error> {
Ok(match value {
@@ -171,7 +172,7 @@ impl TryFrom<SdkPushCondition> for PushCondition {
Self::RoomMemberCount { prefix: is.prefix.into(), count: is.count.into() }
}
SdkPushCondition::SenderNotificationPermission { key } => {
Self::SenderNotificationPermission { key }
Self::SenderNotificationPermission { key: key.to_string() }
}
SdkPushCondition::EventPropertyIs { key, value } => {
Self::EventPropertyIs { key, value: value.into() }
@@ -179,7 +180,7 @@ impl TryFrom<SdkPushCondition> for PushCondition {
SdkPushCondition::EventPropertyContains { key, value } => {
Self::EventPropertyContains { key, value: value.into() }
}
_ => return Err(()),
_ => return Err("Unsupported condition type".to_owned()),
})
}
}
@@ -196,7 +197,7 @@ impl From<PushCondition> for SdkPushCondition {
},
},
PushCondition::SenderNotificationPermission { key } => {
Self::SenderNotificationPermission { key }
Self::SenderNotificationPermission { key: key.into() }
}
PushCondition::EventPropertyIs { key, value } => {
Self::EventPropertyIs { key, value: value.into() }
@@ -290,7 +291,7 @@ impl TryFrom<SdkTweak> for Tweak {
SdkTweak::Highlight(highlight) => Self::Highlight { value: highlight },
SdkTweak::Custom { name, value } => {
let json_string = serde_json::to_string(&value)
.map_err(|e| format!("Failed to serialize custom tweak value: {}", e))?;
.map_err(|e| format!("Failed to serialize custom tweak value: {e}"))?;
Self::Custom { name, value: json_string }
}
@@ -308,9 +309,9 @@ impl TryFrom<Tweak> for SdkTweak {
Tweak::Highlight { value } => Self::Highlight(value),
Tweak::Custom { name, value } => {
let json_value: serde_json::Value = serde_json::from_str(&value)
.map_err(|e| format!("Failed to deserialize custom tweak value: {}", e))?;
.map_err(|e| format!("Failed to deserialize custom tweak value: {e}"))?;
let value = serde_json::from_value(json_value)
.map_err(|e| format!("Failed to convert JSON value: {}", e))?;
.map_err(|e| format!("Failed to convert JSON value: {e}"))?;
Self::Custom { name, value }
}
@@ -334,7 +335,7 @@ impl TryFrom<SdkAction> for Action {
Ok(match value {
SdkAction::Notify => Self::Notify,
SdkAction::SetTweak(tweak) => Self::SetTweak {
value: tweak.try_into().map_err(|e| format!("Failed to convert tweak: {}", e))?,
value: tweak.try_into().map_err(|e| format!("Failed to convert tweak: {e}"))?,
},
_ => return Err("Unsupported action type".to_owned()),
})
@@ -348,7 +349,7 @@ impl TryFrom<Action> for SdkAction {
Ok(match value {
Action::Notify => Self::Notify,
Action::SetTweak { value } => Self::SetTweak(
value.try_into().map_err(|e| format!("Failed to convert tweak: {}", e))?,
value.try_into().map_err(|e| format!("Failed to convert tweak: {e}"))?,
),
})
}
@@ -387,7 +388,7 @@ impl From<RoomNotificationMode> for SdkRoomNotificationMode {
/// Delegate to notify of changes in push rules
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait NotificationSettingsDelegate: Sync + Send {
pub trait NotificationSettingsDelegate: SyncOutsideWasm + SendOutsideWasm {
fn settings_did_change(&self);
}
+426 -186
View File
@@ -1,3 +1,9 @@
use std::sync::OnceLock;
#[cfg(feature = "sentry")]
use std::sync::{atomic::AtomicBool, Arc};
#[cfg(feature = "sentry")]
use tracing::warn;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_core::Subscriber;
use tracing_subscriber::{
@@ -8,170 +14,158 @@ use tracing_subscriber::{
time::FormatTime,
FormatEvent, FormatFields, FormattedFields,
},
layer::SubscriberExt,
layer::{Layered, SubscriberExt as _},
registry::LookupSpan,
util::SubscriberInitExt,
EnvFilter, Layer,
reload::{self, Handle},
util::SubscriberInitExt as _,
EnvFilter, Layer, Registry,
};
use crate::tracing::LogLevel;
use crate::{error::ClientError, tracing::LogLevel};
pub fn log_panics() {
std::env::set_var("RUST_BACKTRACE", "1");
log_panics::init();
// Adjusted version of tracing_subscriber::fmt::Format
struct EventFormatter {
display_timestamp: bool,
display_level: bool,
}
fn text_layers<S>(config: TracingConfiguration) -> impl Layer<S>
impl EventFormatter {
fn new() -> Self {
Self { display_timestamp: true, display_level: true }
}
#[cfg(target_os = "android")]
fn for_logcat() -> Self {
// Level and time are already captured by logcat separately
Self { display_timestamp: false, display_level: false }
}
fn format_timestamp(&self, writer: &mut fmt::format::Writer<'_>) -> std::fmt::Result {
if fmt::time::SystemTime.format_time(writer).is_err() {
writer.write_str("<unknown time>")?;
}
Ok(())
}
fn write_filename(
&self,
writer: &mut fmt::format::Writer<'_>,
filename: &str,
) -> std::fmt::Result {
const CRATES_IO_PATH_MATCHER: &str = ".cargo/registry/src/index.crates.io";
let crates_io_filename = filename
.split_once(CRATES_IO_PATH_MATCHER)
.and_then(|(_, rest)| rest.split_once('/').map(|(_, rest)| rest));
if let Some(filename) = crates_io_filename {
writer.write_str("<crates.io>/")?;
writer.write_str(filename)
} else {
writer.write_str(filename)
}
}
}
impl<S, N> FormatEvent<S, N> for EventFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
// Adjusted version of tracing_subscriber::fmt::Format
struct EventFormatter {
display_timestamp: bool,
display_level: bool,
}
fn format_event(
&self,
ctx: &fmt::FmtContext<'_, S, N>,
mut writer: fmt::format::Writer<'_>,
event: &tracing_core::Event<'_>,
) -> std::fmt::Result {
let meta = event.metadata();
impl EventFormatter {
fn new() -> Self {
Self { display_timestamp: true, display_level: true }
if self.display_timestamp {
self.format_timestamp(&mut writer)?;
writer.write_char(' ')?;
}
#[cfg(target_os = "android")]
fn for_logcat() -> Self {
// Level and time are already captured by logcat separately
Self { display_timestamp: false, display_level: false }
if self.display_level {
// For info and warn, add a padding space to the left
write!(writer, "{:>5} ", meta.level())?;
}
fn format_timestamp(&self, writer: &mut fmt::format::Writer<'_>) -> std::fmt::Result {
if fmt::time::SystemTime.format_time(writer).is_err() {
writer.write_str("<unknown time>")?;
}
Ok(())
}
write!(writer, "{}: ", meta.target())?;
fn write_filename(
&self,
writer: &mut fmt::format::Writer<'_>,
filename: &str,
) -> std::fmt::Result {
const CRATES_IO_PATH_MATCHER: &str = ".cargo/registry/src/index.crates.io";
let crates_io_filename = filename
.split_once(CRATES_IO_PATH_MATCHER)
.and_then(|(_, rest)| rest.split_once('/').map(|(_, rest)| rest));
ctx.format_fields(writer.by_ref(), event)?;
if let Some(filename) = crates_io_filename {
writer.write_str("<crates.io>/")?;
writer.write_str(filename)
} else {
writer.write_str(filename)
if let Some(filename) = meta.file() {
writer.write_str(" | ")?;
self.write_filename(&mut writer, filename)?;
if let Some(line_number) = meta.line() {
write!(writer, ":{line_number}")?;
}
}
}
impl<S, N> FormatEvent<S, N> for EventFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &fmt::FmtContext<'_, S, N>,
mut writer: fmt::format::Writer<'_>,
event: &tracing_core::Event<'_>,
) -> std::fmt::Result {
let meta = event.metadata();
if let Some(scope) = ctx.event_scope() {
writer.write_str(" | spans: ")?;
if self.display_timestamp {
self.format_timestamp(&mut writer)?;
writer.write_char(' ')?;
}
let mut first = true;
if self.display_level {
// For info and warn, add a padding space to the left
write!(writer, "{:>5} ", meta.level())?;
}
write!(writer, "{}: ", meta.target())?;
ctx.format_fields(writer.by_ref(), event)?;
if let Some(filename) = meta.file() {
writer.write_str(" | ")?;
self.write_filename(&mut writer, filename)?;
if let Some(line_number) = meta.line() {
write!(writer, ":{line_number}")?;
for span in scope.from_root() {
if !first {
writer.write_str(" > ")?;
}
}
if let Some(scope) = ctx.event_scope() {
writer.write_str(" | spans: ")?;
first = false;
let mut first = true;
write!(writer, "{}", span.name())?;
for span in scope.from_root() {
if !first {
writer.write_str(" > ")?;
}
first = false;
write!(writer, "{}", span.name())?;
if let Some(fields) = &span.extensions().get::<FormattedFields<N>>() {
if !fields.is_empty() {
write!(writer, "{{{fields}}}")?;
}
if let Some(fields) = &span.extensions().get::<FormattedFields<N>>() {
if !fields.is_empty() {
write!(writer, "{{{fields}}}")?;
}
}
}
writeln!(writer)
}
writeln!(writer)
}
}
let file_layer = config.write_to_files.map(|c| {
let mut builder = RollingFileAppender::builder()
.rotation(Rotation::HOURLY)
.filename_prefix(&c.file_prefix);
// Another fields formatter is necessary because of this bug
// https://github.com/tokio-rs/tracing/issues/1372. Using a new
// formatter for the fields forces to record them in different span
// extensions, and thus remove the duplicated fields in the span.
#[derive(Default)]
struct FieldsFormatterForFiles(DefaultFields);
if let Some(max_files) = c.max_files {
builder = builder.max_log_files(max_files as usize)
};
if let Some(file_suffix) = c.file_suffix {
builder = builder.filename_suffix(file_suffix)
}
impl<'writer> FormatFields<'writer> for FieldsFormatterForFiles {
fn format_fields<R: RecordFields>(
&self,
writer: Writer<'writer>,
fields: R,
) -> std::fmt::Result {
self.0.format_fields(writer, fields)
}
}
let writer = builder.build(&c.path).expect("Failed to create a rolling file appender.");
type ReloadHandle = Handle<
tracing_subscriber::fmt::Layer<
Layered<EnvFilter, Registry>,
FieldsFormatterForFiles,
EventFormatter,
RollingFileAppender,
>,
Layered<EnvFilter, Registry>,
>;
// Another fields formatter is necessary because of this bug
// https://github.com/tokio-rs/tracing/issues/1372. Using a new
// formatter for the fields forces to record them in different span
// extensions, and thus remove the duplicated fields in the span.
#[derive(Default)]
struct FieldsFormatterForFiles(DefaultFields);
fn text_layers(
config: TracingConfiguration,
) -> (impl Layer<Layered<EnvFilter, Registry>>, Option<ReloadHandle>) {
let (file_layer, reload_handle) = config
.write_to_files
.map(|c| {
let layer = make_file_layer(c);
reload::Layer::new(layer)
})
.unzip();
impl<'writer> FormatFields<'writer> for FieldsFormatterForFiles {
fn format_fields<R: RecordFields>(
&self,
writer: Writer<'writer>,
fields: R,
) -> std::fmt::Result {
self.0.format_fields(writer, fields)
}
}
fmt::layer()
.fmt_fields(FieldsFormatterForFiles::default())
.event_format(EventFormatter::new())
// EventFormatter doesn't support ANSI colors anyways, but the
// default field formatter does, which is unhelpful for iOS +
// Android logs, but enabled by default.
.with_ansi(false)
.with_writer(writer)
});
Layer::and_then(
let layers = Layer::and_then(
file_layer,
config.write_to_stdout_or_system.then(|| {
// Another fields formatter is necessary because of this bug
@@ -209,7 +203,41 @@ where
"org.matrix.rust.sdk".to_owned(),
));
}),
)
);
(layers, reload_handle)
}
fn make_file_layer(
file_configuration: TracingFileConfiguration,
) -> tracing_subscriber::fmt::Layer<
Layered<EnvFilter, Registry, Registry>,
FieldsFormatterForFiles,
EventFormatter,
RollingFileAppender,
> {
let mut builder = RollingFileAppender::builder()
.rotation(Rotation::HOURLY)
.filename_prefix(&file_configuration.file_prefix);
if let Some(max_files) = file_configuration.max_files {
builder = builder.max_log_files(max_files as usize)
}
if let Some(file_suffix) = file_configuration.file_suffix {
builder = builder.filename_suffix(file_suffix)
}
let writer =
builder.build(&file_configuration.path).expect("Failed to create a rolling file appender.");
fmt::layer()
.fmt_fields(FieldsFormatterForFiles::default())
.event_format(EventFormatter::new())
// EventFormatter doesn't support ANSI colors anyways, but the
// default field formatter does, which is unhelpful for iOS +
// Android logs, but enabled by default.
.with_ansi(false)
.with_writer(writer)
}
/// Configuration to save logs to (rotated) log-files.
@@ -243,6 +271,7 @@ enum LogTarget {
MatrixSdkBaseEventCache,
MatrixSdkBaseSlidingSync,
MatrixSdkBaseStoreAmbiguityMap,
MatrixSdkBaseResponseProcessors,
// SDK common modules.
MatrixSdkCommonStoreLocks,
@@ -261,6 +290,7 @@ enum LogTarget {
// SDK UI modules.
MatrixSdkUiTimeline,
MatrixSdkUiNotificationClient,
}
impl LogTarget {
@@ -271,6 +301,7 @@ impl LogTarget {
LogTarget::MatrixSdkBaseEventCache => "matrix_sdk_base::event_cache",
LogTarget::MatrixSdkBaseSlidingSync => "matrix_sdk_base::sliding_sync",
LogTarget::MatrixSdkBaseStoreAmbiguityMap => "matrix_sdk_base::store::ambiguity_map",
LogTarget::MatrixSdkBaseResponseProcessors => "matrix_sdk_base::response_processors",
LogTarget::MatrixSdkCommonStoreLocks => "matrix_sdk_common::store_locks",
LogTarget::MatrixSdk => "matrix_sdk",
LogTarget::MatrixSdkClient => "matrix_sdk::client",
@@ -283,6 +314,7 @@ impl LogTarget {
LogTarget::MatrixSdkSendQueue => "matrix_sdk::send_queue",
LogTarget::MatrixSdkEventCacheStore => "matrix_sdk_sqlite::event_cache_store",
LogTarget::MatrixSdkUiTimeline => "matrix_sdk_ui::timeline",
LogTarget::MatrixSdkUiNotificationClient => "matrix_sdk_ui::notification_client",
}
}
}
@@ -305,6 +337,8 @@ const DEFAULT_TARGET_LOG_LEVELS: &[(LogTarget, LogLevel)] = &[
(LogTarget::MatrixSdkEventCacheStore, LogLevel::Info),
(LogTarget::MatrixSdkCommonStoreLocks, LogLevel::Warn),
(LogTarget::MatrixSdkBaseStoreAmbiguityMap, LogLevel::Warn),
(LogTarget::MatrixSdkUiNotificationClient, LogLevel::Info),
(LogTarget::MatrixSdkBaseResponseProcessors, LogLevel::Debug),
];
const IMMUTABLE_LOG_TARGETS: &[LogTarget] = &[
@@ -325,6 +359,10 @@ pub enum TraceLogPacks {
SendQueue,
/// Enables all the logs relevant to the timeline.
Timeline,
/// Enables all the logs relevant to the notification client.
NotificationClient,
/// Enables all the logs relevant to sync profiling.
SyncProfiling,
}
impl TraceLogPacks {
@@ -339,10 +377,34 @@ impl TraceLogPacks {
],
TraceLogPacks::SendQueue => &[LogTarget::MatrixSdkSendQueue],
TraceLogPacks::Timeline => &[LogTarget::MatrixSdkUiTimeline],
TraceLogPacks::NotificationClient => &[LogTarget::MatrixSdkUiNotificationClient],
TraceLogPacks::SyncProfiling => &[
LogTarget::MatrixSdkSlidingSync,
LogTarget::MatrixSdkBaseSlidingSync,
LogTarget::MatrixSdkBaseResponseProcessors,
LogTarget::MatrixSdkCrypto,
],
}
}
}
#[cfg(feature = "sentry")]
struct SentryLoggingCtx {
/// The Sentry client guard, which keeps the Sentry context alive.
_guard: sentry::ClientInitGuard,
/// Whether the Sentry layer is enabled or not, at a global level.
enabled: Arc<AtomicBool>,
}
struct LoggingCtx {
reload_handle: Option<ReloadHandle>,
#[cfg(feature = "sentry")]
sentry: Option<SentryLoggingCtx>,
}
static LOGGING: OnceLock<LoggingCtx> = OnceLock::new();
#[derive(uniffi::Record)]
pub struct TracingConfiguration {
/// The desired log level.
@@ -363,6 +425,108 @@ pub struct TracingConfiguration {
/// If set, configures rotated log files where to write additional logs.
write_to_files: Option<TracingFileConfiguration>,
/// If set, the Sentry DSN to use for error reporting.
#[cfg(feature = "sentry")]
sentry_dsn: Option<String>,
}
impl TracingConfiguration {
/// Sets up the tracing configuration and return a [`Logger`] instance
/// holding onto it.
#[cfg_attr(not(feature = "sentry"), allow(unused_mut))]
fn build(mut self) -> LoggingCtx {
// Show full backtraces, if we run into panics.
std::env::set_var("RUST_BACKTRACE", "1");
// Log panics.
log_panics::init();
let env_filter = build_tracing_filter(&self);
let logging_ctx;
#[cfg(feature = "sentry")]
{
// Prepare the Sentry layer, if a DSN is provided.
let (sentry_layer, sentry_logging_ctx) =
if let Some(sentry_dsn) = self.sentry_dsn.take() {
// Initialize the Sentry client with the given options.
let sentry_guard = sentry::init((
sentry_dsn,
sentry::ClientOptions {
traces_sample_rate: 0.0,
attach_stacktrace: true,
release: Some(env!("VERGEN_GIT_SHA").into()),
..sentry::ClientOptions::default()
},
));
let sentry_enabled = Arc::new(AtomicBool::new(true));
// Add a Sentry layer to the tracing subscriber.
//
// Pass custom event and span filters, which will ignore anything, if the Sentry
// support has been globally disabled, or if the statement doesn't include a
// `sentry` field set to `true`.
let sentry_layer = sentry_tracing::layer()
.event_filter({
let enabled = sentry_enabled.clone();
move |metadata| {
if enabled.load(std::sync::atomic::Ordering::SeqCst)
&& metadata.fields().field("sentry").is_some()
{
sentry_tracing::default_event_filter(metadata)
} else {
// Ignore the event.
sentry_tracing::EventFilter::Ignore
}
}
})
.span_filter({
let enabled = sentry_enabled.clone();
move |metadata| {
if enabled.load(std::sync::atomic::Ordering::SeqCst) {
sentry_tracing::default_span_filter(metadata)
} else {
// Ignore, if sentry is globally disabled.
false
}
}
});
(
Some(sentry_layer),
Some(SentryLoggingCtx { _guard: sentry_guard, enabled: sentry_enabled }),
)
} else {
(None, None)
};
let (text_layers, reload_handle) = crate::platform::text_layers(self);
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(&env_filter))
.with(text_layers)
.with(sentry_layer)
.init();
logging_ctx = LoggingCtx { reload_handle, sentry: sentry_logging_ctx };
}
#[cfg(not(feature = "sentry"))]
{
let (text_layers, reload_handle) = crate::platform::text_layers(self);
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(&env_filter))
.with(text_layers)
.init();
logging_ctx = LoggingCtx { reload_handle };
}
// Log the log levels 🧠.
tracing::info!(env_filter, "Logging has been set up");
logging_ctx
}
}
fn build_tracing_filter(config: &TracingConfiguration) -> String {
@@ -407,26 +571,79 @@ fn build_tracing_filter(config: &TracingConfiguration) -> String {
/// the NSE process on iOS). Otherwise, this can remain false, in which case a
/// multithreaded tokio runtime will be set up.
#[matrix_sdk_ffi_macros::export]
pub fn init_platform(config: TracingConfiguration, use_lightweight_tokio_runtime: bool) {
log_panics();
let env_filter = build_tracing_filter(&config);
tracing_subscriber::registry()
.with(EnvFilter::new(&env_filter))
.with(text_layers(config))
.init();
// Log the log levels 🧠.
tracing::info!(env_filter, "Logging has been set up");
if use_lightweight_tokio_runtime {
setup_lightweight_tokio_runtime();
} else {
setup_multithreaded_tokio_runtime();
pub fn init_platform(
config: TracingConfiguration,
use_lightweight_tokio_runtime: bool,
) -> Result<(), ClientError> {
#[cfg(all(feature = "js", target_family = "wasm"))]
{
console_error_panic_hook::set_once();
}
#[cfg(not(target_family = "wasm"))]
{
LOGGING.set(config.build()).map_err(|_| ClientError::Generic {
msg: "logger already initialized".to_owned(),
details: None,
})?;
if use_lightweight_tokio_runtime {
setup_lightweight_tokio_runtime();
} else {
setup_multithreaded_tokio_runtime();
}
}
Ok(())
}
/// Set the global enablement level for the Sentry layer (after the logs have
/// been set up).
#[matrix_sdk_ffi_macros::export]
#[cfg(feature = "sentry")]
pub fn enable_sentry_logging(enabled: bool) {
if let Some(ctx) = LOGGING.get() {
if let Some(sentry_ctx) = &ctx.sentry {
sentry_ctx.enabled.store(enabled, std::sync::atomic::Ordering::SeqCst);
} else {
warn!("Sentry logging is not enabled");
}
} else {
// Can't use log statements here, since logging hasn't been enabled yet 🧠
eprintln!("Logging hasn't been enabled yet");
};
}
/// Updates the tracing subscriber with a new file writer based on the provided
/// configuration.
///
/// This method will throw if `init_platform` hasn't been called, or if it was
/// called with `write_to_files` set to `None`.
#[matrix_sdk_ffi_macros::export]
pub fn reload_tracing_file_writer(
configuration: TracingFileConfiguration,
) -> Result<(), ClientError> {
let Some(logging_context) = LOGGING.get() else {
return Err(ClientError::Generic {
msg: "Logging hasn't been initialized yet".to_owned(),
details: None,
});
};
let Some(reload_handle) = logging_context.reload_handle.as_ref() else {
return Err(ClientError::Generic {
msg: "Logging wasn't initialized with a file config".to_owned(),
details: None,
});
};
let layer = make_file_layer(configuration);
reload_handle.reload(layer).map_err(|error| ClientError::Generic {
msg: format!("Failed to reload file config: {error}"),
details: None,
})
}
#[cfg(not(target_family = "wasm"))]
fn setup_multithreaded_tokio_runtime() {
async_compat::set_runtime_builder(Box::new(|| {
eprintln!("spawning a multithreaded tokio runtime");
@@ -437,6 +654,7 @@ fn setup_multithreaded_tokio_runtime() {
}));
}
#[cfg(not(target_family = "wasm"))]
fn setup_lightweight_tokio_runtime() {
async_compat::set_runtime_builder(Box::new(|| {
eprintln!("spawning a lightweight tokio runtime");
@@ -468,6 +686,8 @@ fn setup_lightweight_tokio_runtime() {
#[cfg(test)]
mod tests {
use similar_asserts::assert_eq;
use super::build_tracing_filter;
use crate::platform::TraceLogPacks;
@@ -479,31 +699,39 @@ mod tests {
extra_targets: vec!["super_duper_app".to_owned()],
write_to_stdout_or_system: true,
write_to_files: None,
#[cfg(feature = "sentry")]
sentry_dsn: None,
};
let filter = build_tracing_filter(&config);
assert_eq!(
filter,
"panic=error,\
hyper=warn,\
matrix_sdk_ffi=info,\
matrix_sdk=info,\
matrix_sdk::client=trace,\
matrix_sdk_crypto=debug,\
matrix_sdk_crypto::olm::account=trace,\
matrix_sdk::oidc=trace,\
matrix_sdk::http_client=debug,\
matrix_sdk::sliding_sync=info,\
matrix_sdk_base::sliding_sync=info,\
matrix_sdk_ui::timeline=info,\
matrix_sdk::send_queue=info,\
matrix_sdk::event_cache=info,\
matrix_sdk_base::event_cache=info,\
matrix_sdk_sqlite::event_cache_store=info,\
matrix_sdk_common::store_locks=warn,\
matrix_sdk_base::store::ambiguity_map=warn,\
super_duper_app=error"
r#"panic=error,
hyper=warn,
matrix_sdk_ffi=info,
matrix_sdk=info,
matrix_sdk::client=trace,
matrix_sdk_crypto=debug,
matrix_sdk_crypto::olm::account=trace,
matrix_sdk::oidc=trace,
matrix_sdk::http_client=debug,
matrix_sdk::sliding_sync=info,
matrix_sdk_base::sliding_sync=info,
matrix_sdk_ui::timeline=info,
matrix_sdk::send_queue=info,
matrix_sdk::event_cache=info,
matrix_sdk_base::event_cache=info,
matrix_sdk_sqlite::event_cache_store=info,
matrix_sdk_common::store_locks=warn,
matrix_sdk_base::store::ambiguity_map=warn,
matrix_sdk_ui::notification_client=info,
matrix_sdk_base::response_processors=debug,
super_duper_app=error"#
.split('\n')
.map(|s| s.trim())
.collect::<Vec<_>>()
.join("")
);
}
@@ -515,32 +743,40 @@ mod tests {
extra_targets: vec!["super_duper_app".to_owned(), "some_other_span".to_owned()],
write_to_stdout_or_system: true,
write_to_files: None,
#[cfg(feature = "sentry")]
sentry_dsn: None,
};
let filter = build_tracing_filter(&config);
assert_eq!(
filter,
"panic=error,\
hyper=warn,\
matrix_sdk_ffi=info,\
matrix_sdk=info,\
matrix_sdk::client=trace,\
matrix_sdk_crypto=trace,\
matrix_sdk_crypto::olm::account=trace,\
matrix_sdk::oidc=trace,\
matrix_sdk::http_client=trace,\
matrix_sdk::sliding_sync=trace,\
matrix_sdk_base::sliding_sync=trace,\
matrix_sdk_ui::timeline=trace,\
matrix_sdk::send_queue=trace,\
matrix_sdk::event_cache=trace,\
matrix_sdk_base::event_cache=trace,\
matrix_sdk_sqlite::event_cache_store=trace,\
matrix_sdk_common::store_locks=warn,\
matrix_sdk_base::store::ambiguity_map=warn,\
super_duper_app=trace,\
some_other_span=trace"
r#"panic=error,
hyper=warn,
matrix_sdk_ffi=info,
matrix_sdk=info,
matrix_sdk::client=trace,
matrix_sdk_crypto=trace,
matrix_sdk_crypto::olm::account=trace,
matrix_sdk::oidc=trace,
matrix_sdk::http_client=trace,
matrix_sdk::sliding_sync=trace,
matrix_sdk_base::sliding_sync=trace,
matrix_sdk_ui::timeline=trace,
matrix_sdk::send_queue=trace,
matrix_sdk::event_cache=trace,
matrix_sdk_base::event_cache=trace,
matrix_sdk_sqlite::event_cache_store=trace,
matrix_sdk_common::store_locks=warn,
matrix_sdk_base::store::ambiguity_map=warn,
matrix_sdk_ui::notification_client=trace,
matrix_sdk_base::response_processors=trace,
super_duper_app=trace,
some_other_span=trace"#
.split('\n')
.map(|s| s.trim())
.collect::<Vec<_>>()
.join("")
);
}
@@ -552,6 +788,8 @@ mod tests {
extra_targets: vec!["super_duper_app".to_owned()],
write_to_stdout_or_system: true,
write_to_files: None,
#[cfg(feature = "sentry")]
sentry_dsn: None,
};
let filter = build_tracing_filter(&config);
@@ -576,6 +814,8 @@ mod tests {
matrix_sdk_sqlite::event_cache_store=trace,
matrix_sdk_common::store_locks=warn,
matrix_sdk_base::store::ambiguity_map=warn,
matrix_sdk_ui::notification_client=info,
matrix_sdk_base::response_processors=debug,
super_duper_app=info"#
.split('\n')
.map(|s| s.trim())
+166
View File
@@ -0,0 +1,166 @@
use std::sync::Arc;
use matrix_sdk::{
authentication::oauth::qrcode::{self, DeviceCodeErrorResponseType, LoginFailureReason},
crypto::types::qr_login::{LoginQrCodeDecodeError, QrCodeModeData},
};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use tracing::error;
/// Data for the QR code login mechanism.
///
/// The [`QrCodeData`] can be serialized and encoded as a QR code or it can be
/// decoded from a QR code.
#[derive(Debug, uniffi::Object)]
pub struct QrCodeData {
pub(crate) inner: qrcode::QrCodeData,
}
#[matrix_sdk_ffi_macros::export]
impl QrCodeData {
/// Attempt to decode a slice of bytes into a [`QrCodeData`] object.
///
/// The slice of bytes would generally be returned by a QR code decoder.
#[uniffi::constructor]
pub fn from_bytes(bytes: Vec<u8>) -> Result<Arc<Self>, QrCodeDecodeError> {
Ok(Self { inner: qrcode::QrCodeData::from_bytes(&bytes)? }.into())
}
/// The server name contained within the scanned QR code data.
///
/// Note: This value is only present when scanning a QR code the belongs to
/// a logged in client. The mode where the new client shows the QR code
/// will return `None`.
pub fn server_name(&self) -> Option<String> {
match &self.inner.mode_data {
QrCodeModeData::Reciprocate { server_name } => Some(server_name.to_owned()),
QrCodeModeData::Login => None,
}
}
}
/// Error type for the decoding of the [`QrCodeData`].
#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi(flat_error)]
pub enum QrCodeDecodeError {
#[error("Error decoding QR code: {error:?}")]
Crypto {
#[from]
error: LoginQrCodeDecodeError,
},
}
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum HumanQrLoginError {
#[error("Linking with this device is not supported.")]
LinkingNotSupported,
#[error("The sign in was cancelled.")]
Cancelled,
#[error("The sign in was not completed in the required time.")]
Expired,
#[error("A secure connection could not have been established between the two devices.")]
ConnectionInsecure,
#[error("The sign in was declined.")]
Declined,
#[error("An unknown error has happened.")]
Unknown,
#[error("The homeserver doesn't provide sliding sync in its configuration.")]
SlidingSyncNotAvailable,
#[error("Unable to use OIDC as the supplied client metadata is invalid.")]
OidcMetadataInvalid,
#[error("The other device is not signed in and as such can't sign in other devices.")]
OtherDeviceNotSignedIn,
}
impl From<qrcode::QRCodeLoginError> for HumanQrLoginError {
fn from(value: qrcode::QRCodeLoginError) -> Self {
use qrcode::{QRCodeLoginError, SecureChannelError};
match value {
QRCodeLoginError::LoginFailure { reason, .. } => match reason {
LoginFailureReason::UnsupportedProtocol => HumanQrLoginError::LinkingNotSupported,
LoginFailureReason::AuthorizationExpired => HumanQrLoginError::Expired,
LoginFailureReason::UserCancelled => HumanQrLoginError::Cancelled,
_ => HumanQrLoginError::Unknown,
},
QRCodeLoginError::OAuth(e) => {
if let Some(e) = e.as_request_token_error() {
match e {
DeviceCodeErrorResponseType::AccessDenied => HumanQrLoginError::Declined,
DeviceCodeErrorResponseType::ExpiredToken => HumanQrLoginError::Expired,
_ => HumanQrLoginError::Unknown,
}
} else {
HumanQrLoginError::Unknown
}
}
QRCodeLoginError::SecureChannel(e) => match e {
SecureChannelError::Utf8(_)
| SecureChannelError::MessageDecode(_)
| SecureChannelError::Json(_)
| SecureChannelError::RendezvousChannel(_) => HumanQrLoginError::Unknown,
SecureChannelError::SecureChannelMessage { .. }
| SecureChannelError::Ecies(_)
| SecureChannelError::InvalidCheckCode => HumanQrLoginError::ConnectionInsecure,
SecureChannelError::InvalidIntent => HumanQrLoginError::OtherDeviceNotSignedIn,
},
QRCodeLoginError::UnexpectedMessage { .. }
| QRCodeLoginError::CrossProcessRefreshLock(_)
| QRCodeLoginError::DeviceKeyUpload(_)
| QRCodeLoginError::SessionTokens(_)
| QRCodeLoginError::UserIdDiscovery(_)
| QRCodeLoginError::SecretImport(_) => HumanQrLoginError::Unknown,
}
}
}
/// Enum describing the progress of the QR-code login.
#[derive(Debug, Default, Clone, uniffi::Enum)]
pub enum QrLoginProgress {
/// The login process is starting.
#[default]
Starting,
/// We established a secure channel with the other device.
EstablishingSecureChannel {
/// The check code that the device should display so the other device
/// can confirm that the channel is secure as well.
check_code: u8,
/// The string representation of the check code, will be guaranteed to
/// be 2 characters long, preserving the leading zero if the
/// first digit is a zero.
check_code_string: String,
},
/// We are waiting for the login and for the OAuth 2.0 authorization server
/// to give us an access token.
WaitingForToken { user_code: String },
/// The login has successfully finished.
Done,
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait QrLoginProgressListener: SyncOutsideWasm + SendOutsideWasm {
fn on_update(&self, state: QrLoginProgress);
}
impl From<qrcode::LoginProgress> for QrLoginProgress {
fn from(value: qrcode::LoginProgress) -> Self {
use qrcode::LoginProgress;
match value {
LoginProgress::Starting => Self::Starting,
LoginProgress::EstablishingSecureChannel { check_code } => {
let check_code = check_code.to_digit();
Self::EstablishingSecureChannel {
check_code,
check_code_string: format!("{check_code:02}"),
}
}
LoginProgress::WaitingForToken { user_code } => Self::WaitingForToken { user_code },
LoginProgress::Done => Self::Done,
}
}
}
@@ -1,7 +1,6 @@
use std::{collections::HashMap, pin::pin, sync::Arc};
use anyhow::{Context, Result};
use async_compat::get_runtime_handle;
use futures_util::{pin_mut, StreamExt};
use matrix_sdk::{
crypto::LocalTrust,
@@ -10,9 +9,14 @@ use matrix_sdk::{
TryFromReportedContentScoreError,
},
ComposerDraft as SdkComposerDraft, ComposerDraftType as SdkComposerDraftType, EncryptionState,
RoomHero as SdkRoomHero, RoomMemberships, RoomState,
PredecessorRoom as SdkPredecessorRoom, RoomHero as SdkRoomHero, RoomMemberships, RoomState,
SuccessorRoom as SdkSuccessorRoom,
};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use matrix_sdk_ui::{
timeline::{default_event_filter, RoomExt, TimelineBuilder},
unable_to_decrypt_hook::UtdHookManager,
};
use matrix_sdk_ui::timeline::{default_event_filter, RoomExt};
use mime::Mime;
use ruma::{
assign,
@@ -22,33 +26,37 @@ use ruma::{
avatar::ImageInfo as RumaAvatarImageInfo,
history_visibility::HistoryVisibility as RumaHistoryVisibility,
join_rules::JoinRule as RumaJoinRule, message::RoomMessageEventContentWithoutRelation,
power_levels::RoomPowerLevels as RumaPowerLevels, MediaSource,
MediaSource,
},
AnyMessageLikeEventContent, AnySyncTimelineEvent, TimelineEventType,
AnyMessageLikeEventContent, AnySyncTimelineEvent,
},
EventId, Int, OwnedDeviceId, OwnedUserId, RoomAliasId, UserId,
EventId, Int, OwnedDeviceId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, RoomAliasId,
ServerName, UserId,
};
use tokio::sync::RwLock;
use tracing::{error, warn};
use self::{power_levels::RoomPowerLevels, room_info::RoomInfo};
use crate::{
chunk_iterator::ChunkIterator,
client::{JoinRule, RoomVisibility},
error::{ClientError, MediaInfoError, NotYetImplemented, RoomError},
event::{MessageLikeEventType, StateEventType},
identity_status_change::IdentityStatusChange,
live_location_share::{LastLocation, LiveLocationShare},
room_info::RoomInfo,
room_member::{RoomMember, RoomMemberWithSenderInfo},
ruma::{ImageInfo, LocationContent, Mentions, NotifyType},
room_preview::RoomPreview,
ruma::{ImageInfo, LocationContent},
runtime::get_runtime_handle,
timeline::{
configuration::{TimelineConfiguration, TimelineFilter},
ReceiptType, SendHandle, Timeline,
EventTimelineItem, LatestEventValue, ReceiptType, SendHandle, Timeline,
},
utils::u64_to_uint,
utils::{u64_to_uint, AsyncRuntimeDropped},
TaskHandle,
};
mod power_levels;
pub mod room_info;
#[derive(Debug, Clone, uniffi::Enum)]
pub enum Membership {
Invited,
@@ -70,21 +78,15 @@ impl From<RoomState> for Membership {
}
}
pub(crate) type TimelineLock = Arc<RwLock<Option<Arc<Timeline>>>>;
#[derive(uniffi::Object)]
pub struct Room {
pub(super) inner: SdkRoom,
timeline: TimelineLock,
utd_hook_manager: Option<Arc<UtdHookManager>>,
}
impl Room {
pub(crate) fn new(inner: SdkRoom) -> Self {
Room { inner, timeline: Default::default() }
}
pub(crate) fn with_timeline(inner: SdkRoom, timeline: TimelineLock) -> Self {
Room { inner, timeline }
pub(crate) fn new(inner: SdkRoom, utd_hook_manager: Option<Arc<UtdHookManager>>) -> Self {
Room { inner, utd_hook_manager }
}
}
@@ -114,7 +116,10 @@ impl Room {
self.inner.is_direct().await.unwrap_or(false)
}
pub fn is_public(&self) -> bool {
/// Whether the room can be publicly joined or not, based on its join rule.
///
/// Can return `None` if the join rule state event is missing.
pub fn is_public(&self) -> Option<bool> {
self.inner.is_public()
}
@@ -122,8 +127,31 @@ impl Room {
self.inner.is_space()
}
pub fn is_tombstoned(&self) -> bool {
self.inner.is_tombstoned()
/// If this room is tombstoned, return the “reference” to the successor room
/// —i.e. the room replacing this one.
///
/// A room is tombstoned if it has received a [`m.room.tombstone`] state
/// event.
///
/// [`m.room.tombstone`]: https://spec.matrix.org/v1.14/client-server-api/#mroomtombstone
pub fn successor_room(&self) -> Option<SuccessorRoom> {
self.inner.successor_room().map(Into::into)
}
/// If this room is the successor of a tombstoned room, return the
/// “reference” to the predecessor room.
///
/// A room is tombstoned if it has received a [`m.room.tombstone`] state
/// event.
///
/// To determine if a room is the successor of a tombstoned room, the
/// [`m.room.create`] must have been received, **with** a `predecessor`
/// field.
///
/// [`m.room.tombstone`]: https://spec.matrix.org/v1.14/client-server-api/#mroomtombstone
/// [`m.room.create`]: https://spec.matrix.org/v1.14/client-server-api/#mroomcreate
pub fn predecessor_room(&self) -> Option<PredecessorRoom> {
self.inner.predecessor_room().map(Into::into)
}
pub fn canonical_alias(&self) -> Option<String> {
@@ -134,6 +162,17 @@ impl Room {
self.inner.alt_aliases().iter().map(|a| a.to_string()).collect()
}
/// Get the user who created the invite, if any.
pub async fn inviter(&self) -> Result<Option<RoomMember>, ClientError> {
let invite_details = self.inner.invite_details().await?;
match invite_details.inviter {
Some(inviter) => Ok(Some(inviter.try_into()?)),
None => Ok(None),
}
}
/// The room's current membership state.
pub fn membership(&self) -> Membership {
self.inner.state().into()
}
@@ -173,15 +212,10 @@ impl Room {
Ok(())
}
/// Create a timeline with a default configuration, i.e. a live timeline
/// with read receipts and read marker tracking.
pub async fn timeline(&self) -> Result<Arc<Timeline>, ClientError> {
let mut write_guard = self.timeline.write().await;
if let Some(timeline) = &*write_guard {
Ok(timeline.clone())
} else {
let timeline = Timeline::new(self.inner.timeline().await?);
*write_guard = Some(timeline.clone());
Ok(timeline)
}
Ok(Timeline::new(self.inner.timeline().await?))
}
/// Build a new timeline instance with the given configuration.
@@ -189,7 +223,7 @@ impl Room {
&self,
configuration: TimelineConfiguration,
) -> Result<Arc<Timeline>, ClientError> {
let mut builder = matrix_sdk_ui::timeline::Timeline::builder(&self.inner);
let mut builder = matrix_sdk_ui::timeline::TimelineBuilder::new(&self.inner);
builder = builder
.with_focus(configuration.focus.try_into()?)
@@ -233,6 +267,14 @@ impl Room {
builder = builder.with_internal_id_prefix(internal_id_prefix);
}
if configuration.report_utds {
if let Some(utd_hook_manager) = self.utd_hook_manager.clone() {
builder = builder.with_unable_to_decrypt_hook(utd_hook_manager);
} else {
return Err(ClientError::Generic { msg: "Failed creating timeline because the configuration is set to report UTDs but no hook manager is set".to_owned(), details: None });
}
}
let timeline = builder.build().await?;
Ok(Timeline::new(timeline))
@@ -246,6 +288,26 @@ impl Room {
self.inner.encryption_state()
}
/// Checks whether the room is encrypted or not.
///
/// **Note**: this info may not be reliable if you don't set up
/// `m.room.encryption` as required state.
async fn is_encrypted(&self) -> bool {
self.inner
.latest_encryption_state()
.await
.map(|state| state.is_encrypted())
.unwrap_or(false)
}
async fn latest_event(&self) -> Option<EventTimelineItem> {
self.inner.latest_event_item().await.map(Into::into)
}
async fn new_latest_event(&self) -> LatestEventValue {
self.inner.new_latest_event().await.into()
}
pub async fn latest_encryption_state(&self) -> Result<EncryptionState, ClientError> {
Ok(self.inner.latest_encryption_state().await?)
}
@@ -346,8 +408,11 @@ impl Room {
///
/// * `content` - The content of the event to send encoded as JSON string.
pub async fn send_raw(&self, event_type: String, content: String) -> Result<(), ClientError> {
let content_json: serde_json::Value = serde_json::from_str(&content)
.map_err(|e| ClientError::Generic { msg: format!("Failed to parse JSON: {e}") })?;
let content_json: serde_json::Value =
serde_json::from_str(&content).map_err(|e| ClientError::Generic {
msg: format!("Failed to parse JSON: {e}"),
details: Some(format!("{e:?}")),
})?;
self.inner.send_raw(&event_type, content_json).await?;
@@ -404,9 +469,7 @@ impl Room {
.report_content(
EventId::parse(event_id)?,
score.map(TryFrom::try_from).transpose().map_err(
|error: TryFromReportedContentScoreError| ClientError::Generic {
msg: error.to_string(),
},
|error: TryFromReportedContentScoreError| ClientError::from_err(error),
)?,
reason,
)
@@ -425,7 +488,7 @@ impl Room {
/// # Errors
///
/// Returns an error if the room is not found or on rate limit
pub async fn report_room(&self, reason: Option<String>) -> Result<(), ClientError> {
pub async fn report_room(&self, reason: String) -> Result<(), ClientError> {
self.inner.report_room(reason).await?;
Ok(())
@@ -516,21 +579,6 @@ impl Room {
Ok(())
}
pub async fn can_user_redact_own(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_redact_own(&user_id).await?)
}
pub async fn can_user_redact_other(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_redact_other(&user_id).await?)
}
pub async fn can_user_ban(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_ban(&user_id).await?)
}
pub async fn ban_user(
&self,
user_id: String,
@@ -549,16 +597,6 @@ impl Room {
Ok(self.inner.unban_user(&user_id, reason.as_deref()).await?)
}
pub async fn can_user_invite(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_invite(&user_id).await?)
}
pub async fn can_user_kick(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_kick(&user_id).await?)
}
pub async fn kick_user(
&self,
user_id: String,
@@ -568,37 +606,6 @@ impl Room {
Ok(self.inner.kick_user(&user_id, reason.as_deref()).await?)
}
pub async fn can_user_send_state(
&self,
user_id: String,
state_event: StateEventType,
) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_send_state(&user_id, state_event.into()).await?)
}
pub async fn can_user_send_message(
&self,
user_id: String,
message: MessageLikeEventType,
) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_send_message(&user_id, message.into()).await?)
}
pub async fn can_user_pin_unpin(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_pin_unpin(&user_id).await?)
}
pub async fn can_user_trigger_room_notification(
&self,
user_id: String,
) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.can_user_trigger_room_notification(&user_id).await?)
}
pub fn own_user_id(&self) -> String {
self.inner.own_user_id().to_string()
}
@@ -655,17 +662,17 @@ impl Room {
/// Mark a room as read, by attaching a read receipt on the latest event.
///
/// Note: this does NOT unset the unread flag; it's the caller's
/// responsibility to do so, if needs be.
/// responsibility to do so, if need be.
pub async fn mark_as_read(&self, receipt_type: ReceiptType) -> Result<(), ClientError> {
let timeline = self.timeline().await?;
let timeline = TimelineBuilder::new(&self.inner).build().await?;
timeline.mark_as_read(receipt_type).await?;
timeline.mark_as_read(receipt_type.into()).await?;
Ok(())
}
pub async fn get_power_levels(&self) -> Result<RoomPowerLevels, ClientError> {
pub async fn get_power_levels(&self) -> Result<Arc<RoomPowerLevels>, ClientError> {
let power_levels = self.inner.power_levels().await.map_err(matrix_sdk::Error::from)?;
Ok(RoomPowerLevels::from(power_levels))
Ok(Arc::new(RoomPowerLevels::new(power_levels, self.inner.own_user_id().to_owned())))
}
pub async fn apply_power_level_changes(
@@ -689,10 +696,7 @@ impl Room {
})
.collect::<Result<Vec<_>>>()?;
self.inner
.update_power_levels(updates)
.await
.map_err(|e| ClientError::Generic { msg: e.to_string() })?;
self.inner.update_power_levels(updates).await.map_err(ClientError::from_err)?;
Ok(())
}
@@ -704,8 +708,11 @@ impl Room {
Ok(self.inner.get_suggested_user_role(&user_id).await?)
}
pub async fn reset_power_levels(&self) -> Result<RoomPowerLevels, ClientError> {
Ok(RoomPowerLevels::from(self.inner.reset_power_levels().await?))
pub async fn reset_power_levels(&self) -> Result<Arc<RoomPowerLevels>, ClientError> {
Ok(Arc::new(RoomPowerLevels::new(
self.inner.reset_power_levels().await?,
self.inner.own_user_id().to_owned(),
)))
}
pub async fn matrix_to_permalink(&self) -> Result<String, ClientError> {
@@ -717,49 +724,6 @@ impl Room {
Ok(self.inner.matrix_to_event_permalink(event_id).await?.to_string())
}
/// This will only send a call notification event if appropriate.
///
/// This function is supposed to be called whenever the user creates a room
/// call. It will send a `m.call.notify` event if:
/// - there is not yet a running call.
///
/// It will configure the notify type: ring or notify based on:
/// - is this a DM room -> ring
/// - is this a group with more than one other member -> notify
pub async fn send_call_notification_if_needed(&self) -> Result<(), ClientError> {
self.inner.send_call_notification_if_needed().await?;
Ok(())
}
/// Send a call notification event in the current room.
///
/// This is only supposed to be used in **custom** situations where the user
/// explicitly chooses to send a `m.call.notify` event to invite/notify
/// someone explicitly in unusual conditions. The default should be to
/// use `send_call_notification_if_necessary` just before a new room call is
/// created/joined.
///
/// One example could be that the UI allows to start a call with a subset of
/// users of the room members first. And then later on the user can
/// invite more users to the call.
pub async fn send_call_notification(
&self,
call_id: String,
application: RtcApplicationType,
notify_type: NotifyType,
mentions: Mentions,
) -> Result<(), ClientError> {
self.inner
.send_call_notification(
call_id,
application.into(),
notify_type.into(),
mentions.into(),
)
.await?;
Ok(())
}
/// Returns whether the send queue for that particular room is enabled or
/// not.
pub fn is_send_queue_enabled(&self) -> bool {
@@ -773,18 +737,31 @@ impl Room {
/// Store the given `ComposerDraft` in the state store using the current
/// room id, as identifier.
pub async fn save_composer_draft(&self, draft: ComposerDraft) -> Result<(), ClientError> {
Ok(self.inner.save_composer_draft(draft.try_into()?).await?)
pub async fn save_composer_draft(
&self,
draft: ComposerDraft,
thread_root: Option<String>,
) -> Result<(), ClientError> {
let thread_root = thread_root.map(EventId::parse).transpose()?;
Ok(self.inner.save_composer_draft(draft.try_into()?, thread_root.as_deref()).await?)
}
/// Retrieve the `ComposerDraft` stored in the state store for this room.
pub async fn load_composer_draft(&self) -> Result<Option<ComposerDraft>, ClientError> {
Ok(self.inner.load_composer_draft().await?.map(Into::into))
pub async fn load_composer_draft(
&self,
thread_root: Option<String>,
) -> Result<Option<ComposerDraft>, ClientError> {
let thread_root = thread_root.map(EventId::parse).transpose()?;
Ok(self.inner.load_composer_draft(thread_root.as_deref()).await?.map(Into::into))
}
/// Remove the `ComposerDraft` stored in the state store for this room.
pub async fn clear_composer_draft(&self) -> Result<(), ClientError> {
Ok(self.inner.clear_composer_draft().await?)
pub async fn clear_composer_draft(
&self,
thread_root: Option<String>,
) -> Result<(), ClientError> {
let thread_root = thread_root.map(EventId::parse).transpose()?;
Ok(self.inner.clear_composer_draft(thread_root.as_deref()).await?)
}
/// Edit an event given its event id.
@@ -1084,11 +1061,99 @@ impl Room {
self.inner.forget().await?;
Ok(())
}
/// Builds a `RoomPreview` from a room list item. This is intended for
/// invited, knocked or banned rooms.
async fn preview_room(&self, via: Vec<String>) -> Result<Arc<RoomPreview>, ClientError> {
// Validate parameters first.
let server_names: Vec<OwnedServerName> = via
.into_iter()
.map(|server| ServerName::parse(server).map_err(ClientError::from))
.collect::<Result<_, ClientError>>()?;
// Do the thing.
let client = self.inner.client();
let (room_or_alias_id, mut server_names) = if let Some(alias) = self.inner.canonical_alias()
{
let room_or_alias_id: OwnedRoomOrAliasId = alias.into();
(room_or_alias_id, Vec::new())
} else {
let room_or_alias_id: OwnedRoomOrAliasId = self.inner.room_id().to_owned().into();
(room_or_alias_id, server_names)
};
// If no server names are provided and the room's membership is invited,
// add the server name from the sender's user id as a fallback value
if server_names.is_empty() {
if let Ok(invite_details) = self.inner.invite_details().await {
if let Some(inviter) = invite_details.inviter {
server_names.push(inviter.user_id().server_name().to_owned());
}
}
}
let room_preview = client.get_room_preview(&room_or_alias_id, server_names).await?;
Ok(Arc::new(RoomPreview::new(AsyncRuntimeDropped::new(client), room_preview)))
}
/// Set a MSC4306 subscription to a thread in this room, based on the thread
/// root event id.
///
/// If `subscribed` is `true`, it will subscribe to the thread, with a
/// precision that the subscription was manually requested by the user
/// (i.e. not automatic).
///
/// If the thread was already subscribed to (resp. unsubscribed from), while
/// trying to subscribe to it (resp. unsubscribe from it), it will do
/// nothing, i.e. subscribing (resp. unsubscribing) to a thread is an
/// idempotent operation.
pub async fn set_thread_subscription(
&self,
thread_root_event_id: String,
subscribed: bool,
) -> Result<(), ClientError> {
let thread_root = EventId::parse(thread_root_event_id)?;
if subscribed {
// This is a manual subscription.
let automatic = None;
self.inner.subscribe_thread(thread_root, automatic).await?;
} else {
self.inner.unsubscribe_thread(thread_root).await?;
}
Ok(())
}
/// Return the current MSC4306 thread subscription for the given thread root
/// in this room.
///
/// Returns `None` if the thread doesn't exist, or isn't subscribed to, or
/// the server can't handle MSC4306; otherwise, returns the thread
/// subscription status.
pub async fn fetch_thread_subscription(
&self,
thread_root_event_id: String,
) -> Result<Option<ThreadSubscription>, ClientError> {
let thread_root = EventId::parse(thread_root_event_id)?;
Ok(self
.inner
.fetch_thread_subscription(thread_root)
.await?
.map(|sub| ThreadSubscription { automatic: sub.automatic }))
}
}
/// A thread subscription (MSC4306).
#[derive(uniffi::Record)]
pub struct ThreadSubscription {
/// Whether the thread subscription happened automatically (e.g. after a
/// mention) or if it was manually requested by the user.
automatic: bool,
}
/// A listener for receiving new live location shares in a room.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait LiveLocationShareListener: Sync + Send {
pub trait LiveLocationShareListener: SyncOutsideWasm + SendOutsideWasm {
fn call(&self, live_location_shares: Vec<LiveLocationShare>);
}
@@ -1110,7 +1175,7 @@ impl From<matrix_sdk::room::knock_requests::KnockRequest> for KnockRequest {
/// A listener for receiving new requests to a join a room.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait KnockRequestsListener: Send + Sync {
pub trait KnockRequestsListener: SendOutsideWasm + SyncOutsideWasm {
fn call(&self, join_requests: Vec<KnockRequest>);
}
@@ -1181,66 +1246,18 @@ pub fn matrix_to_room_alias_permalink(
Ok(room_alias.matrix_to_uri().to_string())
}
#[derive(uniffi::Record)]
pub struct RoomPowerLevels {
/// The level required to ban a user.
pub ban: i64,
/// The level required to invite a user.
pub invite: i64,
/// The level required to kick a user.
pub kick: i64,
/// The level required to redact an event.
pub redact: i64,
/// The default level required to send message events.
pub events_default: i64,
/// The default level required to send state events.
pub state_default: i64,
/// The default power level for every user in the room.
pub users_default: i64,
/// The level required to change the room's name.
pub room_name: i64,
/// The level required to change the room's avatar.
pub room_avatar: i64,
/// The level required to change the room's topic.
pub room_topic: i64,
}
impl From<RumaPowerLevels> for RoomPowerLevels {
fn from(value: RumaPowerLevels) -> Self {
fn state_event_level_for(
power_levels: &RumaPowerLevels,
event_type: &TimelineEventType,
) -> i64 {
let default_state: i64 = power_levels.state_default.into();
power_levels.events.get(event_type).map_or(default_state, |&level| level.into())
}
Self {
ban: value.ban.into(),
invite: value.invite.into(),
kick: value.kick.into(),
redact: value.redact.into(),
events_default: value.events_default.into(),
state_default: value.state_default.into(),
users_default: value.users_default.into(),
room_name: state_event_level_for(&value, &TimelineEventType::RoomName),
room_avatar: state_event_level_for(&value, &TimelineEventType::RoomAvatar),
room_topic: state_event_level_for(&value, &TimelineEventType::RoomTopic),
}
}
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RoomInfoListener: Sync + Send {
pub trait RoomInfoListener: SyncOutsideWasm + SendOutsideWasm {
fn call(&self, room_info: RoomInfo);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait TypingNotificationsListener: Sync + Send {
pub trait TypingNotificationsListener: SyncOutsideWasm + SendOutsideWasm {
fn call(&self, typing_user_ids: Vec<String>);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait IdentityStatusChangeListener: Sync + Send {
pub trait IdentityStatusChangeListener: SyncOutsideWasm + SendOutsideWasm {
fn call(&self, identity_status_change: Vec<IdentityStatusChange>);
}
@@ -1462,3 +1479,45 @@ impl TryFrom<RoomHistoryVisibility> for RumaHistoryVisibility {
}
}
}
/// When a room A is tombstoned, it is replaced by a room B. The room A is the
/// predecessor of B, and B is the successor of A. This type holds information
/// about the successor room. See [`Room::successor_room`].
///
/// A room is tombstoned if it has received a [`m.room.tombstone`] state event.
///
/// [`m.room.tombstone`]: https://spec.matrix.org/v1.14/client-server-api/#mroomtombstone
#[derive(uniffi::Record)]
pub struct SuccessorRoom {
/// The ID of the replacement room.
pub room_id: String,
/// The message explaining why the room has been tombstoned.
pub reason: Option<String>,
}
impl From<SdkSuccessorRoom> for SuccessorRoom {
fn from(value: SdkSuccessorRoom) -> Self {
Self { room_id: value.room_id.to_string(), reason: value.reason }
}
}
/// When a room A is tombstoned, it is replaced by a room B. The room A is the
/// predecessor of B, and B is the successor of A. This type holds information
/// about the predecessor room. See [`Room::predecessor_room`].
///
/// To know the predecessor of a room, the [`m.room.create`] state event must
/// have been received.
///
/// [`m.room.create`]: https://spec.matrix.org/v1.14/client-server-api/#mroomcreate
#[derive(uniffi::Record)]
pub struct PredecessorRoom {
/// The ID of the replacement room.
pub room_id: String,
}
impl From<SdkPredecessorRoom> for PredecessorRoom {
fn from(value: SdkPredecessorRoom) -> Self {
Self { room_id: value.room_id.to_string() }
}
}
@@ -0,0 +1,233 @@
use std::collections::HashMap;
use anyhow::Result;
use ruma::{
events::{room::power_levels::RoomPowerLevels as RumaPowerLevels, TimelineEventType},
OwnedUserId, UserId,
};
use crate::{
error::ClientError,
event::{MessageLikeEventType, StateEventType},
};
#[derive(uniffi::Object)]
pub struct RoomPowerLevels {
inner: RumaPowerLevels,
own_user_id: OwnedUserId,
}
impl RoomPowerLevels {
pub fn new(value: RumaPowerLevels, own_user_id: OwnedUserId) -> Self {
Self { inner: value, own_user_id }
}
}
#[matrix_sdk_ffi_macros::export]
impl RoomPowerLevels {
fn values(&self) -> RoomPowerLevelsValues {
self.inner.clone().into()
}
/// Gets a map with the `UserId` of users with power levels other than `0`
/// and their power level.
pub fn user_power_levels(&self) -> HashMap<String, i64> {
let mut user_power_levels = HashMap::<String, i64>::new();
for (id, level) in self.inner.users.iter() {
user_power_levels.insert(id.to_string(), (*level).into());
}
user_power_levels
}
/// Returns true if the current user is able to ban in the room.
pub fn can_own_user_ban(&self) -> bool {
self.inner.user_can_ban(&self.own_user_id)
}
/// Returns true if the user with the given user_id is able to ban in the
/// room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_ban(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_ban(&user_id))
}
/// Returns true if the current user is able to redact their own messages in
/// the room.
pub fn can_own_user_redact_own(&self) -> bool {
self.inner.user_can_redact_own_event(&self.own_user_id)
}
/// Returns true if the user with the given user_id is able to redact
/// their own messages in the room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_redact_own(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_redact_own_event(&user_id))
}
/// Returns true if the current user user is able to redact messages of
/// other users in the room.
pub fn can_own_user_redact_other(&self) -> bool {
self.inner.user_can_redact_event_of_other(&self.own_user_id)
}
/// Returns true if the user with the given user_id is able to redact
/// messages of other users in the room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_redact_other(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_redact_event_of_other(&user_id))
}
/// Returns true if the current user is able to invite in the room.
pub fn can_own_user_invite(&self) -> bool {
self.inner.user_can_invite(&self.own_user_id)
}
/// Returns true if the user with the given user_id is able to invite in the
/// room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_invite(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_invite(&user_id))
}
/// Returns true if the current user is able to kick in the room.
pub fn can_own_user_kick(&self) -> bool {
self.inner.user_can_kick(&self.own_user_id)
}
/// Returns true if the user with the given user_id is able to kick in the
/// room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_kick(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_kick(&user_id))
}
/// Returns true if the current user is able to send a specific state event
/// type in the room.
pub fn can_own_user_send_state(&self, state_event: StateEventType) -> bool {
self.inner.user_can_send_state(&self.own_user_id, state_event.into())
}
/// Returns true if the user with the given user_id is able to send a
/// specific state event type in the room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_send_state(
&self,
user_id: String,
state_event: StateEventType,
) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_send_state(&user_id, state_event.into()))
}
/// Returns true if the current user is able to send a specific message type
/// in the room.
pub fn can_own_user_send_message(&self, message: MessageLikeEventType) -> bool {
self.inner.user_can_send_message(&self.own_user_id, message.into())
}
/// Returns true if the user with the given user_id is able to send a
/// specific message type in the room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_send_message(
&self,
user_id: String,
message: MessageLikeEventType,
) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_send_message(&user_id, message.into()))
}
/// Returns true if the current user is able to pin or unpin events in the
/// room.
pub fn can_own_user_pin_unpin(&self) -> bool {
self.inner.user_can_send_state(&self.own_user_id, StateEventType::RoomPinnedEvents.into())
}
/// Returns true if the user with the given user_id is able to pin or unpin
/// events in the room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_pin_unpin(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_send_state(&user_id, StateEventType::RoomPinnedEvents.into()))
}
/// Returns true if the current user is able to trigger a notification in
/// the room.
pub fn can_own_user_trigger_room_notification(&self) -> bool {
self.inner.user_can_trigger_room_notification(&self.own_user_id)
}
/// Returns true if the user with the given user_id is able to trigger a
/// notification in the room.
///
/// The call may fail if there is an error in getting the power levels.
pub fn can_user_trigger_room_notification(&self, user_id: String) -> Result<bool, ClientError> {
let user_id = UserId::parse(&user_id)?;
Ok(self.inner.user_can_trigger_room_notification(&user_id))
}
}
/// This intermediary struct is used to expose the power levels values through
/// FFI and work around it not exposing public exported object fields.
#[derive(uniffi::Record)]
pub struct RoomPowerLevelsValues {
/// The level required to ban a user.
pub ban: i64,
/// The level required to invite a user.
pub invite: i64,
/// The level required to kick a user.
pub kick: i64,
/// The level required to redact an event.
pub redact: i64,
/// The default level required to send message events.
pub events_default: i64,
/// The default level required to send state events.
pub state_default: i64,
/// The default power level for every user in the room.
pub users_default: i64,
/// The level required to change the room's name.
pub room_name: i64,
/// The level required to change the room's avatar.
pub room_avatar: i64,
/// The level required to change the room's topic.
pub room_topic: i64,
}
impl From<RumaPowerLevels> for RoomPowerLevelsValues {
fn from(value: RumaPowerLevels) -> Self {
fn state_event_level_for(
power_levels: &RumaPowerLevels,
event_type: &TimelineEventType,
) -> i64 {
let default_state: i64 = power_levels.state_default.into();
power_levels.events.get(event_type).map_or(default_state, |&level| level.into())
}
Self {
ban: value.ban.into(),
invite: value.invite.into(),
kick: value.kick.into(),
redact: value.redact.into(),
events_default: value.events_default.into(),
state_default: value.state_default.into(),
users_default: value.users_default.into(),
room_name: state_event_level_for(&value, &TimelineEventType::RoomName),
room_avatar: state_event_level_for(&value, &TimelineEventType::RoomAvatar),
room_topic: state_event_level_for(&value, &TimelineEventType::RoomTopic),
}
}
}
@@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::sync::Arc;
use matrix_sdk::{EncryptionState, RoomState};
use tracing::warn;
@@ -7,7 +7,9 @@ use crate::{
client::JoinRule,
error::ClientError,
notification_settings::RoomNotificationMode,
room::{Membership, RoomHero, RoomHistoryVisibility},
room::{
power_levels::RoomPowerLevels, Membership, RoomHero, RoomHistoryVisibility, SuccessorRoom,
},
room_member::RoomMember,
};
@@ -15,7 +17,7 @@ use crate::{
pub struct RoomInfo {
id: String,
encryption_state: EncryptionState,
creator: Option<String>,
creators: Option<Vec<String>>,
/// The room's name from the room state event if received from sync, or one
/// that's been computed otherwise.
display_name: Option<String>,
@@ -24,9 +26,14 @@ pub struct RoomInfo {
topic: Option<String>,
avatar_url: Option<String>,
is_direct: bool,
is_public: bool,
/// Whether the room is public or not, based on the join rules.
///
/// Can be `None` if the join rules state event is not available for this
/// room.
is_public: Option<bool>,
is_space: bool,
is_tombstoned: bool,
/// If present, it means the room has been archived/upgraded.
successor_room: Option<SuccessorRoom>,
is_favourite: bool,
canonical_alias: Option<String>,
alternative_aliases: Vec<String>,
@@ -41,7 +48,6 @@ pub struct RoomInfo {
active_members_count: u64,
invited_members_count: u64,
joined_members_count: u64,
user_power_levels: HashMap<String, i64>,
highlight_count: u64,
notification_count: u64,
cached_user_defined_notification_mode: Option<RoomNotificationMode>,
@@ -64,29 +70,46 @@ pub struct RoomInfo {
join_rule: Option<JoinRule>,
/// The history visibility for this room, if known.
history_visibility: RoomHistoryVisibility,
/// This room's current power levels.
///
/// Can be missing if the room power levels event is missing from the store.
power_levels: Option<Arc<RoomPowerLevels>>,
/// This room's version.
room_version: Option<String>,
/// Whether creators are privileged over every other user (have infinite
/// power level).
privileged_creators_role: bool,
}
impl RoomInfo {
pub(crate) async fn new(room: &matrix_sdk::Room) -> Result<Self, ClientError> {
let unread_notification_counts = room.unread_notification_counts();
let power_levels_map = room.users_with_power_levels().await;
let mut user_power_levels = HashMap::<String, i64>::new();
for (id, level) in power_levels_map.iter() {
user_power_levels.insert(id.to_string(), *level);
}
let pinned_event_ids =
room.pinned_event_ids().unwrap_or_default().iter().map(|id| id.to_string()).collect();
let join_rule = room.join_rule().try_into();
if let Err(e) = &join_rule {
warn!("Failed to parse join rule: {:?}", e);
}
let join_rule = room
.join_rule()
.map(TryInto::try_into)
.transpose()
.inspect_err(|err| {
warn!("Failed to parse join rule: {err}");
})
.ok()
.flatten();
let power_levels = room
.power_levels()
.await
.ok()
.map(|p| RoomPowerLevels::new(p, room.own_user_id().to_owned()));
Ok(Self {
id: room.room_id().to_string(),
encryption_state: room.encryption_state(),
creator: room.creator().as_ref().map(ToString::to_string),
creators: room
.creators()
.map(|creators| creators.into_iter().map(Into::into).collect()),
display_name: room.cached_display_name().map(|name| name.to_string()),
raw_name: room.name(),
topic: room.topic(),
@@ -94,7 +117,7 @@ impl RoomInfo {
is_direct: room.is_direct().await?,
is_public: room.is_public(),
is_space: room.is_space(),
is_tombstoned: room.is_tombstoned(),
successor_room: room.successor_room().map(Into::into),
is_favourite: room.is_favourite(),
canonical_alias: room.canonical_alias().map(Into::into),
alternative_aliases: room.alt_aliases().into_iter().map(Into::into).collect(),
@@ -115,7 +138,6 @@ impl RoomInfo {
active_members_count: room.active_members_count(),
invited_members_count: room.invited_members_count(),
joined_members_count: room.joined_members_count(),
user_power_levels,
highlight_count: unread_notification_counts.highlight_count,
notification_count: unread_notification_counts.notification_count,
cached_user_defined_notification_mode: room
@@ -132,8 +154,15 @@ impl RoomInfo {
num_unread_notifications: room.num_unread_notifications(),
num_unread_mentions: room.num_unread_mentions(),
pinned_event_ids,
join_rule: join_rule.ok(),
join_rule,
history_visibility: room.history_visibility_or_default().try_into()?,
power_levels: power_levels.map(Arc::new),
room_version: room.version().map(|version| version.to_string()),
privileged_creators_role: room
.version()
.and_then(|version| version.rules())
.map(|rules| rules.authorization.explicitly_privilege_room_creators)
.unwrap_or_default(),
})
}
}
@@ -15,28 +15,34 @@
use std::{fmt::Debug, sync::Arc};
use async_compat::get_runtime_handle;
use eyeball_im::VectorDiff;
use futures_util::StreamExt;
use matrix_sdk::room_directory_search::RoomDirectorySearch as SdkRoomDirectorySearch;
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use ruma::ServerName;
use tokio::sync::RwLock;
use crate::{error::ClientError, task_handle::TaskHandle};
use crate::{error::ClientError, runtime::get_runtime_handle, task_handle::TaskHandle};
#[derive(uniffi::Enum)]
pub enum PublicRoomJoinRule {
Public,
Knock,
Restricted,
KnockRestricted,
Invite,
}
impl TryFrom<ruma::directory::PublicRoomJoinRule> for PublicRoomJoinRule {
impl TryFrom<ruma::room::JoinRuleKind> for PublicRoomJoinRule {
type Error = String;
fn try_from(value: ruma::directory::PublicRoomJoinRule) -> Result<Self, Self::Error> {
fn try_from(value: ruma::room::JoinRuleKind) -> Result<Self, Self::Error> {
match value {
ruma::directory::PublicRoomJoinRule::Public => Ok(Self::Public),
ruma::directory::PublicRoomJoinRule::Knock => Ok(Self::Knock),
ruma::room::JoinRuleKind::Public => Ok(Self::Public),
ruma::room::JoinRuleKind::Knock => Ok(Self::Knock),
ruma::room::JoinRuleKind::Restricted => Ok(Self::Restricted),
ruma::room::JoinRuleKind::KnockRestricted => Ok(Self::KnockRestricted),
ruma::room::JoinRuleKind::Invite => Ok(Self::Invite),
rule => Err(format!("unsupported join rule: {rule:?}")),
}
}
@@ -149,11 +155,6 @@ impl RoomDirectorySearch {
}
}
#[derive(uniffi::Record)]
pub struct RoomDirectorySearchEntriesResult {
pub entries_stream: Arc<TaskHandle>,
}
#[derive(uniffi::Enum)]
pub enum RoomDirectorySearchEntryUpdate {
Append { values: Vec<RoomDescription> },
@@ -198,6 +199,6 @@ impl From<VectorDiff<matrix_sdk::room_directory_search::RoomDescription>>
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RoomDirectorySearchEntriesListener: Send + Sync + Debug {
pub trait RoomDirectorySearchEntriesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, room_entries_update: Vec<RoomDirectorySearchEntryUpdate>);
}
+55 -228
View File
@@ -2,33 +2,30 @@
use std::{fmt::Debug, mem::MaybeUninit, ptr::addr_of_mut, sync::Arc, time::Duration};
use async_compat::get_runtime_handle;
use eyeball_im::VectorDiff;
use futures_util::{pin_mut, StreamExt, TryFutureExt};
use matrix_sdk::ruma::{
api::client::sync::sync_events::UnreadNotificationsCount as RumaUnreadNotificationsCount,
RoomId,
use futures_util::{pin_mut, StreamExt};
use matrix_sdk::{
ruma::{
api::client::sync::sync_events::UnreadNotificationsCount as RumaUnreadNotificationsCount,
RoomId,
},
Room as SdkRoom,
};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use matrix_sdk_ui::{
room_list_service::filters::{
new_filter_all, new_filter_any, new_filter_category, new_filter_favourite,
new_filter_fuzzy_match_room_name, new_filter_invite, new_filter_joined,
new_filter_non_left, new_filter_none, new_filter_normalized_match_room_name,
new_filter_unread, BoxedFilterFn, RoomCategory,
new_filter_all, new_filter_any, new_filter_category, new_filter_deduplicate_versions,
new_filter_favourite, new_filter_fuzzy_match_room_name, new_filter_invite,
new_filter_joined, new_filter_low_priority, new_filter_non_left, new_filter_none,
new_filter_normalized_match_room_name, new_filter_not, new_filter_space, new_filter_unread,
BoxedFilterFn, RoomCategory,
},
timeline::default_event_filter,
unable_to_decrypt_hook::UtdHookManager,
};
use ruma::{OwnedRoomOrAliasId, OwnedServerName, ServerName};
use tokio::sync::RwLock;
use crate::{
error::ClientError,
room::{Membership, Room},
room_info::RoomInfo,
room_preview::RoomPreview,
timeline::{configuration::TimelineEventTypeFilter, EventTimelineItem, Timeline},
utils::AsyncRuntimeDropped,
runtime::get_runtime_handle,
TaskHandle,
};
@@ -44,15 +41,12 @@ pub enum RoomListError {
RoomNotFound { room_name: String },
#[error("invalid room ID: {error}")]
InvalidRoomId { error: String },
#[error("A timeline instance already exists for room {room_name}")]
TimelineAlreadyExists { room_name: String },
#[error("A timeline instance hasn't been initialized for room {room_name}")]
TimelineNotInitialized { room_name: String },
#[error("Timeline couldn't be initialized: {error}")]
InitializingTimeline { error: String },
#[error("Event cache ran into an error: {error}")]
EventCache { error: String },
#[error("The requested room doesn't match the membership requirements {expected:?}, observed {actual:?}")]
#[error(
"The requested room doesn't match the membership requirements {expected:?}, \
observed {actual:?}"
)]
IncorrectRoomMembership { expected: Vec<Membership>, actual: Membership },
}
@@ -64,12 +58,6 @@ impl From<matrix_sdk_ui::room_list_service::Error> for RoomListError {
SlidingSync(error) => Self::SlidingSync { error: error.to_string() },
UnknownList(list_name) => Self::UnknownList { list_name },
RoomNotFound(room_id) => Self::RoomNotFound { room_name: room_id.to_string() },
TimelineAlreadyExists(room_id) => {
Self::TimelineAlreadyExists { room_name: room_id.to_string() }
}
InitializingTimeline(source) => {
Self::InitializingTimeline { error: source.to_string() }
}
EventCache(error) => Self::EventCache { error: error.to_string() },
}
}
@@ -101,13 +89,10 @@ impl RoomListService {
})))
}
fn room(&self, room_id: String) -> Result<Arc<RoomListItem>, RoomListError> {
fn room(&self, room_id: String) -> Result<Arc<Room>, RoomListError> {
let room_id = <&RoomId>::try_from(room_id.as_str()).map_err(RoomListError::from)?;
Ok(Arc::new(RoomListItem {
inner: Arc::new(self.inner.room(room_id)?),
utd_hook: self.utd_hook.clone(),
}))
Ok(Arc::new(Room::new(self.inner.room(room_id)?, self.utd_hook.clone())))
}
async fn all_rooms(self: Arc<Self>) -> Result<Arc<RoomList>, RoomListError> {
@@ -137,7 +122,7 @@ impl RoomListService {
})))
}
fn subscribe_to_rooms(&self, room_ids: Vec<String>) -> Result<(), RoomListError> {
async fn subscribe_to_rooms(&self, room_ids: Vec<String>) -> Result<(), RoomListError> {
let room_ids = room_ids
.into_iter()
.map(|room_id| {
@@ -145,7 +130,9 @@ impl RoomListService {
})
.collect::<Result<Vec<_>, _>>()?;
self.inner.subscribe_to_rooms(&room_ids.iter().map(AsRef::as_ref).collect::<Vec<_>>());
self.inner
.subscribe_to_rooms(&room_ids.iter().map(AsRef::as_ref).collect::<Vec<_>>())
.await;
Ok(())
}
@@ -182,8 +169,7 @@ impl RoomList {
page_size: u32,
listener: Box<dyn RoomListEntriesListener>,
) -> Arc<RoomListEntriesWithDynamicAdaptersResult> {
let this = self.clone();
let utd_hook = self.room_list_service.utd_hook.clone();
let this = self;
// The following code deserves a bit of explanation.
// `matrix_sdk_ui::room_list_service::RoomList::entries_with_dynamic_adapters`
@@ -237,6 +223,7 @@ impl RoomList {
let dynamic_entries_controller =
Arc::new(RoomListDynamicEntriesController::new(dynamic_entries_controller));
let utd_hook = this.room_list_service.utd_hook.clone();
let entries_stream = Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
pin_mut!(entries_stream);
@@ -244,7 +231,7 @@ impl RoomList {
listener.on_update(
diffs
.into_iter()
.map(|diff| RoomListEntriesUpdate::from(diff, utd_hook.clone()))
.map(|room| RoomListEntriesUpdate::from(utd_hook.clone(), room))
.collect(),
);
}
@@ -271,7 +258,7 @@ impl RoomList {
Arc::new(unsafe { result.assume_init() })
}
fn room(&self, room_id: String) -> Result<Arc<RoomListItem>, RoomListError> {
fn room(&self, room_id: String) -> Result<Arc<Room>, RoomListError> {
self.room_list_service.room(room_id)
}
}
@@ -362,63 +349,60 @@ impl From<matrix_sdk_ui::room_list_service::RoomListLoadingState> for RoomListLo
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RoomListServiceStateListener: Send + Sync + Debug {
pub trait RoomListServiceStateListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, state: RoomListServiceState);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RoomListLoadingStateListener: Send + Sync + Debug {
pub trait RoomListLoadingStateListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, state: RoomListLoadingState);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RoomListServiceSyncIndicatorListener: Send + Sync + Debug {
pub trait RoomListServiceSyncIndicatorListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, sync_indicator: RoomListServiceSyncIndicator);
}
#[derive(uniffi::Enum)]
pub enum RoomListEntriesUpdate {
Append { values: Vec<Arc<RoomListItem>> },
Append { values: Vec<Arc<Room>> },
Clear,
PushFront { value: Arc<RoomListItem> },
PushBack { value: Arc<RoomListItem> },
PushFront { value: Arc<Room> },
PushBack { value: Arc<Room> },
PopFront,
PopBack,
Insert { index: u32, value: Arc<RoomListItem> },
Set { index: u32, value: Arc<RoomListItem> },
Insert { index: u32, value: Arc<Room> },
Set { index: u32, value: Arc<Room> },
Remove { index: u32 },
Truncate { length: u32 },
Reset { values: Vec<Arc<RoomListItem>> },
Reset { values: Vec<Arc<Room>> },
}
impl RoomListEntriesUpdate {
fn from(
vector_diff: VectorDiff<matrix_sdk_ui::room_list_service::Room>,
utd_hook: Option<Arc<UtdHookManager>>,
) -> Self {
fn from(utd_hook: Option<Arc<UtdHookManager>>, vector_diff: VectorDiff<SdkRoom>) -> Self {
match vector_diff {
VectorDiff::Append { values } => Self::Append {
values: values
.into_iter()
.map(|value| Arc::new(RoomListItem::from(value, utd_hook.clone())))
.map(|value| Arc::new(Room::new(value, utd_hook.clone())))
.collect(),
},
VectorDiff::Clear => Self::Clear,
VectorDiff::PushFront { value } => {
Self::PushFront { value: Arc::new(RoomListItem::from(value, utd_hook)) }
Self::PushFront { value: Arc::new(Room::new(value, utd_hook)) }
}
VectorDiff::PushBack { value } => {
Self::PushBack { value: Arc::new(RoomListItem::from(value, utd_hook)) }
Self::PushBack { value: Arc::new(Room::new(value, utd_hook)) }
}
VectorDiff::PopFront => Self::PopFront,
VectorDiff::PopBack => Self::PopBack,
VectorDiff::Insert { index, value } => Self::Insert {
index: u32::try_from(index).unwrap(),
value: Arc::new(RoomListItem::from(value, utd_hook)),
value: Arc::new(Room::new(value, utd_hook)),
},
VectorDiff::Set { index, value } => Self::Set {
index: u32::try_from(index).unwrap(),
value: Arc::new(RoomListItem::from(value, utd_hook)),
value: Arc::new(Room::new(value, utd_hook)),
},
VectorDiff::Remove { index } => Self::Remove { index: u32::try_from(index).unwrap() },
VectorDiff::Truncate { length } => {
@@ -427,7 +411,7 @@ impl RoomListEntriesUpdate {
VectorDiff::Reset { values } => Self::Reset {
values: values
.into_iter()
.map(|value| Arc::new(RoomListItem::from(value, utd_hook.clone())))
.map(|value| Arc::new(Room::new(value, utd_hook.clone())))
.collect(),
},
}
@@ -435,7 +419,7 @@ impl RoomListEntriesUpdate {
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RoomListEntriesListener: Send + Sync + Debug {
pub trait RoomListEntriesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, room_entries_update: Vec<RoomListEntriesUpdate>);
}
@@ -471,15 +455,21 @@ impl RoomListDynamicEntriesController {
pub enum RoomListEntriesDynamicFilterKind {
All { filters: Vec<RoomListEntriesDynamicFilterKind> },
Any { filters: Vec<RoomListEntriesDynamicFilterKind> },
NonSpace,
NonLeft,
// Not { filter: RoomListEntriesDynamicFilterKind } - requires recursive enum
// support in uniffi https://github.com/mozilla/uniffi-rs/issues/396
Joined,
Unread,
Favourite,
LowPriority,
NonLowPriority,
Invite,
Category { expect: RoomListFilterCategory },
None,
NormalizedMatchRoomName { pattern: String },
FuzzyMatchRoomName { pattern: String },
DeduplicateVersions,
}
#[derive(uniffi::Enum)]
@@ -509,9 +499,12 @@ impl From<RoomListEntriesDynamicFilterKind> for BoxedFilterFn {
filters.into_iter().map(|filter| BoxedFilterFn::from(filter)).collect(),
)),
Kind::NonLeft => Box::new(new_filter_non_left()),
Kind::NonSpace => Box::new(new_filter_not(Box::new(new_filter_space()))),
Kind::Joined => Box::new(new_filter_joined()),
Kind::Unread => Box::new(new_filter_unread()),
Kind::Favourite => Box::new(new_filter_favourite()),
Kind::LowPriority => Box::new(new_filter_low_priority()),
Kind::NonLowPriority => Box::new(new_filter_not(Box::new(new_filter_low_priority()))),
Kind::Invite => Box::new(new_filter_invite()),
Kind::Category { expect } => Box::new(new_filter_category(expect.into())),
Kind::None => Box::new(new_filter_none()),
@@ -521,177 +514,11 @@ impl From<RoomListEntriesDynamicFilterKind> for BoxedFilterFn {
Kind::FuzzyMatchRoomName { pattern } => {
Box::new(new_filter_fuzzy_match_room_name(&pattern))
}
Kind::DeduplicateVersions => Box::new(new_filter_deduplicate_versions()),
}
}
}
#[derive(uniffi::Object)]
pub struct RoomListItem {
inner: Arc<matrix_sdk_ui::room_list_service::Room>,
utd_hook: Option<Arc<UtdHookManager>>,
}
impl RoomListItem {
fn from(
value: matrix_sdk_ui::room_list_service::Room,
utd_hook: Option<Arc<UtdHookManager>>,
) -> Self {
Self { inner: Arc::new(value), utd_hook }
}
}
#[matrix_sdk_ffi_macros::export]
impl RoomListItem {
fn id(&self) -> String {
self.inner.id().to_string()
}
/// Returns the room's name from the state event if available, otherwise
/// compute a room name based on the room's nature (DM or not) and number of
/// members.
fn display_name(&self) -> Option<String> {
self.inner.cached_display_name()
}
fn avatar_url(&self) -> Option<String> {
self.inner.avatar_url().map(|uri| uri.to_string())
}
async fn is_direct(&self) -> bool {
self.inner.inner_room().is_direct().await.unwrap_or(false)
}
fn canonical_alias(&self) -> Option<String> {
self.inner.inner_room().canonical_alias().map(|alias| alias.to_string())
}
async fn room_info(&self) -> Result<RoomInfo, ClientError> {
RoomInfo::new(self.inner.inner_room()).await
}
/// The room's current membership state.
fn membership(&self) -> Membership {
self.inner.inner_room().state().into()
}
/// Builds a `RoomPreview` from a room list item. This is intended for
/// invited, knocked or banned rooms.
async fn preview_room(&self, via: Vec<String>) -> Result<Arc<RoomPreview>, ClientError> {
// Validate parameters first.
let server_names: Vec<OwnedServerName> = via
.into_iter()
.map(|server| ServerName::parse(server).map_err(ClientError::from))
.collect::<Result<_, ClientError>>()?;
// Do the thing.
let client = self.inner.client();
let (room_or_alias_id, mut server_names) = if let Some(alias) = self.inner.canonical_alias()
{
let room_or_alias_id: OwnedRoomOrAliasId = alias.into();
(room_or_alias_id, Vec::new())
} else {
let room_or_alias_id: OwnedRoomOrAliasId = self.inner.id().to_owned().into();
(room_or_alias_id, server_names)
};
// If no server names are provided and the room's membership is invited,
// add the server name from the sender's user id as a fallback value
if server_names.is_empty() {
if let Ok(invite_details) = self.inner.invite_details().await {
if let Some(inviter) = invite_details.inviter {
server_names.push(inviter.user_id().server_name().to_owned());
}
}
}
let room_preview = client.get_room_preview(&room_or_alias_id, server_names).await?;
Ok(Arc::new(RoomPreview::new(AsyncRuntimeDropped::new(client), room_preview)))
}
/// Build a full `Room` FFI object, filling its associated timeline.
///
/// An error will be returned if the room is a state different than joined
/// or if its internal timeline hasn't been initialized.
fn full_room(&self) -> Result<Arc<Room>, RoomListError> {
if !matches!(self.membership(), Membership::Joined) {
return Err(RoomListError::IncorrectRoomMembership {
expected: vec![Membership::Joined],
actual: self.membership(),
});
}
if let Some(timeline) = self.inner.timeline() {
Ok(Arc::new(Room::with_timeline(
self.inner.inner_room().clone(),
Arc::new(RwLock::new(Some(Timeline::from_arc(timeline)))),
)))
} else {
Err(RoomListError::TimelineNotInitialized {
room_name: self.inner.inner_room().room_id().to_string(),
})
}
}
/// Checks whether the Room's timeline has been initialized before.
fn is_timeline_initialized(&self) -> bool {
self.inner.is_timeline_initialized()
}
/// Initializes the timeline for this room using the provided parameters.
///
/// * `event_type_filter` - An optional [`TimelineEventTypeFilter`] to be
/// used to filter timeline events besides the default timeline filter. If
/// `None` is passed, only the default timeline filter will be used.
/// * `internal_id_prefix` - An optional String that will be prepended to
/// all the timeline item's internal IDs, making it possible to
/// distinguish different timeline instances from each other.
async fn init_timeline(
&self,
event_type_filter: Option<Arc<TimelineEventTypeFilter>>,
internal_id_prefix: Option<String>,
) -> Result<(), RoomListError> {
let mut timeline_builder = self
.inner
.default_room_timeline_builder()
.await
.map_err(|err| RoomListError::InitializingTimeline { error: err.to_string() })?;
if let Some(event_type_filter) = event_type_filter {
timeline_builder = timeline_builder.event_filter(move |event, room_version_id| {
// Always perform the default filter first
default_event_filter(event, room_version_id) && event_type_filter.filter(event)
});
}
if let Some(internal_id_prefix) = internal_id_prefix {
timeline_builder = timeline_builder.with_internal_id_prefix(internal_id_prefix);
}
if let Some(utd_hook) = self.utd_hook.clone() {
timeline_builder = timeline_builder.with_unable_to_decrypt_hook(utd_hook);
}
self.inner.init_timeline_with_builder(timeline_builder).map_err(RoomListError::from).await
}
/// Checks whether the room is encrypted or not.
///
/// **Note**: this info may not be reliable if you don't set up
/// `m.room.encryption` as required state.
async fn is_encrypted(&self) -> bool {
self.inner
.latest_encryption_state()
.await
.map(|state| state.is_encrypted())
.unwrap_or(false)
}
async fn latest_event(&self) -> Option<EventTimelineItem> {
self.inner.latest_event().await.map(Into::into)
}
}
#[derive(uniffi::Object)]
pub struct UnreadNotificationsCount {
highlight_count: u32,
+57 -9
View File
@@ -1,5 +1,5 @@
use matrix_sdk::room::{RoomMember as SdkRoomMember, RoomMemberRole};
use ruma::UserId;
use ruma::{events::room::power_levels::UserPowerLevel, UserId};
use crate::error::{ClientError, NotYetImplemented};
@@ -57,16 +57,25 @@ impl TryFrom<matrix_sdk::ruma::events::room::member::MembershipState> for Member
}
}
/// Get the suggested role for the given power level.
///
/// Returns an error if the value of the power level is out of range for numbers
/// accepted in canonical JSON.
#[matrix_sdk_ffi_macros::export]
pub fn suggested_role_for_power_level(power_level: i64) -> RoomMemberRole {
pub fn suggested_role_for_power_level(
power_level: PowerLevel,
) -> Result<RoomMemberRole, ClientError> {
// It's not possible to expose the constructor on the Enum through Uniffi ☹️
RoomMemberRole::suggested_role_for_power_level(power_level)
Ok(RoomMemberRole::suggested_role_for_power_level(power_level.try_into()?))
}
/// Get the suggested power level for the given role.
///
/// Returns an error if the value of the power level is unsupported.
#[matrix_sdk_ffi_macros::export]
pub fn suggested_power_level_for_role(role: RoomMemberRole) -> i64 {
pub fn suggested_power_level_for_role(role: RoomMemberRole) -> Result<PowerLevel, ClientError> {
// It's not possible to expose methods on an Enum through Uniffi ☹️
role.suggested_power_level()
Ok(role.suggested_power_level().try_into()?)
}
/// Generates a `matrix.to` permalink to the given userID.
@@ -83,8 +92,8 @@ pub struct RoomMember {
pub avatar_url: Option<String>,
pub membership: MembershipState,
pub is_name_ambiguous: bool,
pub power_level: i64,
pub normalized_power_level: i64,
pub power_level: PowerLevel,
pub normalized_power_level: PowerLevel,
pub is_ignored: bool,
pub suggested_role_for_power_level: RoomMemberRole,
pub membership_change_reason: Option<String>,
@@ -100,8 +109,8 @@ impl TryFrom<SdkRoomMember> for RoomMember {
avatar_url: m.avatar_url().map(|a| a.to_string()),
membership: m.membership().clone().try_into()?,
is_name_ambiguous: m.name_ambiguous(),
power_level: m.power_level(),
normalized_power_level: m.normalized_power_level(),
power_level: m.power_level().try_into()?,
normalized_power_level: m.normalized_power_level().try_into()?,
is_ignored: m.is_ignored(),
suggested_role_for_power_level: m.suggested_role_for_power_level(),
membership_change_reason: m.event().reason().map(|s| s.to_owned()),
@@ -130,3 +139,42 @@ impl TryFrom<matrix_sdk::room::RoomMemberWithSenderInfo> for RoomMemberWithSende
})
}
}
#[derive(Clone, uniffi::Enum)]
pub enum PowerLevel {
/// The user is a room creator and has infinite power level.
///
/// This power level was introduced in room version 12.
Infinite,
/// The user has the given power level.
Value { value: i64 },
}
impl TryFrom<UserPowerLevel> for PowerLevel {
type Error = NotYetImplemented;
fn try_from(value: UserPowerLevel) -> Result<Self, Self::Error> {
match value {
UserPowerLevel::Infinite => Ok(Self::Infinite),
UserPowerLevel::Int(value) => Ok(Self::Value { value: value.into() }),
_ => Err(NotYetImplemented),
}
}
}
impl TryFrom<PowerLevel> for UserPowerLevel {
type Error = ClientError;
fn try_from(value: PowerLevel) -> Result<Self, Self::Error> {
Ok(match value {
PowerLevel::Infinite => Self::Infinite,
PowerLevel::Value { value } => {
Self::Int(value.try_into().map_err(|err| ClientError::Generic {
msg: "Power level is out of range".to_owned(),
details: Some(format!("{err:?}")),
})?)
}
})
}
}
+34 -41
View File
@@ -1,10 +1,9 @@
use anyhow::Context as _;
use matrix_sdk::{room_preview::RoomPreview as SdkRoomPreview, Client};
use ruma::{room::RoomType as RumaRoomType, space::SpaceRoomJoinRule};
use tracing::warn;
use ruma::room::{JoinRuleSummary, RoomType as RumaRoomType};
use crate::{
client::JoinRule,
client::{AllowRule, JoinRule},
error::ClientError,
room::{Membership, RoomHero},
room_member::{RoomMember, RoomMemberWithSenderInfo},
@@ -22,9 +21,9 @@ pub struct RoomPreview {
#[matrix_sdk_ffi_macros::export]
impl RoomPreview {
/// Returns the room info the preview contains.
pub fn info(&self) -> Result<RoomPreviewInfo, ClientError> {
pub fn info(&self) -> RoomPreviewInfo {
let info = &self.inner;
Ok(RoomPreviewInfo {
RoomPreviewInfo {
room_id: info.room_id.to_string(),
canonical_alias: info.canonical_alias.as_ref().map(|alias| alias.to_string()),
name: info.name.clone(),
@@ -32,20 +31,16 @@ impl RoomPreview {
avatar_url: info.avatar_url.as_ref().map(|url| url.to_string()),
num_joined_members: info.num_joined_members,
num_active_members: info.num_active_members,
room_type: info.room_type.as_ref().into(),
room_type: info.room_type.clone().into(),
is_history_world_readable: info.is_world_readable,
membership: info.state.map(|state| state.into()),
join_rule: info
.join_rule
.clone()
.try_into()
.map_err(|_| anyhow::anyhow!("unhandled SpaceRoomJoinRule kind"))?,
join_rule: info.join_rule.clone().map(Into::into),
is_direct: info.is_direct,
heroes: info
.heroes
.as_ref()
.map(|heroes| heroes.iter().map(|h| h.to_owned().into()).collect()),
})
}
}
/// Leave the room if the room preview state is either joined, invited or
@@ -59,15 +54,7 @@ impl RoomPreview {
let room =
self.client.get_room(&self.inner.room_id).context("missing room for a room preview")?;
let should_forget = matches!(room.state(), matrix_sdk::RoomState::Invited);
room.leave().await.map_err(ClientError::from)?;
if should_forget {
_ = self.forget().await;
}
Ok(())
Ok(room.leave().await?)
}
/// Get the user who created the invite, if any.
@@ -122,30 +109,36 @@ pub struct RoomPreviewInfo {
/// The membership state for the current user, if known.
pub membership: Option<Membership>,
/// The join rule for this room (private, public, knock, etc.).
pub join_rule: JoinRule,
pub join_rule: Option<JoinRule>,
/// Whether the room is direct or not, if known.
pub is_direct: Option<bool>,
/// Room heroes.
pub heroes: Option<Vec<RoomHero>>,
}
impl TryFrom<SpaceRoomJoinRule> for JoinRule {
type Error = ();
fn try_from(join_rule: SpaceRoomJoinRule) -> Result<Self, ()> {
Ok(match join_rule {
SpaceRoomJoinRule::Invite => JoinRule::Invite,
SpaceRoomJoinRule::Knock => JoinRule::Knock,
SpaceRoomJoinRule::Private => JoinRule::Private,
SpaceRoomJoinRule::Restricted => JoinRule::Restricted { rules: Vec::new() },
SpaceRoomJoinRule::KnockRestricted => JoinRule::KnockRestricted { rules: Vec::new() },
SpaceRoomJoinRule::Public => JoinRule::Public,
SpaceRoomJoinRule::_Custom(_) => JoinRule::Custom { repr: join_rule.to_string() },
_ => {
warn!("unhandled SpaceRoomJoinRule: {join_rule}");
return Err(());
}
})
impl From<JoinRuleSummary> for JoinRule {
fn from(join_rule: JoinRuleSummary) -> Self {
match join_rule {
JoinRuleSummary::Invite => JoinRule::Invite,
JoinRuleSummary::Knock => JoinRule::Knock,
JoinRuleSummary::Private => JoinRule::Private,
JoinRuleSummary::Restricted(summary) => JoinRule::Restricted {
rules: summary
.allowed_room_ids
.iter()
.map(|room_id| AllowRule::RoomMembership { room_id: room_id.to_string() })
.collect(),
},
JoinRuleSummary::KnockRestricted(summary) => JoinRule::KnockRestricted {
rules: summary
.allowed_room_ids
.iter()
.map(|room_id| AllowRule::RoomMembership { room_id: room_id.to_string() })
.collect(),
},
JoinRuleSummary::Public => JoinRule::Public,
_ => JoinRule::Custom { repr: join_rule.as_str().to_owned() },
}
}
}
@@ -160,8 +153,8 @@ pub enum RoomType {
Custom { value: String },
}
impl From<Option<&RumaRoomType>> for RoomType {
fn from(value: Option<&RumaRoomType>) -> Self {
impl From<Option<RumaRoomType>> for RoomType {
fn from(value: Option<RumaRoomType>) -> Self {
match value {
Some(RumaRoomType::Space) => RoomType::Space,
Some(RumaRoomType::_Custom(_)) => RoomType::Custom {
File diff suppressed because it is too large Load Diff
+110
View File
@@ -0,0 +1,110 @@
// Copyright 2025 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Runtime abstractions for cross-platform async execution. This provides
//! a stand-in for tokio's `get_runtime_handle` method that will work on
//! both Wasm and non-Wasm platforms. It also provides corresponding types
//! that can be used in place of tokio's `Handle` and `Runtime` types.
#[cfg(not(target_family = "wasm"))]
mod sys {
pub use tokio::runtime::Handle;
/// Get a runtime handle appropriate for the current target platform.
///
/// This function returns a unified `Handle` type that works across both
/// Wasm and non-Wasm platforms, allowing code to be written that is
/// agnostic to the platform-specific runtime implementation.
///
/// Returns:
/// - A `tokio::runtime::Handle` on non-Wasm platforms
/// - A `WasmRuntimeHandle` on Wasm platforms
pub fn get_runtime_handle() -> Handle {
async_compat::get_runtime_handle()
}
}
#[cfg(target_family = "wasm")]
mod sys {
use std::future::Future;
use matrix_sdk_common::executor::{spawn, JoinHandle};
/// A dummy guard that does nothing when dropped.
/// This is used for the Wasm implementation to match
/// tokio::runtime::EnterGuard.
#[derive(Debug)]
pub struct RuntimeGuard;
/// A runtime handle implementation for WebAssembly targets.
///
/// This implements a minimal subset of the tokio::runtime::Handle API
/// that is needed for the matrix-rust-sdk to function on Wasm.
#[derive(Default, Debug)]
pub struct Handle;
pub type Runtime = Handle;
impl Handle {
/// Spawns a future in the wasm32 bindgen runtime.
#[track_caller]
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + 'static,
F::Output: 'static,
{
spawn(future)
}
/// Runs the provided function on an executor dedicated to blocking
/// operations.
#[track_caller]
pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + 'static,
R: 'static,
{
spawn(async move { func() })
}
/// Runs a future to completion on the current thread.
pub fn block_on<F, T>(&self, future: F) -> T
where
F: Future<Output = T>,
{
futures_executor::block_on(future)
}
/// Enters the runtime context.
///
/// For WebAssembly, this is a no-op that returns a dummy guard.
pub fn enter(&self) -> RuntimeGuard {
RuntimeGuard
}
}
/// Get a runtime handle appropriate for the current target platform.
///
/// This function returns a unified `Handle` type that works across both
/// Wasm and non-Wasm platforms, allowing code to be written that is
/// agnostic to the platform-specific runtime implementation.
///
/// Returns:
/// - A `tokio::runtime::Handle` on non-Wasm platforms
/// - A `WasmRuntimeHandle` on Wasm platforms
pub fn get_runtime_handle() -> Handle {
Handle
}
}
pub use sys::*;
@@ -1,6 +1,5 @@
use std::sync::{Arc, RwLock};
use async_compat::get_runtime_handle;
use futures_util::StreamExt;
use matrix_sdk::{
encryption::{
@@ -11,10 +10,13 @@ use matrix_sdk::{
ruma::events::key::verification::VerificationMethod,
Account,
};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use ruma::UserId;
use tracing::{error, warn};
use crate::{client::UserProfile, error::ClientError, utils::Timestamp};
use crate::{
client::UserProfile, error::ClientError, runtime::get_runtime_handle, utils::Timestamp,
};
#[derive(uniffi::Object)]
pub struct SessionVerificationEmoji {
@@ -51,7 +53,7 @@ pub struct SessionVerificationRequestDetails {
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SessionVerificationControllerDelegate: Sync + Send {
pub trait SessionVerificationControllerDelegate: SyncOutsideWasm + SendOutsideWasm {
fn did_receive_verification_request(&self, details: SessionVerificationRequestDetails);
fn did_accept_verification_request(&self);
fn did_start_sas_verification(&self);
@@ -94,7 +96,7 @@ impl SessionVerificationController {
.encryption
.get_verification_request(&sender_id, flow_id)
.await
.ok_or(ClientError::new("Unknown session verification request"))?;
.ok_or(ClientError::from_str("Unknown session verification request", None))?;
self.set_ongoing_verification_request(verification_request)
}
@@ -114,11 +116,8 @@ impl SessionVerificationController {
/// Request verification for the current device
pub async fn request_device_verification(&self) -> Result<(), ClientError> {
let methods = vec![VerificationMethod::SasV1];
let verification_request = self
.user_identity
.request_verification_with_methods(methods)
.await
.map_err(anyhow::Error::from)?;
let verification_request =
self.user_identity.request_verification_with_methods(methods).await?;
self.set_ongoing_verification_request(verification_request)
}
@@ -131,18 +130,15 @@ impl SessionVerificationController {
.encryption
.get_user_identity(&user_id)
.await?
.ok_or(ClientError::new("Unknown user identity"))?;
.ok_or(ClientError::from_str("Unknown user identity", None))?;
if user_identity.is_verified() {
return Err(ClientError::new("User is already verified"));
return Err(ClientError::from_str("User is already verified", None));
}
let methods = vec![VerificationMethod::SasV1];
let verification_request = user_identity
.request_verification_with_methods(methods)
.await
.map_err(anyhow::Error::from)?;
let verification_request = user_identity.request_verification_with_methods(methods).await?;
self.set_ongoing_verification_request(verification_request)
}
@@ -153,7 +149,7 @@ impl SessionVerificationController {
let verification_request = self.verification_request.read().unwrap().clone();
let Some(verification_request) = verification_request else {
return Err(ClientError::new("Verification request missing."));
return Err(ClientError::from_str("Verification request missing.", None));
};
match verification_request.start_sas().await {
@@ -183,7 +179,7 @@ impl SessionVerificationController {
let sas_verification = self.sas_verification.read().unwrap().clone();
let Some(sas_verification) = sas_verification else {
return Err(ClientError::new("SAS verification missing"));
return Err(ClientError::from_str("SAS verification missing", None));
};
Ok(sas_verification.confirm().await?)
@@ -194,7 +190,7 @@ impl SessionVerificationController {
let sas_verification = self.sas_verification.read().unwrap().clone();
let Some(sas_verification) = sas_verification else {
return Err(ClientError::new("SAS verification missing"));
return Err(ClientError::from_str("SAS verification missing", None));
};
Ok(sas_verification.mismatch().await?)
@@ -205,7 +201,7 @@ impl SessionVerificationController {
let verification_request = self.verification_request.read().unwrap().clone();
let Some(verification_request) = verification_request else {
return Err(ClientError::new("Verification request missing."));
return Err(ClientError::from_str("Verification request missing.", None));
};
Ok(verification_request.cancel().await?)
@@ -239,7 +235,10 @@ impl SessionVerificationController {
if sender != self.user_identity.user_id() {
if let Some(status) = self.encryption.cross_signing_status().await {
if !status.is_complete() {
warn!("Cannot verify other users until our own device's cross-signing status is complete: {:?}", status);
warn!(
"Cannot verify other users until our own device's cross-signing status \
is complete: {status:?}"
);
return;
}
}
@@ -255,18 +254,14 @@ impl SessionVerificationController {
return;
};
let Ok(sender_profile) = self.account.fetch_user_profile_of(sender).await else {
let Ok(sender_profile) = UserProfile::fetch(&self.account, sender).await else {
error!("Failed fetching user profile for verification request");
return;
};
if let Some(delegate) = &*self.delegate.read().unwrap() {
delegate.did_receive_verification_request(SessionVerificationRequestDetails {
sender_profile: UserProfile {
user_id: request.other_user_id().to_string(),
display_name: sender_profile.displayname,
avatar_url: sender_profile.avatar_url.as_ref().map(|url| url.to_string()),
},
sender_profile,
flow_id: request.flow_id().into(),
device_id: other_device_data.device_id().into(),
device_display_name: other_device_data.display_name().map(str::to_string),
@@ -285,7 +280,10 @@ impl SessionVerificationController {
if !ongoing_verification_request.is_done()
&& !ongoing_verification_request.is_cancelled()
{
return Err(ClientError::new("There is another verification flow ongoing."));
return Err(ClientError::from_str(
"There is another verification flow ongoing.",
None,
));
}
}
+276
View File
@@ -0,0 +1,276 @@
// Copyright 2025 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{fmt::Debug, sync::Arc};
use eyeball_im::VectorDiff;
use futures_util::{pin_mut, StreamExt};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use matrix_sdk_ui::spaces::{
room_list::SpaceRoomListPaginationState, SpaceRoom as UISpaceRoom,
SpaceRoomList as UISpaceRoomList, SpaceService as UISpaceService,
};
use ruma::RoomId;
use crate::{
client::JoinRule,
error::ClientError,
room::{Membership, RoomHero},
room_preview::RoomType,
runtime::get_runtime_handle,
TaskHandle,
};
/// The main entry point into the Spaces facilities.
///
/// The spaces service is responsible for retrieving one's joined rooms,
/// building a graph out of their `m.space.parent` and `m.space.child` state
/// events, and providing access to the top-level spaces and their children.
#[derive(uniffi::Object)]
pub struct SpaceService {
inner: UISpaceService,
}
impl SpaceService {
/// Creates a new `SpaceService` instance.
pub(crate) fn new(inner: UISpaceService) -> Self {
Self { inner }
}
}
#[matrix_sdk_ffi_macros::export]
impl SpaceService {
/// Returns a list of all the top-level joined spaces. It will eagerly
/// compute the latest version and also notify subscribers if there were
/// any changes.
pub async fn joined_spaces(&self) -> Vec<SpaceRoom> {
self.inner.joined_spaces().await.into_iter().map(Into::into).collect()
}
/// Subscribes to updates on the joined spaces list. If space rooms are
/// joined or left, the stream will yield diffs that reflect the changes.
pub async fn subscribe_to_joined_spaces(
&self,
listener: Box<dyn SpaceServiceJoinedSpacesListener>,
) -> Arc<TaskHandle> {
let (initial_values, mut stream) = self.inner.subscribe_to_joined_spaces().await;
listener.on_update(vec![SpaceListUpdate::Reset {
values: initial_values.into_iter().map(Into::into).collect(),
}]);
Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
while let Some(diffs) = stream.next().await {
listener.on_update(diffs.into_iter().map(Into::into).collect());
}
})))
}
/// Returns a `SpaceRoomList` for the given space ID.
#[allow(clippy::unused_async)]
// This method doesn't need to be async but if its not the FFI layer panics
// with "there is no no reactor running, must be called from the context
// of a Tokio 1.x runtime" error because the underlying constructor spawns
// an async task.
pub async fn space_room_list(
&self,
space_id: String,
) -> Result<Arc<SpaceRoomList>, ClientError> {
let space_id = RoomId::parse(space_id)?;
Ok(Arc::new(SpaceRoomList::new(self.inner.space_room_list(space_id))))
}
}
/// The `SpaceRoomList`represents a paginated list of direct rooms
/// that belong to a particular space.
///
/// It can be used to paginate through the list (and have live updates on the
/// pagination state) as well as subscribe to changes as rooms are joined or
/// left.
///
/// The `SpaceRoomList` also automatically subscribes to client room changes
/// and updates the list accordingly as rooms are joined or left.
#[derive(uniffi::Object)]
pub struct SpaceRoomList {
inner: UISpaceRoomList,
}
impl SpaceRoomList {
/// Creates a new `SpaceRoomList` for the underlying UI crate room list.
fn new(inner: UISpaceRoomList) -> Self {
Self { inner }
}
}
#[matrix_sdk_ffi_macros::export]
impl SpaceRoomList {
/// Returns if the room list is currently paginating or not.
pub fn pagination_state(&self) -> SpaceRoomListPaginationState {
self.inner.pagination_state()
}
/// Subscribe to pagination updates.
pub fn subscribe_to_pagination_state_updates(
&self,
listener: Box<dyn SpaceRoomListPaginationStateListener>,
) -> Arc<TaskHandle> {
let pagination_state = self.inner.subscribe_to_pagination_state_updates();
Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
pin_mut!(pagination_state);
while let Some(state) = pagination_state.next().await {
listener.on_update(state);
}
})))
}
/// Return the current list of rooms.
pub fn rooms(&self) -> Vec<SpaceRoom> {
self.inner.rooms().into_iter().map(Into::into).collect()
}
/// Subscribes to room list updates.
pub fn subscribe_to_room_update(
&self,
listener: Box<dyn SpaceRoomListEntriesListener>,
) -> Arc<TaskHandle> {
let (initial_values, mut stream) = self.inner.subscribe_to_room_updates();
listener.on_update(vec![SpaceListUpdate::Reset {
values: initial_values.into_iter().map(Into::into).collect(),
}]);
Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
while let Some(diffs) = stream.next().await {
listener.on_update(diffs.into_iter().map(Into::into).collect());
}
})))
}
/// Ask the list to retrieve the next page if the end hasn't been reached
/// yet. Otherwise it no-ops.
pub async fn paginate(&self) -> Result<(), ClientError> {
self.inner.paginate().await.map_err(ClientError::from)
}
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceRoomListPaginationStateListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, pagination_state: SpaceRoomListPaginationState);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceRoomListEntriesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, rooms: Vec<SpaceListUpdate>);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceServiceJoinedSpacesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, room_updates: Vec<SpaceListUpdate>);
}
/// Structure representing a room in a space and aggregated information
/// relevant to the UI layer.
#[derive(uniffi::Record)]
pub struct SpaceRoom {
/// The ID of the room.
pub room_id: String,
/// The canonical alias of the room, if any.
pub canonical_alias: Option<String>,
/// The name of the room, if any.
pub name: Option<String>,
/// The topic of the room, if any.
pub topic: Option<String>,
/// The URL for the room's avatar, if one is set.
pub avatar_url: Option<String>,
/// The type of room from `m.room.create`, if any.
pub room_type: RoomType,
/// The number of members joined to the room.
pub num_joined_members: u64,
/// The join rule of the room.
pub join_rule: Option<JoinRule>,
/// Whether the room may be viewed by users without joining.
pub world_readable: Option<bool>,
/// Whether guest users may join the room and participate in it.
pub guest_can_join: bool,
/// The number of children room this has, if a space.
pub children_count: u64,
/// Whether this room is joined, left etc.
pub state: Option<Membership>,
/// A list of room members considered to be heroes.
pub heroes: Option<Vec<RoomHero>>,
}
impl From<UISpaceRoom> for SpaceRoom {
fn from(room: UISpaceRoom) -> Self {
Self {
room_id: room.room_id.into(),
canonical_alias: room.canonical_alias.map(|alias| alias.into()),
name: room.name,
topic: room.topic,
avatar_url: room.avatar_url.map(|url| url.into()),
room_type: room.room_type.into(),
num_joined_members: room.num_joined_members,
join_rule: room.join_rule.map(Into::into),
world_readable: room.world_readable,
guest_can_join: room.guest_can_join,
children_count: room.children_count,
state: room.state.map(Into::into),
heroes: room.heroes.map(|heroes| heroes.into_iter().map(Into::into).collect()),
}
}
}
#[derive(uniffi::Enum)]
pub enum SpaceListUpdate {
Append { values: Vec<SpaceRoom> },
Clear,
PushFront { value: SpaceRoom },
PushBack { value: SpaceRoom },
PopFront,
PopBack,
Insert { index: u32, value: SpaceRoom },
Set { index: u32, value: SpaceRoom },
Remove { index: u32 },
Truncate { length: u32 },
Reset { values: Vec<SpaceRoom> },
}
impl From<VectorDiff<UISpaceRoom>> for SpaceListUpdate {
fn from(diff: VectorDiff<UISpaceRoom>) -> Self {
match diff {
VectorDiff::Append { values } => {
Self::Append { values: values.into_iter().map(|v| v.into()).collect() }
}
VectorDiff::Clear => Self::Clear,
VectorDiff::PushFront { value } => Self::PushFront { value: value.into() },
VectorDiff::PushBack { value } => Self::PushBack { value: value.into() },
VectorDiff::PopFront => Self::PopFront,
VectorDiff::PopBack => Self::PopBack,
VectorDiff::Insert { index, value } => {
Self::Insert { index: index as u32, value: value.into() }
}
VectorDiff::Set { index, value } => {
Self::Set { index: index as u32, value: value.into() }
}
VectorDiff::Remove { index } => Self::Remove { index: index as u32 },
VectorDiff::Truncate { length } => Self::Truncate { length: length as u32 },
VectorDiff::Reset { values } => {
Self::Reset { values: values.into_iter().map(|v| v.into()).collect() }
}
}
}
}
+23 -122
View File
@@ -12,24 +12,22 @@
// See the License for that specific language governing permissions and
// limitations under the License.
use std::{fmt::Debug, sync::Arc, time::Duration};
use std::{fmt::Debug, sync::Arc};
use async_compat::get_runtime_handle;
use futures_util::pin_mut;
use matrix_sdk::{crypto::types::events::UtdCause, Client};
use matrix_sdk::Client;
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use matrix_sdk_ui::{
sync_service::{
State as MatrixSyncServiceState, SyncService as MatrixSyncService,
SyncServiceBuilder as MatrixSyncServiceBuilder,
},
unable_to_decrypt_hook::{
UnableToDecryptHook, UnableToDecryptInfo as SdkUnableToDecryptInfo, UtdHookManager,
},
unable_to_decrypt_hook::UtdHookManager,
};
use tracing::error;
use crate::{
error::ClientError, helpers::unwrap_or_clone_arc, room_list::RoomListService, TaskHandle,
error::ClientError, helpers::unwrap_or_clone_arc, room_list::RoomListService,
runtime::get_runtime_handle, TaskHandle,
};
#[derive(uniffi::Enum)]
@@ -54,7 +52,7 @@ impl From<MatrixSyncServiceState> for SyncServiceState {
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SyncServiceStateObserver: Send + Sync + Debug {
pub trait SyncServiceStateObserver: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, state: SyncServiceState);
}
@@ -92,23 +90,26 @@ impl SyncService {
}
})))
}
/// Force expiring both sliding sync sessions.
///
/// This ensures that the sync service is stopped before expiring both
/// sessions. It should be used sparingly, as it will cause a restart of
/// the sessions on the server as well.
pub async fn expire_sessions(&self) {
self.inner.expire_sessions().await;
}
}
#[derive(Clone, uniffi::Object)]
pub struct SyncServiceBuilder {
client: Client,
builder: MatrixSyncServiceBuilder,
utd_hook: Option<Arc<UtdHookManager>>,
}
impl SyncServiceBuilder {
pub(crate) fn new(client: Client) -> Arc<Self> {
Arc::new(Self {
client: client.clone(),
builder: MatrixSyncService::builder(client),
utd_hook: None,
})
pub(crate) fn new(client: Client, utd_hook: Option<Arc<UtdHookManager>>) -> Arc<Self> {
Arc::new(Self { builder: MatrixSyncService::builder(client), utd_hook })
}
}
@@ -117,40 +118,20 @@ impl SyncServiceBuilder {
pub fn with_cross_process_lock(self: Arc<Self>) -> Arc<Self> {
let this = unwrap_or_clone_arc(self);
let builder = this.builder.with_cross_process_lock();
Arc::new(Self { client: this.client, builder, utd_hook: this.utd_hook })
Arc::new(Self { builder, ..this })
}
/// Enable the "offline" mode for the [`SyncService`].
pub fn with_offline_mode(self: Arc<Self>) -> Arc<Self> {
let this = unwrap_or_clone_arc(self);
let builder = this.builder.with_offline_mode();
Arc::new(Self { client: this.client, builder, utd_hook: this.utd_hook })
Arc::new(Self { builder, ..this })
}
pub async fn with_utd_hook(
self: Arc<Self>,
delegate: Box<dyn UnableToDecryptDelegate>,
) -> Arc<Self> {
// UTDs detected before this duration may be reclassified as "late decryption"
// events (or discarded, if they get decrypted fast enough).
const UTD_HOOK_GRACE_PERIOD: Duration = Duration::from_secs(60);
pub fn with_share_pos(self: Arc<Self>, enable: bool) -> Arc<Self> {
let this = unwrap_or_clone_arc(self);
let mut utd_hook = UtdHookManager::new(Arc::new(UtdHook { delegate }), this.client.clone())
.with_max_delay(UTD_HOOK_GRACE_PERIOD);
if let Err(e) = utd_hook.reload_from_store().await {
error!("Unable to reload UTD hook data from data store: {}", e);
// Carry on with the setup anyway; we shouldn't fail setup just
// because the UTD hook failed to load its data.
}
Arc::new(Self {
client: this.client,
builder: this.builder,
utd_hook: Some(Arc::new(utd_hook)),
})
let builder = this.builder.with_share_pos(enable);
Arc::new(Self { builder, ..this })
}
pub async fn finish(self: Arc<Self>) -> Result<Arc<SyncService>, ClientError> {
@@ -161,83 +142,3 @@ impl SyncServiceBuilder {
}))
}
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait UnableToDecryptDelegate: Sync + Send {
fn on_utd(&self, info: UnableToDecryptInfo);
}
struct UtdHook {
delegate: Box<dyn UnableToDecryptDelegate>,
}
impl std::fmt::Debug for UtdHook {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UtdHook").finish_non_exhaustive()
}
}
impl UnableToDecryptHook for UtdHook {
fn on_utd(&self, info: SdkUnableToDecryptInfo) {
const IGNORE_UTD_PERIOD: Duration = Duration::from_secs(4);
// UTDs that have been decrypted in the `IGNORE_UTD_PERIOD` are just ignored and
// not considered UTDs.
if let Some(duration) = &info.time_to_decrypt {
if *duration < IGNORE_UTD_PERIOD {
return;
}
}
// Report the UTD to the client.
self.delegate.on_utd(info.into());
}
}
#[derive(uniffi::Record)]
pub struct UnableToDecryptInfo {
/// The identifier of the event that couldn't get decrypted.
event_id: String,
/// If the event could be decrypted late (that is, the event was encrypted
/// at first, but could be decrypted later on), then this indicates the
/// time it took to decrypt the event. If it is not set, this is
/// considered a definite UTD.
///
/// If set, this is in milliseconds.
pub time_to_decrypt_ms: Option<u64>,
/// What we know about what caused this UTD. E.g. was this event sent when
/// we were not a member of this room?
pub cause: UtdCause,
/// The difference between the event creation time (`origin_server_ts`) and
/// the time our device was created. If negative, this event was sent
/// *before* our device was created.
pub event_local_age_millis: i64,
/// Whether the user had verified their own identity at the point they
/// received the UTD event.
pub user_trusts_own_identity: bool,
/// The homeserver of the user that sent the undecryptable event.
pub sender_homeserver: String,
/// Our local user's own homeserver, or `None` if the client is not logged
/// in.
pub own_homeserver: Option<String>,
}
impl From<SdkUnableToDecryptInfo> for UnableToDecryptInfo {
fn from(value: SdkUnableToDecryptInfo) -> Self {
Self {
event_id: value.event_id.to_string(),
time_to_decrypt_ms: value.time_to_decrypt.map(|ttd| ttd.as_millis() as u64),
cause: value.cause,
event_local_age_millis: value.event_local_age_millis,
user_trusts_own_identity: value.user_trusts_own_identity,
sender_homeserver: value.sender_homeserver.to_string(),
own_homeserver: value.own_homeserver.map(String::from),
}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use tokio::task::JoinHandle;
use matrix_sdk_common::executor::JoinHandle;
use tracing::debug;
/// A task handle is a way to keep the handle a task running by itself in
@@ -63,9 +63,27 @@ impl From<FilterTimelineEventType> for TimelineEventType {
#[derive(uniffi::Enum)]
pub enum TimelineFocus {
Live,
Event { event_id: String, num_context_events: u16 },
PinnedEvents { max_events_to_load: u16, max_concurrent_requests: u16 },
Live {
/// Whether to hide in-thread replies from the live timeline.
hide_threaded_events: bool,
},
Event {
/// The initial event to focus on. This is usually the target of a
/// permalink.
event_id: String,
/// The number of context events to load around the focused event.
num_context_events: u16,
/// Whether to hide in-thread replies from the live timeline.
hide_threaded_events: bool,
},
Thread {
/// The thread root event ID to focus on.
root_event_id: String,
},
PinnedEvents {
max_events_to_load: u16,
max_concurrent_requests: u16,
},
}
impl TryFrom<TimelineFocus> for matrix_sdk_ui::timeline::TimelineFocus {
@@ -75,15 +93,29 @@ impl TryFrom<TimelineFocus> for matrix_sdk_ui::timeline::TimelineFocus {
value: TimelineFocus,
) -> Result<matrix_sdk_ui::timeline::TimelineFocus, Self::Error> {
match value {
TimelineFocus::Live => Ok(Self::Live),
TimelineFocus::Event { event_id, num_context_events } => {
TimelineFocus::Live { hide_threaded_events } => Ok(Self::Live { hide_threaded_events }),
TimelineFocus::Event { event_id, num_context_events, hide_threaded_events } => {
let parsed_event_id =
EventId::parse(&event_id).map_err(|err| FocusEventError::InvalidEventId {
event_id: event_id.clone(),
err: err.to_string(),
})?;
Ok(Self::Event { target: parsed_event_id, num_context_events })
Ok(Self::Event {
target: parsed_event_id,
num_context_events,
hide_threaded_events,
})
}
TimelineFocus::Thread { root_event_id } => {
let parsed_root_event_id = EventId::parse(&root_event_id).map_err(|err| {
FocusEventError::InvalidEventId {
event_id: root_event_id.clone(),
err: err.to_string(),
}
})?;
Ok(Self::Thread { root_event_id: parsed_root_event_id })
}
TimelineFocus::PinnedEvents { max_events_to_load, max_concurrent_requests } => {
Ok(Self::PinnedEvents { max_events_to_load, max_concurrent_requests })
@@ -146,4 +178,8 @@ pub struct TimelineConfiguration {
/// As this has a non negligible performance impact, make sure to enable it
/// only when you need it.
pub track_read_receipts: bool,
/// Whether this timeline instance should report UTDs through the client's
/// delegate.
pub report_utds: bool,
}
@@ -96,6 +96,14 @@ impl From<matrix_sdk_ui::timeline::TimelineItemContent> for TimelineItemContent
}
#[derive(Clone, uniffi::Enum)]
// A note about this `allow(clippy::large_enum_variant)`.
// In order to reduce the size of `TimelineItemContent`, we would need to
// put some parts in a `Box`, or an `Arc`. Sadly, it doesn't play well with
// UniFFI. We would need to change the `uniffi::Record` of the subtypes into
// `uniffi::Object`, which is a radical change. It would simplify the memory
// usage, but it would slow down the performance around the FFI border. Thus,
// let's consider this is a false-positive lint in this particular case.
#[allow(clippy::large_enum_variant)]
pub enum TimelineItemContent {
MsgLike {
content: MsgLikeContent,
File diff suppressed because it is too large Load Diff
@@ -15,9 +15,12 @@
use std::{collections::HashMap, sync::Arc};
use matrix_sdk::crypto::types::events::UtdCause;
use ruma::events::{room::MediaSource as RumaMediaSource, EventContent};
use ruma::events::{room::MediaSource as RumaMediaSource, MessageLikeEventContent};
use super::{content::Reaction, reply::InReplyToDetails};
use super::{
content::Reaction,
reply::{EmbeddedEventDetails, InReplyToDetails},
};
use crate::{
error::ClientError,
ruma::{ImageInfo, MediaSource, MediaSourceExt, Mentions, MessageType, PollKind},
@@ -56,10 +59,12 @@ pub enum MsgLikeKind {
pub struct MsgLikeContent {
pub kind: MsgLikeKind,
pub reactions: Vec<Reaction>,
/// Event ID of the thread root, if this is a threaded message.
pub thread_root: Option<String>,
/// The event this message is replying to, if any.
pub in_reply_to: Option<Arc<InReplyToDetails>>,
/// Event ID of the thread root, if this is a message in a thread.
pub thread_root: Option<String>,
/// Details about the thread this message is the root of.
pub thread_summary: Option<Arc<ThreadSummary>>,
}
#[derive(Clone, uniffi::Record)]
@@ -95,6 +100,8 @@ impl TryFrom<matrix_sdk_ui::timeline::MsgLikeContent> for MsgLikeContent {
let thread_root = value.thread_root.map(|id| id.to_string());
let thread_summary = value.thread_summary.map(|t| Arc::new(t.into()));
Ok(match value.kind {
Kind::Message(message) => {
let msg_type = TryInto::<MessageType>::try_into(message.msgtype().clone())
@@ -112,6 +119,7 @@ impl TryFrom<matrix_sdk_ui::timeline::MsgLikeContent> for MsgLikeContent {
reactions,
in_reply_to,
thread_root,
thread_summary,
}
}
Kind::Sticker(sticker) => {
@@ -134,6 +142,7 @@ impl TryFrom<matrix_sdk_ui::timeline::MsgLikeContent> for MsgLikeContent {
reactions,
in_reply_to,
thread_root,
thread_summary,
}
}
Kind::Poll(poll_state) => {
@@ -156,16 +165,22 @@ impl TryFrom<matrix_sdk_ui::timeline::MsgLikeContent> for MsgLikeContent {
reactions,
in_reply_to,
thread_root,
thread_summary,
}
}
Kind::Redacted => {
Self { kind: MsgLikeKind::Redacted, reactions, in_reply_to, thread_root }
}
Kind::Redacted => Self {
kind: MsgLikeKind::Redacted,
reactions,
in_reply_to,
thread_root,
thread_summary,
},
Kind::UnableToDecrypt(msg) => Self {
kind: MsgLikeKind::UnableToDecrypt { msg: EncryptedMessage::new(&msg) },
reactions,
in_reply_to,
thread_root,
thread_summary,
},
})
}
@@ -222,3 +237,29 @@ pub struct PollAnswer {
pub id: String,
pub text: String,
}
#[derive(Clone, uniffi::Object)]
pub struct ThreadSummary {
pub latest_event: EmbeddedEventDetails,
pub num_replies: u32,
}
#[matrix_sdk_ffi_macros::export]
impl ThreadSummary {
pub fn latest_event(&self) -> EmbeddedEventDetails {
self.latest_event.clone()
}
pub fn num_replies(&self) -> u64 {
self.num_replies as u64
}
}
impl From<matrix_sdk_ui::timeline::ThreadSummary> for ThreadSummary {
fn from(value: matrix_sdk_ui::timeline::ThreadSummary) -> Self {
Self {
latest_event: EmbeddedEventDetails::from(value.latest_event),
num_replies: value.num_replies,
}
}
}
+35 -22
View File
@@ -12,18 +12,19 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use matrix_sdk_ui::timeline::TimelineDetails;
use matrix_sdk_ui::timeline::{EmbeddedEvent, TimelineDetails};
use super::{content::TimelineItemContent, ProfileDetails};
use crate::{event::EventOrTransactionId, utils::Timestamp};
#[derive(Clone, uniffi::Object)]
pub struct InReplyToDetails {
event_id: String,
event: RepliedToEventDetails,
event: EmbeddedEventDetails,
}
impl InReplyToDetails {
pub(crate) fn new(event_id: String, event: RepliedToEventDetails) -> Self {
pub(crate) fn new(event_id: String, event: EmbeddedEventDetails) -> Self {
Self { event_id, event }
}
}
@@ -34,35 +35,47 @@ impl InReplyToDetails {
self.event_id.clone()
}
pub fn event(&self) -> RepliedToEventDetails {
pub fn event(&self) -> EmbeddedEventDetails {
self.event.clone()
}
}
impl From<matrix_sdk_ui::timeline::InReplyToDetails> for InReplyToDetails {
fn from(inner: matrix_sdk_ui::timeline::InReplyToDetails) -> Self {
let event_id = inner.event_id.to_string();
let event = match &inner.event {
TimelineDetails::Unavailable => RepliedToEventDetails::Unavailable,
TimelineDetails::Pending => RepliedToEventDetails::Pending,
TimelineDetails::Ready(event) => RepliedToEventDetails::Ready {
content: event.content().clone().into(),
sender: event.sender().to_string(),
sender_profile: event.sender_profile().into(),
},
TimelineDetails::Error(err) => {
RepliedToEventDetails::Error { message: err.to_string() }
}
};
Self { event_id, event }
Self { event_id: inner.event_id.to_string(), event: inner.event.into() }
}
}
#[derive(Clone, uniffi::Enum)]
pub enum RepliedToEventDetails {
#[allow(clippy::large_enum_variant)]
pub enum EmbeddedEventDetails {
Unavailable,
Pending,
Ready { content: TimelineItemContent, sender: String, sender_profile: ProfileDetails },
Error { message: String },
Ready {
content: TimelineItemContent,
sender: String,
sender_profile: ProfileDetails,
timestamp: Timestamp,
event_or_transaction_id: EventOrTransactionId,
},
Error {
message: String,
},
}
impl From<TimelineDetails<Box<EmbeddedEvent>>> for EmbeddedEventDetails {
fn from(event: TimelineDetails<Box<EmbeddedEvent>>) -> Self {
match event {
TimelineDetails::Unavailable => EmbeddedEventDetails::Unavailable,
TimelineDetails::Pending => EmbeddedEventDetails::Pending,
TimelineDetails::Ready(event) => EmbeddedEventDetails::Ready {
content: event.content.into(),
sender: event.sender.to_string(),
sender_profile: event.sender_profile.into(),
timestamp: event.timestamp.into(),
event_or_transaction_id: event.identifier.into(),
},
TimelineDetails::Error(err) => EmbeddedEventDetails::Error { message: err.to_string() },
}
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ use tracing_core::{identify_callsite, metadata::Kind as MetadataKind};
/// Log an event.
///
/// The target should be something like a module path, and can be referenced in
/// the filter string given to `setup_tracing`. `level` and `target` for a
/// the filter string given to `init_platform`. `level` and `target` for a
/// callsite are fixed at the first `log_event` call for that callsite and can
/// not be changed afterwards, i.e. the level and target passed for second and
/// following `log_event`s with the same callsite will be ignored.
+101
View File
@@ -0,0 +1,101 @@
// Copyright 2025 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{fmt::Debug, sync::Arc, time::Duration};
use matrix_sdk::crypto::types::events::UtdCause;
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use matrix_sdk_ui::unable_to_decrypt_hook::{
UnableToDecryptHook, UnableToDecryptInfo as SdkUnableToDecryptInfo,
};
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait UnableToDecryptDelegate: SyncOutsideWasm + SendOutsideWasm {
fn on_utd(&self, info: UnableToDecryptInfo);
}
pub struct UtdHook {
pub delegate: Arc<dyn UnableToDecryptDelegate>,
}
impl std::fmt::Debug for UtdHook {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UtdHook").finish_non_exhaustive()
}
}
impl UnableToDecryptHook for UtdHook {
fn on_utd(&self, info: SdkUnableToDecryptInfo) {
const IGNORE_UTD_PERIOD: Duration = Duration::from_secs(4);
// UTDs that have been decrypted in the `IGNORE_UTD_PERIOD` are just ignored and
// not considered UTDs.
if let Some(duration) = &info.time_to_decrypt {
if *duration < IGNORE_UTD_PERIOD {
return;
}
}
// Report the UTD to the client.
self.delegate.on_utd(info.into());
}
}
#[derive(uniffi::Record)]
pub struct UnableToDecryptInfo {
/// The identifier of the event that couldn't get decrypted.
event_id: String,
/// If the event could be decrypted late (that is, the event was encrypted
/// at first, but could be decrypted later on), then this indicates the
/// time it took to decrypt the event. If it is not set, this is
/// considered a definite UTD.
///
/// If set, this is in milliseconds.
pub time_to_decrypt_ms: Option<u64>,
/// What we know about what caused this UTD. E.g. was this event sent when
/// we were not a member of this room?
pub cause: UtdCause,
/// The difference between the event creation time (`origin_server_ts`) and
/// the time our device was created. If negative, this event was sent
/// *before* our device was created.
pub event_local_age_millis: i64,
/// Whether the user had verified their own identity at the point they
/// received the UTD event.
pub user_trusts_own_identity: bool,
/// The homeserver of the user that sent the undecryptable event.
pub sender_homeserver: String,
/// Our local user's own homeserver, or `None` if the client is not logged
/// in.
pub own_homeserver: Option<String>,
}
impl From<SdkUnableToDecryptInfo> for UnableToDecryptInfo {
fn from(value: SdkUnableToDecryptInfo) -> Self {
Self {
event_id: value.event_id.to_string(),
time_to_decrypt_ms: value.time_to_decrypt.map(|ttd| ttd.as_millis() as u64),
cause: value.cause,
event_local_age_millis: value.event_local_age_millis,
user_trusts_own_identity: value.user_trusts_own_identity,
sender_homeserver: value.sender_homeserver.to_string(),
own_homeserver: value.own_homeserver.map(String::from),
}
}
}
+2 -1
View File
@@ -14,10 +14,11 @@
use std::{mem::ManuallyDrop, ops::Deref};
use async_compat::get_runtime_handle;
use ruma::{MilliSecondsSinceUnixEpoch, UInt};
use tracing::warn;
use crate::runtime::get_runtime_handle;
#[derive(Debug, Clone)]
pub struct Timestamp(u64);
+62 -184
View File
@@ -1,15 +1,12 @@
use std::sync::{Arc, Mutex};
use async_compat::get_runtime_handle;
use language_tags::LanguageTag;
use matrix_sdk::{
async_trait,
widget::{MessageLikeEventFilter, StateEventFilter},
};
use matrix_sdk::widget::{MessageLikeEventFilter, StateEventFilter, ToDeviceEventFilter};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use ruma::events::MessageLikeEventType;
use tracing::error;
use crate::room::Room;
use crate::{room::Room, runtime::get_runtime_handle};
#[derive(uniffi::Record)]
pub struct WidgetDriverAndHandle {
@@ -95,7 +92,7 @@ impl From<matrix_sdk::widget::WidgetSettings> for WidgetSettings {
///
/// # Arguments
/// * `widget_settings` - The widget settings to generate the url for.
/// * `room` - A matrix room which is used to query the logged in username
/// * `room` - A Matrix room which is used to query the logged in username
/// * `props` - Properties from the client that can be used by a widget to adapt
/// to the client. e.g. language, font-scale...
#[matrix_sdk_ffi_macros::export]
@@ -113,168 +110,6 @@ pub async fn generate_webview_url(
.map(|url| url.to_string())?)
}
/// Defines if a call is encrypted and which encryption system should be used.
///
/// This controls the url parameters: `perParticipantE2EE`, `password`.
#[derive(uniffi::Enum, Clone)]
pub enum EncryptionSystem {
/// Equivalent to the element call url parameter: `enableE2EE=false`
Unencrypted,
/// Equivalent to the element call url parameter:
/// `perParticipantE2EE=true`
PerParticipantKeys,
/// Equivalent to the element call url parameter:
/// `password={secret}`
SharedSecret {
/// The secret/password which is used in the url.
secret: String,
},
}
impl From<EncryptionSystem> for matrix_sdk::widget::EncryptionSystem {
fn from(value: EncryptionSystem) -> Self {
match value {
EncryptionSystem::Unencrypted => Self::Unencrypted,
EncryptionSystem::PerParticipantKeys => Self::PerParticipantKeys,
EncryptionSystem::SharedSecret { secret } => Self::SharedSecret { secret },
}
}
}
/// Defines the intent of showing the call.
///
/// This controls whether to show or skip the lobby.
#[derive(uniffi::Enum, Clone)]
pub enum Intent {
/// The user wants to start a call.
StartCall,
/// The user wants to join an existing call.
JoinExisting,
}
impl From<Intent> for matrix_sdk::widget::Intent {
fn from(value: Intent) -> Self {
match value {
Intent::StartCall => Self::StartCall,
Intent::JoinExisting => Self::JoinExisting,
}
}
}
/// Properties to create a new virtual Element Call widget.
#[derive(uniffi::Record, Clone)]
pub struct VirtualElementCallWidgetOptions {
/// The url to the Element Call app including any `/room` path if required.
///
/// E.g. <https://call.element.io>, <https://call.element.dev>, <https://call.element.dev/room>
pub element_call_url: String,
/// The widget id.
pub widget_id: String,
/// The url that is used as the target for the PostMessages sent
/// by the widget (to the client).
///
/// For a web app client this is the client url. In case of using other
/// platforms the client most likely is setup up to listen to
/// postmessages in the same webview the widget is hosted. In this case
/// the `parent_url` is set to the url of the webview with the widget. Be
/// aware that this means that the widget will receive its own postmessage
/// messages. The `matrix-widget-api` (js) ignores those so this works but
/// it might break custom implementations.
///
/// Defaults to `element_call_url` for the non-iframe (dedicated webview)
/// usecase.
pub parent_url: Option<String>,
/// Whether the branding header of Element call should be hidden.
///
/// Default: `true`
pub hide_header: Option<bool>,
/// If set, the lobby will be skipped and the widget will join the
/// call on the `io.element.join` action.
///
/// Default: `false`
pub preload: Option<bool>,
/// The font scale which will be used inside element call.
///
/// Default: `1`
pub font_scale: Option<f64>,
/// Whether element call should prompt the user to open in the browser or
/// the app.
///
/// Default: `false`
pub app_prompt: Option<bool>,
/// Make it not possible to get to the calls list in the webview.
///
/// Default: `true`
pub confine_to_room: Option<bool>,
/// The font to use, to adapt to the system font.
pub font: Option<String>,
/// The encryption system to use.
///
/// Use `EncryptionSystem::Unencrypted` to disable encryption.
pub encryption: EncryptionSystem,
/// The intent of showing the call.
/// If the user wants to start a call or join an existing one.
/// Controls if the lobby is skipped or not.
pub intent: Option<Intent>,
/// Do not show the screenshare button.
pub hide_screensharing: bool,
/// Can be used to pass a PostHog id to element call.
pub posthog_user_id: Option<String>,
/// The host of the posthog api.
/// Supported since Element Call v0.9.0. Only used by the embedded package.
pub posthog_api_host: Option<String>,
/// The key for the posthog api.
/// Supported since Element Call v0.9.0. Only used by the embedded package.
pub posthog_api_key: Option<String>,
/// The url to use for submitting rageshakes.
/// Supported since Element Call v0.9.0. Only used by the embedded package.
pub rageshake_submit_url: Option<String>,
/// Sentry [DSN](https://docs.sentry.io/concepts/key-terms/dsn-explainer/)
/// Supported since Element Call v0.9.0. Only used by the embedded package.
pub sentry_dsn: Option<String>,
/// Sentry [environment](https://docs.sentry.io/concepts/key-terms/key-terms/)
/// Supported since Element Call v0.9.0. Only used by the embedded package.
pub sentry_environment: Option<String>,
}
impl From<VirtualElementCallWidgetOptions> for matrix_sdk::widget::VirtualElementCallWidgetOptions {
fn from(value: VirtualElementCallWidgetOptions) -> Self {
Self {
element_call_url: value.element_call_url,
widget_id: value.widget_id,
parent_url: value.parent_url,
hide_header: value.hide_header,
preload: value.preload,
font_scale: value.font_scale,
app_prompt: value.app_prompt,
confine_to_room: value.confine_to_room,
font: value.font,
posthog_user_id: value.posthog_user_id,
encryption: value.encryption.into(),
intent: value.intent.map(Into::into),
hide_screensharing: value.hide_screensharing,
posthog_api_host: value.posthog_api_host,
posthog_api_key: value.posthog_api_key,
rageshake_submit_url: value.rageshake_submit_url,
sentry_dsn: value.sentry_dsn,
sentry_environment: value.sentry_environment,
}
}
}
/// `WidgetSettings` are usually created from a state event.
/// (currently unimplemented)
///
@@ -290,9 +125,9 @@ impl From<VirtualElementCallWidgetOptions> for matrix_sdk::widget::VirtualElemen
/// call widget.
#[matrix_sdk_ffi_macros::export]
pub fn new_virtual_element_call_widget(
props: VirtualElementCallWidgetOptions,
props: matrix_sdk::widget::VirtualElementCallWidgetOptions,
) -> Result<WidgetSettings, ParseError> {
Ok(matrix_sdk::widget::WidgetSettings::new_virtual_element_call_widget(props.into())
Ok(matrix_sdk::widget::WidgetSettings::new_virtual_element_call_widget(props)
.map(|w| w.into())?)
}
@@ -321,7 +156,9 @@ pub fn get_element_call_required_permissions(
event_type: "org.matrix.rageshake_request".to_owned(),
},
// To read and send encryption keys
WidgetEventFilter::ToDevice { event_type: "io.element.call.encryption_keys".to_owned() },
// TODO change this to the appropriate to-device version once ready
// remove this once all matrixRTC call apps supports to-device encryption.
WidgetEventFilter::MessageLikeWithType {
event_type: "io.element.call.encryption_keys".to_owned(),
},
@@ -344,6 +181,8 @@ pub fn get_element_call_required_permissions(
read: vec![
// To compute the current state of the matrixRTC session.
WidgetEventFilter::StateWithType { event_type: StateEventType::CallMember.to_string() },
// To display the name of the room.
WidgetEventFilter::StateWithType { event_type: StateEventType::RoomName.to_string() },
// To detect leaving/kicked room members during a call.
WidgetEventFilter::StateWithType { event_type: StateEventType::RoomMember.to_string() },
// To decide whether to encrypt the call streams based on the room encryption setting.
@@ -358,6 +197,15 @@ pub fn get_element_call_required_permissions(
.chain(read_send.clone())
.collect(),
send: vec![
// To notify other users that a call has started.
WidgetEventFilter::MessageLikeWithType {
event_type: "org.matrix.msc4075.rtc.notification".to_owned(),
},
// Also for call notifications, except this is the deprecated fallback type which
// Element Call still sends.
WidgetEventFilter::MessageLikeWithType {
event_type: MessageLikeEventType::CallNotify.to_string(),
},
// To send the call participation state event (main MatrixRTC event).
// This is required for legacy state events (using only one event for all devices with
// a membership array). TODO: remove once legacy call member events are
@@ -372,13 +220,24 @@ pub fn get_element_call_required_permissions(
event_type: StateEventType::CallMember.to_string(),
state_key: format!("{own_user_id}_{own_device_id}"),
},
// Same as above for [MSC3779] and [MSC4143](https://github.com/matrix-org/matrix-spec-proposals/pull/4143),
// with application suffix
WidgetEventFilter::StateWithTypeAndStateKey {
event_type: StateEventType::CallMember.to_string(),
state_key: format!("{own_user_id}_{own_device_id}_m.call"),
},
// The same as above but with an underscore.
// To work around the issue that state events starting with `@` have to be matrix id's
// To work around the issue that state events starting with `@` have to be Matrix id's
// but we use mxId+deviceId.
WidgetEventFilter::StateWithTypeAndStateKey {
event_type: StateEventType::CallMember.to_string(),
state_key: format!("_{own_user_id}_{own_device_id}"),
},
// Same as above for [MSC4143], with application suffix
WidgetEventFilter::StateWithTypeAndStateKey {
event_type: StateEventType::CallMember.to_string(),
state_key: format!("_{own_user_id}_{own_device_id}_m.call"),
},
]
.into_iter()
.chain(read_send)
@@ -442,7 +301,7 @@ pub struct WidgetCapabilities {
/// Types of the messages that a widget wants to be able to send.
pub send: Vec<WidgetEventFilter>,
/// If this capability is requested by the widget, it can not operate
/// separately from the matrix client.
/// separately from the Matrix client.
///
/// This means clients should not offer to open the widget in a separate
/// browser/tab/webview that is not connected to the postmessage widget-api.
@@ -488,9 +347,11 @@ pub enum WidgetEventFilter {
StateWithType { event_type: String },
/// Matches state events with the given `type` and `state_key`.
StateWithTypeAndStateKey { event_type: String, state_key: String },
/// Matches to-device events with the given `event_type`.
ToDevice { event_type: String },
}
impl From<WidgetEventFilter> for matrix_sdk::widget::EventFilter {
impl From<WidgetEventFilter> for matrix_sdk::widget::Filter {
fn from(value: WidgetEventFilter) -> Self {
match value {
WidgetEventFilter::MessageLikeWithType { event_type } => {
@@ -505,13 +366,16 @@ impl From<WidgetEventFilter> for matrix_sdk::widget::EventFilter {
WidgetEventFilter::StateWithTypeAndStateKey { event_type, state_key } => {
Self::State(StateEventFilter::WithTypeAndStateKey(event_type.into(), state_key))
}
WidgetEventFilter::ToDevice { event_type } => {
Self::ToDevice(ToDeviceEventFilter { event_type: event_type.into() })
}
}
}
}
impl From<matrix_sdk::widget::EventFilter> for WidgetEventFilter {
fn from(value: matrix_sdk::widget::EventFilter) -> Self {
use matrix_sdk::widget::EventFilter as F;
impl From<matrix_sdk::widget::Filter> for WidgetEventFilter {
fn from(value: matrix_sdk::widget::Filter) -> Self {
use matrix_sdk::widget::Filter as F;
match value {
F::MessageLike(MessageLikeEventFilter::WithType(event_type)) => {
@@ -526,18 +390,20 @@ impl From<matrix_sdk::widget::EventFilter> for WidgetEventFilter {
F::State(StateEventFilter::WithTypeAndStateKey(event_type, state_key)) => {
Self::StateWithTypeAndStateKey { event_type: event_type.to_string(), state_key }
}
F::ToDevice(ToDeviceEventFilter { event_type }) => {
Self::ToDevice { event_type: event_type.to_string() }
}
}
}
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait WidgetCapabilitiesProvider: Send + Sync {
pub trait WidgetCapabilitiesProvider: SendOutsideWasm + SyncOutsideWasm {
fn acquire_capabilities(&self, capabilities: WidgetCapabilities) -> WidgetCapabilities;
}
struct CapabilitiesProviderWrap(Arc<dyn WidgetCapabilitiesProvider>);
#[async_trait]
impl matrix_sdk::widget::CapabilitiesProvider for CapabilitiesProviderWrap {
async fn acquire_capabilities(
&self,
@@ -631,8 +497,7 @@ mod tests {
let cap_assert = |capability: &str| {
assert!(
permission_array.contains(&capability.to_owned()),
"The \"{}\" capability was missing from the element call capability list.",
capability
"The \"{capability}\" capability was missing from the element call capability list."
);
};
@@ -640,14 +505,27 @@ mod tests {
cap_assert("org.matrix.msc4157.update_delayed_event");
cap_assert("org.matrix.msc4157.send.delayed_event");
cap_assert("org.matrix.msc2762.receive.state_event:org.matrix.msc3401.call.member");
cap_assert("org.matrix.msc2762.receive.state_event:m.room.name");
cap_assert("org.matrix.msc2762.receive.state_event:m.room.member");
cap_assert("org.matrix.msc2762.receive.state_event:m.room.encryption");
cap_assert("org.matrix.msc2762.receive.event:org.matrix.rageshake_request");
cap_assert("org.matrix.msc2762.receive.event:io.element.call.encryption_keys");
cap_assert("org.matrix.msc2762.receive.state_event:m.room.create");
cap_assert("org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@my_user:my_domain.org");
cap_assert("org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@my_user:my_domain.org_ABCDEFGHI");
cap_assert("org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#_@my_user:my_domain.org_ABCDEFGHI");
cap_assert(
"org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@my_user:my_domain.org",
);
cap_assert(
"org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@my_user:my_domain.org_ABCDEFGHI",
);
cap_assert(
"org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#@my_user:my_domain.org_ABCDEFGHI_m.call",
);
cap_assert(
"org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#_@my_user:my_domain.org_ABCDEFGHI",
);
cap_assert(
"org.matrix.msc2762.send.state_event:org.matrix.msc3401.call.member#_@my_user:my_domain.org_ABCDEFGHI_m.call",
);
cap_assert("org.matrix.msc2762.send.event:org.matrix.rageshake_request");
cap_assert("org.matrix.msc2762.send.event:io.element.call.encryption_keys");
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
{
"rust-analyzer.checkOnSave.command": "clippy",
"rust-analyzer.checkOnSave.command": "check",
"rust-analyzer.rustfmt.extraArgs": ["+nightly"]
}
+106 -2
View File
@@ -6,6 +6,102 @@ All notable changes to this project will be documented in this file.
## [Unreleased] - ReleaseDate
## [0.14.0] - 2025-09-04
### Features
- Add `SyncResponse::RoomUpdates::is_empty` to check if there were any room updates.
([#5593](https://github.com/matrix-org/matrix-rust-sdk/pull/5593))
- Add `EncryptionState::StateEncrypted` to represent rooms supporting encrypted
state events. Feature-gated behind `experimental-encrypted-state-events`.
([#5523](https://github.com/matrix-org/matrix-rust-sdk/pull/5523))
- [**breaking**] The `state` field of `JoinedRoomUpdate` and `LeftRoomUpdate`
now uses the `State` enum, depending on whether the state changes were
received in the `state` field or the `state_after` field.
([#5488](https://github.com/matrix-org/matrix-rust-sdk/pull/5488))
- [**breaking**] `RoomCreateWithCreatorEventContent` has a new field
`additional_creators` that allows to specify additional room creators beside
the user sending the `m.room.create` event, introduced with room version 12.
([#5436](https://github.com/matrix-org/matrix-rust-sdk/pull/5436))
- [**breaking**] The `RoomInfo` method now remembers the inviter at the time
when the `BaseClient::room_joined()` method was called. The caller is
responsible to remember the inviter before a server request to join the room
is made. The `RoomInfo::invite_accepted_at` method was removed, the
`RoomInfo::invite_details` method returns both the timestamp and the
inviter.
([#5390](https://github.com/matrix-org/matrix-rust-sdk/pull/5390))
### Refactor
- [**breaking**] The `Stripped` variants of `RawAnySyncOrStrippedTimelineEvent`,
`RawAnySyncOrStrippedState` and `AnySyncOrStrippedState` use `StrippedState`
instead of `AnyStrippedStateEvent`.
([#5473](https://github.com/matrix-org/matrix-rust-sdk/pull/5473))
- [**breaking**] The `stripped_state` field of `StateChanges` uses
`StrippedState` instead of `AnyStrippedStateEvent`.
([#5473](https://github.com/matrix-org/matrix-rust-sdk/pull/5473))
- [**breaking**] `RelationalLinkedChunk::items` now takes a `RoomId` instead of an
`&OwnedLinkedChunkId` parameter.
([#5445](https://github.com/matrix-org/matrix-rust-sdk/pull/5445))
- [**breaking**] Add an `IsPrefix = False` bound to the
`get_state_event_static()`, `get_state_event_static_for_key()` and
`get_state_events_static()`, `get_account_data_event_static()` and
`get_room_account_data_event_static` methods of `StateStoreExt`. These methods
only worked for events where the full event type is statically-known, and this
is now enforced at compile-time. The matching non-`static` methods of
`StateStore` can be used instead for event types with a variable suffix.
([#5444](https://github.com/matrix-org/matrix-rust-sdk/pull/5444))
- [**breaking**] `SyncOrStrippedState<RoomPowerLevelsEventContent>::power_levels()`
takes `AuthorizationRules` and a list of creators, because creators can have
infinite power levels, as introduced in room version 12.
([#5436](https://github.com/matrix-org/matrix-rust-sdk/pull/5436))
- [**breaking**] `RoomMember::power_level()` and
`RoomMember::normalized_power_level()` now use `UserPowerLevel` to represent
power levels instead of `i64` to differentiate the infinite power level of
creators, as introduced in room version 12.
([#5436](https://github.com/matrix-org/matrix-rust-sdk/pull/5436))
- [**breaking**] The `creator()` methods of `Room` and `RoomInfo` have been
renamed to `creators()` and can now return a list of user IDs, to reflect that
a room can have several creators, as introduced in room version 12.
([#5436](https://github.com/matrix-org/matrix-rust-sdk/pull/5436))
- [**breaking**] `RoomInfo::room_version_or_default()` was replaced with
`room_version_rules_or_default()`. The room version should only be used for
display purposes. The rules contain flags for all the differences in behavior
between all known room versions.
([#5337](https://github.com/matrix-org/matrix-rust-sdk/pull/5337))
- [**breaking**] `MinimalStateEvent::redact()` takes `RedactionRules` instead of
a `RoomVersionId`.
([#5337](https://github.com/matrix-org/matrix-rust-sdk/pull/5337))
- [**breaking**] The `event_id` field of `PredecessorRoom` was removed, due to
its removal in the Matrix specification with MSC4291.
([#5419](https://github.com/matrix-org/matrix-rust-sdk/pull/5419))
## [0.13.0] - 2025-07-10
### Features
- The `RoomInfo` now remembers when an invite was explicitly accepted when the
`BaseClient::room_joined()` method was called. A new getter for this
timestamp exists, the `RoomInfo::invite_accepted_at()` method returns this
timestamp.
([#5333](https://github.com/matrix-org/matrix-rust-sdk/pull/5333))
- [**breaking**] The `BaseClient::new()` method now takes an additional `ThreadingSupport`
parameter controlling whether the client is supposed to do extra processing for threads. Right
now, it controls whether to exclude in-thread events from the room unread counts, but it may be
expanded in the future to support more threading-related features.
([#5325](https://github.com/matrix-org/matrix-rust-sdk/pull/5325))
### Refactor
- The cached `ServerCapabilities` has been renamed to `ServerInfo` and
additionally contains the well-known response alongside the existing server versions.
Despite the old name, it does not contain the server capabilities.
([#5167](https://github.com/matrix-org/matrix-rust-sdk/pull/5167))
- `Room::join_rule` and `Room::is_public` now return an `Option` to reflect that the join rule
state event might be missing, in which case they will return `None`.
([#5278](https://github.com/matrix-org/matrix-rust-sdk/pull/5278))
## [0.12.0] - 2025-06-10
No notable changes in this release.
## [0.11.0] - 2025-04-11
### Features
@@ -22,8 +118,8 @@ All notable changes to this project will be documented in this file.
- `EventCacheStoreMedia` has a new method `last_media_cleanup_time_inner`
- There are new `'static` bounds in `MediaService` for the media cache stores
- `event_cache::store::MemoryStore` implements `Clone`.
- `BaseClient` now has a `handle_verification_events` field which is `true` by
default and can be negated so the `NotificationClient` won't handle received
- `BaseClient` now has a `handle_verification_events` field which is `true` by
default and can be negated so the `NotificationClient` won't handle received
verification events too, causing errors in the `VerificationMachine`.
- [**breaking**] `Room::is_encryption_state_synced` has been removed
([#4777](https://github.com/matrix-org/matrix-rust-sdk/pull/4777))
@@ -40,6 +136,14 @@ All notable changes to this project will be documented in this file.
- [**breaking**] `BaseClient::set_session_metadata` is renamed
`activate`, and `BaseClient::logged_in` is renamed `is_activated`
([#4850](https://github.com/matrix-org/matrix-rust-sdk/pull/4850))
- [**breaking] `DependentQueuedRequestKind::UploadFileWithThumbnail`
was renamed to `DependentQueuedRequestKind::UploadFileOrThumbnail`.
Under the `unstable-msc4274` feature, `DependentQueuedRequestKind::UploadFileOrThumbnail`
and `SentMediaInfo` were generalized to allow chaining multiple dependent
file / thumbnail uploads.
([#4897](https://github.com/matrix-org/matrix-rust-sdk/pull/4897))
- [**breaking**] `RoomInfo::prev_state` has been removed due to being useless.
([#5054](https://github.com/matrix-org/matrix-rust-sdk/pull/5054))
## [0.10.0] - 2025-02-04
+57 -32
View File
@@ -1,26 +1,45 @@
[package]
authors = ["Damir Jelić <poljar@termina.org.uk>"]
description = "The base component to build a Matrix client library."
edition = "2021"
edition = "2024"
homepage = "https://github.com/matrix-org/matrix-rust-sdk"
keywords = ["matrix", "chat", "messaging", "ruma", "nio"]
license = "Apache-2.0"
name = "matrix-sdk-base"
readme = "README.md"
repository = "https://github.com/matrix-org/matrix-rust-sdk"
rust-version = { workspace = true }
version = "0.11.0"
rust-version.workspace = true
version = "0.14.0"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
rustdoc-args = ["--cfg", "docsrs", "--generate-link-to-definition"]
[features]
default = []
e2e-encryption = ["dep:matrix-sdk-crypto"]
js = ["matrix-sdk-common/js", "matrix-sdk-crypto?/js", "ruma/js", "matrix-sdk-store-encryption/js"]
js = [
"matrix-sdk-common/js",
"matrix-sdk-crypto?/js",
"ruma/js",
"matrix-sdk-store-encryption/js",
]
qrcode = ["matrix-sdk-crypto?/qrcode"]
automatic-room-key-forwarding = ["matrix-sdk-crypto?/automatic-room-key-forwarding"]
automatic-room-key-forwarding = [
"matrix-sdk-crypto?/automatic-room-key-forwarding",
]
experimental-send-custom-to-device = [
"matrix-sdk-crypto?/experimental-send-custom-to-device",
]
# Enable experimental support for encrypting state events; see
# https://github.com/matrix-org/matrix-rust-sdk/issues/5397.
experimental-encrypted-state-events = [
"e2e-encryption",
"ruma/unstable-msc3414",
"matrix-sdk-crypto?/experimental-encrypted-state-events"
]
uniffi = ["dep:uniffi", "matrix-sdk-crypto?/uniffi", "matrix-sdk-common/uniffi"]
# Private feature, see
@@ -43,24 +62,27 @@ testing = [
"matrix-sdk-crypto?/testing",
]
# Add support for inline media galleries via msgtypes
unstable-msc4274 = []
[dependencies]
as_variant = { workspace = true }
as_variant.workspace = true
assert_matches = { workspace = true, optional = true }
assert_matches2 = { workspace = true, optional = true }
async-trait = { workspace = true }
bitflags = { version = "2.8.0", features = ["serde"] }
decancer = "3.2.8"
async-trait.workspace = true
bitflags = { workspace = true, features = ["serde"] }
decancer = "3.3.3"
eyeball = { workspace = true, features = ["async-lock"] }
eyeball-im = { workspace = true }
futures-util = { workspace = true }
growable-bloom-filter = { workspace = true }
eyeball-im.workspace = true
futures-util.workspace = true
growable-bloom-filter.workspace = true
http = { workspace = true, optional = true }
matrix-sdk-common = { workspace = true }
matrix-sdk-common.workspace = true
matrix-sdk-crypto = { workspace = true, optional = true }
matrix-sdk-store-encryption = { workspace = true }
matrix-sdk-store-encryption.workspace = true
matrix-sdk-test = { workspace = true, optional = true }
once_cell = { workspace = true }
regex = "1.11.1"
once_cell.workspace = true
regex = "1.11.2"
ruma = { workspace = true, features = [
"canonical-json",
"unstable-msc2867",
@@ -68,29 +90,32 @@ ruma = { workspace = true, features = [
"unstable-msc4186",
"rand",
] }
unicode-normalization = { workspace = true }
serde = { workspace = true, features = ["rc"] }
serde_json = { workspace = true }
tokio = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
serde_json.workspace = true
thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
unicode-normalization.workspace = true
uniffi = { workspace = true, optional = true }
[dev-dependencies]
assert_matches = { workspace = true }
assert_matches2 = { workspace = true }
anyhow.workspace = true
assert_matches.workspace = true
assert_matches2.workspace = true
assign = "1.1.1"
futures-executor = { workspace = true }
http = { workspace = true }
matrix-sdk-test = { workspace = true }
stream_assert = { workspace = true }
similar-asserts = { workspace = true }
futures-executor.workspace = true
http.workspace = true
matrix-sdk-test.workspace = true
matrix-sdk-test-utils.workspace = true
similar-asserts.workspace = true
stream_assert.workspace = true
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = { workspace = true }
[target.'cfg(target_family = "wasm")'.dev-dependencies]
wasm-bindgen-test.workspace = true
gloo-timers = { workspace = true, features = ["futures"] }
[lints]
workspace = true
File diff suppressed because it is too large Load Diff
+14
View File
@@ -17,6 +17,7 @@
use std::fmt;
pub use matrix_sdk_common::debug::*;
use matrix_sdk_common::deserialized_responses::ProcessedToDeviceEvent;
use ruma::{
api::client::sync::sync_events::v3::{InvitedRoom, KnockedRoom},
serde::Raw,
@@ -35,6 +36,19 @@ impl<T> fmt::Debug for DebugListOfRawEventsNoId<'_, T> {
}
}
/// A wrapper around a slice of `ProcessedToDeviceEvent` events that implements
/// `Debug` in a way that only prints the event type of each item.
pub struct DebugListOfProcessedToDeviceEvents<'a>(pub &'a [ProcessedToDeviceEvent]);
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for DebugListOfProcessedToDeviceEvents<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut list = f.debug_list();
list.entries(self.0.iter().map(|e| DebugRawEventNoId(e.as_raw())));
list.finish()
}
}
/// A wrapper around an invited room as found in `/sync` responses that
/// implements `Debug` in a way that only prints the event ID and event type for
/// the raw events contained in `invite_state`.
@@ -20,17 +20,18 @@ pub use matrix_sdk_common::deserialized_responses::*;
use once_cell::sync::Lazy;
use regex::Regex;
use ruma::{
EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, UInt, UserId,
events::{
AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent, EventContentFromType,
PossiblyRedactedStateEventContent, RedactContent, RedactedStateEventContent,
StateEventContent, StaticStateEventContent, StrippedStateEvent, SyncStateEvent,
room::{
member::{MembershipState, RoomMemberEvent, RoomMemberEventContent},
power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent},
},
AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent, EventContentFromType,
PossiblyRedactedStateEventContent, RedactContent, RedactedStateEventContent,
StateEventContent, StaticStateEventContent, StrippedStateEvent, SyncStateEvent,
},
room_version_rules::AuthorizationRules,
serde::Raw,
EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, UInt, UserId,
};
use serde::Serialize;
use unicode_normalization::UnicodeNormalization;
@@ -263,6 +264,18 @@ pub enum RawAnySyncOrStrippedTimelineEvent {
Stripped(Raw<AnyStrippedStateEvent>),
}
impl From<Raw<AnySyncTimelineEvent>> for RawAnySyncOrStrippedTimelineEvent {
fn from(event: Raw<AnySyncTimelineEvent>) -> Self {
Self::Sync(event)
}
}
impl From<Raw<AnyStrippedStateEvent>> for RawAnySyncOrStrippedTimelineEvent {
fn from(event: Raw<AnyStrippedStateEvent>) -> Self {
Self::Stripped(event)
}
}
/// Wrapper around both versions of any raw state event.
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
@@ -292,8 +305,8 @@ impl RawAnySyncOrStrippedState {
C::Redacted: RedactedStateEventContent,
{
match self {
Self::Sync(raw) => RawSyncOrStrippedState::Sync(raw.cast()),
Self::Stripped(raw) => RawSyncOrStrippedState::Stripped(raw.cast()),
Self::Sync(raw) => RawSyncOrStrippedState::Sync(raw.cast_unchecked()),
Self::Stripped(raw) => RawSyncOrStrippedState::Stripped(raw.cast_unchecked()),
}
}
}
@@ -505,10 +518,14 @@ impl MemberEvent {
impl SyncOrStrippedState<RoomPowerLevelsEventContent> {
/// The power levels of the event.
pub fn power_levels(&self) -> RoomPowerLevels {
pub fn power_levels(
&self,
rules: &AuthorizationRules,
creators: Vec<OwnedUserId>,
) -> RoomPowerLevels {
match self {
Self::Sync(e) => e.power_levels(),
Self::Stripped(e) => e.power_levels(),
Self::Sync(e) => e.power_levels(rules, creators),
Self::Stripped(e) => e.power_levels(rules, creators),
}
}
}
@@ -14,31 +14,37 @@
//! Trait and macro of integration tests for `EventCacheStore` implementations.
use std::{collections::BTreeMap, sync::Arc};
use assert_matches::assert_matches;
use async_trait::async_trait;
use assert_matches2::assert_let;
use matrix_sdk_common::{
deserialized_responses::{
AlgorithmInfo, DecryptedRoomEvent, EncryptionInfo, TimelineEvent, TimelineEventKind,
VerificationState,
},
linked_chunk::{lazy_loader, ChunkContent, ChunkIdentifier as CId, Position, Update},
linked_chunk::{
ChunkContent, ChunkIdentifier as CId, LinkedChunkId, Position, Update, lazy_loader,
},
};
use matrix_sdk_test::{event_factory::EventFactory, ALICE, DEFAULT_TEST_ROOM_ID};
use matrix_sdk_test::{ALICE, DEFAULT_TEST_ROOM_ID, event_factory::EventFactory};
use ruma::{
EventId, RoomId,
api::client::media::get_content_thumbnail::v3::Method,
event_id,
events::{
AnyMessageLikeEvent, AnyTimelineEvent,
relation::RelationType,
room::{message::RoomMessageEventContentWithoutRelation, MediaSource},
room::{MediaSource, message::RoomMessageEventContentWithoutRelation},
},
mxc_uri,
push::Action,
room_id, uint, EventId, RoomId,
room_id, uint,
};
use super::{media::IgnoreMediaRetentionPolicy, DynEventCacheStore};
use super::{DynEventCacheStore, media::IgnoreMediaRetentionPolicy};
use crate::{
event_cache::{store::DEFAULT_CHUNK_CAPACITY, Gap},
event_cache::{Gap, store::DEFAULT_CHUNK_CAPACITY},
media::{MediaFormat, MediaRequestParameters, MediaThumbnailSettings},
};
@@ -56,31 +62,27 @@ pub fn make_test_event_with_event_id(
content: &str,
event_id: Option<&EventId>,
) -> TimelineEvent {
let encryption_info = EncryptionInfo {
let encryption_info = Arc::new(EncryptionInfo {
sender: (*ALICE).into(),
sender_device: None,
algorithm_info: AlgorithmInfo::MegolmV1AesSha2 {
curve25519_key: "1337".to_owned(),
sender_claimed_keys: Default::default(),
session_id: Some("mysessionid9".to_owned()),
},
verification_state: VerificationState::Verified,
session_id: Some("mysessionid9".to_owned()),
};
});
let mut builder = EventFactory::new().text_msg(content).room(room_id).sender(*ALICE);
if let Some(event_id) = event_id {
builder = builder.event_id(event_id);
}
let event = builder.into_raw_timeline().cast();
let event = builder.into_raw();
TimelineEvent {
kind: TimelineEventKind::Decrypted(DecryptedRoomEvent {
event,
encryption_info,
unsigned_encryption_info: None,
}),
push_actions: Some(vec![Action::Notify]),
}
TimelineEvent::from_decrypted(
DecryptedRoomEvent { event, encryption_info, unsigned_encryption_info: None },
Some(vec![Action::Notify]),
)
}
/// Check that an event created with [`make_test_event`] contains the expected
@@ -90,7 +92,7 @@ pub fn make_test_event_with_event_id(
#[track_caller]
pub fn check_test_event(event: &TimelineEvent, text: &str) {
// Check push actions.
let actions = event.push_actions.as_ref().unwrap();
let actions = event.push_actions().unwrap();
assert_eq!(actions.len(), 1);
assert_matches!(&actions[0], Action::Notify);
@@ -104,7 +106,7 @@ pub fn check_test_event(event: &TimelineEvent, text: &str) {
// Check event.
let deserialized = d.event.deserialize().unwrap();
assert_matches!(deserialized, ruma::events::AnyMessageLikeEvent::RoomMessage(msg) => {
assert_matches!(deserialized, AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => {
assert_eq!(msg.as_original().unwrap().content.body(), text);
});
});
@@ -114,8 +116,7 @@ pub fn check_test_event(event: &TimelineEvent, text: &str) {
///
/// This trait is not meant to be used directly, but will be used with the
/// `event_cache_store_integration_tests!` macro.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[allow(async_fn_in_trait)]
pub trait EventCacheStoreIntegrationTests {
/// Test media content storage.
async fn test_media_content(&self);
@@ -135,8 +136,11 @@ pub trait EventCacheStoreIntegrationTests {
/// anything.
async fn test_rebuild_empty_linked_chunk(&self);
/// Test that loading a linked chunk's metadata works as intended.
async fn test_load_all_chunks_metadata(&self);
/// Test that clear all the rooms' linked chunks works.
async fn test_clear_all_rooms_chunks(&self);
async fn test_clear_all_linked_chunks(&self);
/// Test that removing a room from storage empties all associated data.
async fn test_remove_room(&self);
@@ -152,10 +156,12 @@ pub trait EventCacheStoreIntegrationTests {
/// Test that saving an event works as expected.
async fn test_save_event(&self);
/// Test multiple things related to distinguishing a thread linked chunk
/// from a room linked chunk.
async fn test_thread_vs_room_linked_chunk(&self);
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EventCacheStoreIntegrationTests for DynEventCacheStore {
async fn test_media_content(&self) {
let uri = mxc_uri!("mxc://localhost/media");
@@ -343,9 +349,10 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
async fn test_handle_updates_and_rebuild_linked_chunk(&self) {
let room_id = room_id!("!r0:matrix.org");
let linked_chunk_id = LinkedChunkId::Room(room_id);
self.handle_linked_chunk_updates(
room_id,
linked_chunk_id,
vec![
// new chunk
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
@@ -377,10 +384,11 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
.unwrap();
// The linked chunk is correctly reloaded.
let lc =
lazy_loader::from_all_chunks::<3, _, _>(self.load_all_chunks(room_id).await.unwrap())
.unwrap()
.unwrap();
let lc = lazy_loader::from_all_chunks::<3, _, _>(
self.load_all_chunks(linked_chunk_id).await.unwrap(),
)
.unwrap()
.unwrap();
let mut chunks = lc.chunks();
@@ -419,21 +427,88 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
assert!(chunks.next().is_none());
}
async fn test_load_all_chunks_metadata(&self) {
let room_id = room_id!("!r0:matrix.org");
let linked_chunk_id = LinkedChunkId::Room(room_id);
self.handle_linked_chunk_updates(
linked_chunk_id,
vec![
// new chunk
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
// new items on 0
Update::PushItems {
at: Position::new(CId::new(0), 0),
items: vec![
make_test_event(room_id, "hello"),
make_test_event(room_id, "world"),
],
},
// a gap chunk
Update::NewGapChunk {
previous: Some(CId::new(0)),
new: CId::new(1),
next: None,
gap: Gap { prev_token: "parmesan".to_owned() },
},
// another items chunk
Update::NewItemsChunk { previous: Some(CId::new(1)), new: CId::new(2), next: None },
// new items on 2
Update::PushItems {
at: Position::new(CId::new(2), 0),
items: vec![make_test_event(room_id, "sup")],
},
// and an empty items chunk to finish
Update::NewItemsChunk { previous: Some(CId::new(2)), new: CId::new(3), next: None },
],
)
.await
.unwrap();
let metas = self.load_all_chunks_metadata(linked_chunk_id).await.unwrap();
assert_eq!(metas.len(), 4);
// The first chunk has two items.
assert_eq!(metas[0].identifier, CId::new(0));
assert_eq!(metas[0].previous, None);
assert_eq!(metas[0].next, Some(CId::new(1)));
assert_eq!(metas[0].num_items, 2);
// The second chunk is a gap, so it has 0 items.
assert_eq!(metas[1].identifier, CId::new(1));
assert_eq!(metas[1].previous, Some(CId::new(0)));
assert_eq!(metas[1].next, Some(CId::new(2)));
assert_eq!(metas[1].num_items, 0);
// The third event chunk has one item.
assert_eq!(metas[2].identifier, CId::new(2));
assert_eq!(metas[2].previous, Some(CId::new(1)));
assert_eq!(metas[2].next, Some(CId::new(3)));
assert_eq!(metas[2].num_items, 1);
// The final event chunk is empty.
assert_eq!(metas[3].identifier, CId::new(3));
assert_eq!(metas[3].previous, Some(CId::new(2)));
assert_eq!(metas[3].next, None);
assert_eq!(metas[3].num_items, 0);
}
async fn test_linked_chunk_incremental_loading(&self) {
let room_id = room_id!("!r0:matrix.org");
let linked_chunk_id = LinkedChunkId::Room(room_id);
let event = |msg: &str| make_test_event(room_id, msg);
// Load the last chunk, but none exists yet.
{
let (last_chunk, chunk_identifier_generator) =
self.load_last_chunk(room_id).await.unwrap();
self.load_last_chunk(linked_chunk_id).await.unwrap();
assert!(last_chunk.is_none());
assert_eq!(chunk_identifier_generator.current(), 0);
}
self.handle_linked_chunk_updates(
room_id,
linked_chunk_id,
vec![
// new chunk for items
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
@@ -464,7 +539,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Load the last chunk.
let mut linked_chunk = {
let (last_chunk, chunk_identifier_generator) =
self.load_last_chunk(room_id).await.unwrap();
self.load_last_chunk(linked_chunk_id).await.unwrap();
assert_eq!(chunk_identifier_generator.current(), 2);
@@ -499,9 +574,9 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
{
let first_chunk = linked_chunk.chunks().next().unwrap().identifier();
let previous_chunk =
self.load_previous_chunk(room_id, first_chunk).await.unwrap().unwrap();
self.load_previous_chunk(linked_chunk_id, first_chunk).await.unwrap().unwrap();
let _ = lazy_loader::insert_new_first_chunk(&mut linked_chunk, previous_chunk).unwrap();
lazy_loader::insert_new_first_chunk(&mut linked_chunk, previous_chunk).unwrap();
let mut rchunks = linked_chunk.rchunks();
@@ -536,9 +611,9 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
{
let first_chunk = linked_chunk.chunks().next().unwrap().identifier();
let previous_chunk =
self.load_previous_chunk(room_id, first_chunk).await.unwrap().unwrap();
self.load_previous_chunk(linked_chunk_id, first_chunk).await.unwrap().unwrap();
let _ = lazy_loader::insert_new_first_chunk(&mut linked_chunk, previous_chunk).unwrap();
lazy_loader::insert_new_first_chunk(&mut linked_chunk, previous_chunk).unwrap();
let mut rchunks = linked_chunk.rchunks();
@@ -585,7 +660,8 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Load the previous chunk: there is none.
{
let first_chunk = linked_chunk.chunks().next().unwrap().identifier();
let previous_chunk = self.load_previous_chunk(room_id, first_chunk).await.unwrap();
let previous_chunk =
self.load_previous_chunk(linked_chunk_id, first_chunk).await.unwrap();
assert!(previous_chunk.is_none());
}
@@ -637,19 +713,21 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
async fn test_rebuild_empty_linked_chunk(&self) {
// When I rebuild a linked chunk from an empty store, it's empty.
let linked_chunk = lazy_loader::from_all_chunks::<3, _, _>(
self.load_all_chunks(&DEFAULT_TEST_ROOM_ID).await.unwrap(),
self.load_all_chunks(LinkedChunkId::Room(&DEFAULT_TEST_ROOM_ID)).await.unwrap(),
)
.unwrap();
assert!(linked_chunk.is_none());
}
async fn test_clear_all_rooms_chunks(&self) {
async fn test_clear_all_linked_chunks(&self) {
let r0 = room_id!("!r0:matrix.org");
let linked_chunk_id0 = LinkedChunkId::Room(r0);
let r1 = room_id!("!r1:matrix.org");
let linked_chunk_id1 = LinkedChunkId::Room(r1);
// Add updates for the first room.
self.handle_linked_chunk_updates(
r0,
linked_chunk_id0,
vec![
// new chunk
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
@@ -665,7 +743,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Add updates for the second room.
self.handle_linked_chunk_updates(
r1,
linked_chunk_id1,
vec![
// Empty items chunk.
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
@@ -689,32 +767,50 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
.unwrap();
// Sanity check: both linked chunks can be reloaded.
assert!(lazy_loader::from_all_chunks::<3, _, _>(self.load_all_chunks(r0).await.unwrap())
assert!(
lazy_loader::from_all_chunks::<3, _, _>(
self.load_all_chunks(linked_chunk_id0).await.unwrap()
)
.unwrap()
.is_some());
assert!(lazy_loader::from_all_chunks::<3, _, _>(self.load_all_chunks(r1).await.unwrap())
.is_some()
);
assert!(
lazy_loader::from_all_chunks::<3, _, _>(
self.load_all_chunks(linked_chunk_id1).await.unwrap()
)
.unwrap()
.is_some());
.is_some()
);
// Clear the chunks.
self.clear_all_rooms_chunks().await.unwrap();
self.clear_all_linked_chunks().await.unwrap();
// Both rooms now have no linked chunk.
assert!(lazy_loader::from_all_chunks::<3, _, _>(self.load_all_chunks(r0).await.unwrap())
assert!(
lazy_loader::from_all_chunks::<3, _, _>(
self.load_all_chunks(linked_chunk_id0).await.unwrap()
)
.unwrap()
.is_none());
assert!(lazy_loader::from_all_chunks::<3, _, _>(self.load_all_chunks(r1).await.unwrap())
.is_none()
);
assert!(
lazy_loader::from_all_chunks::<3, _, _>(
self.load_all_chunks(linked_chunk_id1).await.unwrap()
)
.unwrap()
.is_none());
.is_none()
);
}
async fn test_remove_room(&self) {
let r0 = room_id!("!r0:matrix.org");
let linked_chunk_id0 = LinkedChunkId::Room(r0);
let r1 = room_id!("!r1:matrix.org");
let linked_chunk_id1 = LinkedChunkId::Room(r1);
// Add updates to the first room.
self.handle_linked_chunk_updates(
r0,
linked_chunk_id0,
vec![
// new chunk
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
@@ -730,7 +826,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Add updates to the second room.
self.handle_linked_chunk_updates(
r1,
linked_chunk_id1,
vec![
// new chunk
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
@@ -748,17 +844,19 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
self.remove_room(r0).await.unwrap();
// Check that r0 doesn't have a linked chunk anymore.
let r0_linked_chunk = self.load_all_chunks(r0).await.unwrap();
let r0_linked_chunk = self.load_all_chunks(linked_chunk_id0).await.unwrap();
assert!(r0_linked_chunk.is_empty());
// Check that r1 is unaffected.
let r1_linked_chunk = self.load_all_chunks(r1).await.unwrap();
let r1_linked_chunk = self.load_all_chunks(linked_chunk_id1).await.unwrap();
assert!(!r1_linked_chunk.is_empty());
}
async fn test_filter_duplicated_events(&self) {
let room_id = room_id!("!r0:matrix.org");
let linked_chunk_id = LinkedChunkId::Room(room_id);
let another_room_id = room_id!("!r1:matrix.org");
let another_linked_chunk_id = LinkedChunkId::Room(another_room_id);
let event = |msg: &str| make_test_event(room_id, msg);
let event_comte = event("comté");
@@ -770,7 +868,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
let event_mont_dor = event("mont d'or");
self.handle_linked_chunk_updates(
room_id,
linked_chunk_id,
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems {
@@ -796,7 +894,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Add other events in another room, to ensure filtering take the `room_id` into
// account.
self.handle_linked_chunk_updates(
another_room_id,
another_linked_chunk_id,
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems {
@@ -808,9 +906,9 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
.await
.unwrap();
let duplicated_events = self
.filter_duplicated_events(
room_id,
let duplicated_events = BTreeMap::from_iter(
self.filter_duplicated_events(
linked_chunk_id,
vec![
event_comte.event_id().unwrap().to_owned(),
event_raclette.event_id().unwrap().to_owned(),
@@ -821,26 +919,29 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
],
)
.await
.unwrap();
.unwrap(),
);
assert_eq!(duplicated_events.len(), 3);
assert_eq!(
duplicated_events[0],
(event_comte.event_id().unwrap(), Position::new(CId::new(0), 0))
*duplicated_events.get(&event_comte.event_id().unwrap()).unwrap(),
Position::new(CId::new(0), 0)
);
assert_eq!(
duplicated_events[1],
(event_morbier.event_id().unwrap(), Position::new(CId::new(2), 0))
*duplicated_events.get(&event_morbier.event_id().unwrap()).unwrap(),
Position::new(CId::new(2), 0)
);
assert_eq!(
duplicated_events[2],
(event_mont_dor.event_id().unwrap(), Position::new(CId::new(2), 1))
*duplicated_events.get(&event_mont_dor.event_id().unwrap()).unwrap(),
Position::new(CId::new(2), 1)
);
}
async fn test_find_event(&self) {
let room_id = room_id!("!r0:matrix.org");
let another_room_id = room_id!("!r1:matrix.org");
let another_linked_chunk_id = LinkedChunkId::Room(another_room_id);
let event = |msg: &str| make_test_event(room_id, msg);
let event_comte = event("comté");
@@ -848,7 +949,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Add one event in one room.
self.handle_linked_chunk_updates(
room_id,
LinkedChunkId::Room(room_id),
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems {
@@ -862,7 +963,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Add another event in another room.
self.handle_linked_chunk_updates(
another_room_id,
another_linked_chunk_id,
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems {
@@ -884,19 +985,21 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
assert_eq!(event.event_id(), event_comte.event_id());
// Now let's try to find an event that exists, but not in the expected room.
assert!(self
.find_event(room_id, event_gruyere.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none());
assert!(
self.find_event(room_id, event_gruyere.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none()
);
// Clearing the rooms also clears the event's storage.
self.clear_all_rooms_chunks().await.expect("failed to clear all rooms chunks");
assert!(self
.find_event(room_id, event_comte.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none());
self.clear_all_linked_chunks().await.expect("failed to clear all rooms chunks");
assert!(
self.find_event(room_id, event_comte.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none()
);
}
async fn test_find_event_relations(&self) {
@@ -934,7 +1037,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Save All The Things!
self.save_event(room_id, e1).await.unwrap();
self.save_event(room_id, edit_e1).await.unwrap();
self.save_event(room_id, reaction_e1).await.unwrap();
self.save_event(room_id, reaction_e1.clone()).await.unwrap();
self.save_event(room_id, e2).await.unwrap();
self.save_event(another_room_id, e3).await.unwrap();
self.save_event(another_room_id, reaction_e3).await.unwrap();
@@ -942,8 +1045,17 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
// Finding relations without a filter returns all of them.
let relations = self.find_event_relations(room_id, eid1, None).await.unwrap();
assert_eq!(relations.len(), 2);
assert!(relations.iter().any(|r| r.event_id().as_deref() == Some(edit_eid1)));
assert!(relations.iter().any(|r| r.event_id().as_deref() == Some(reaction_eid1)));
// The position is `None` for items outside the linked chunk.
assert!(
relations
.iter()
.any(|(ev, pos)| ev.event_id().as_deref() == Some(edit_eid1) && pos.is_none())
);
assert!(
relations
.iter()
.any(|(ev, pos)| ev.event_id().as_deref() == Some(reaction_eid1) && pos.is_none())
);
// Finding relations with a filter only returns a subset.
let relations = self
@@ -951,7 +1063,7 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
.await
.unwrap();
assert_eq!(relations.len(), 1);
assert_eq!(relations[0].event_id().as_deref(), Some(edit_eid1));
assert_eq!(relations[0].0.event_id().as_deref(), Some(edit_eid1));
let relations = self
.find_event_relations(
@@ -962,8 +1074,8 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
.await
.unwrap();
assert_eq!(relations.len(), 2);
assert!(relations.iter().any(|r| r.event_id().as_deref() == Some(edit_eid1)));
assert!(relations.iter().any(|r| r.event_id().as_deref() == Some(reaction_eid1)));
assert!(relations.iter().any(|r| r.0.event_id().as_deref() == Some(edit_eid1)));
assert!(relations.iter().any(|r| r.0.event_id().as_deref() == Some(reaction_eid1)));
// We can't find relations using the wrong room.
let relations = self
@@ -971,6 +1083,37 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
.await
.unwrap();
assert!(relations.is_empty());
// But if an event exists in the linked chunk, we may have its position when
// it's found as a relationship.
// Add reaction_e1 to the room's linked chunk.
self.handle_linked_chunk_updates(
LinkedChunkId::Room(room_id),
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems { at: Position::new(CId::new(0), 0), items: vec![reaction_e1] },
],
)
.await
.unwrap();
// When looking for aggregations to e1, we should have the position for
// reaction_e1.
let relations = self.find_event_relations(room_id, eid1, None).await.unwrap();
// The position is set for `reaction_eid1` now.
assert!(relations.iter().any(|(ev, pos)| {
ev.event_id().as_deref() == Some(reaction_eid1)
&& *pos == Some(Position::new(CId::new(0), 0))
}));
// But it's still not set for the other related events.
assert!(
relations
.iter()
.any(|(ev, pos)| ev.event_id().as_deref() == Some(edit_eid1) && pos.is_none())
);
}
async fn test_save_event(&self) {
@@ -1003,16 +1146,151 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
assert_eq!(event.event_id(), event_gruyere.event_id());
// But they won't be returned when searching in the wrong room.
assert!(self
.find_event(another_room_id, event_comte.event_id().unwrap().as_ref())
assert!(
self.find_event(another_room_id, event_comte.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none()
);
assert!(
self.find_event(room_id, event_gruyere.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none()
);
}
async fn test_thread_vs_room_linked_chunk(&self) {
let room_id = room_id!("!r0:matrix.org");
let event = |msg: &str| make_test_event(room_id, msg);
let thread1_ev = event("comté");
let thread2_ev = event("gruyère");
let thread2_ev2 = event("beaufort");
let room_ev = event("brillat savarin triple crème");
let thread_root1 = event("thread1");
let thread_root2 = event("thread2");
// Add one event in a thread linked chunk.
self.handle_linked_chunk_updates(
LinkedChunkId::Thread(room_id, thread_root1.event_id().unwrap().as_ref()),
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems {
at: Position::new(CId::new(0), 0),
items: vec![thread1_ev.clone()],
},
],
)
.await
.unwrap();
// Add one event in another thread linked chunk (same room).
self.handle_linked_chunk_updates(
LinkedChunkId::Thread(room_id, thread_root2.event_id().unwrap().as_ref()),
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems {
at: Position::new(CId::new(0), 0),
items: vec![thread2_ev.clone(), thread2_ev2.clone()],
},
],
)
.await
.unwrap();
// Add another event to the room linked chunk.
self.handle_linked_chunk_updates(
LinkedChunkId::Room(room_id),
vec![
Update::NewItemsChunk { previous: None, new: CId::new(0), next: None },
Update::PushItems {
at: Position::new(CId::new(0), 0),
items: vec![room_ev.clone()],
},
],
)
.await
.unwrap();
// All the events can be found with `find_event()` for the room.
self.find_event(room_id, thread2_ev.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none());
assert!(self
.find_event(room_id, event_gruyere.event_id().unwrap().as_ref())
.expect("failed to find thread1_ev");
self.find_event(room_id, thread2_ev.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.is_none());
.expect("failed to find thread2_ev");
self.find_event(room_id, thread2_ev2.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.expect("failed to find thread2_ev2");
self.find_event(room_id, room_ev.event_id().unwrap().as_ref())
.await
.expect("failed to query for finding an event")
.expect("failed to find room_ev");
// Finding duplicates operates based on the linked chunk id.
let dups = self
.filter_duplicated_events(
LinkedChunkId::Thread(room_id, thread_root1.event_id().unwrap().as_ref()),
vec![
thread1_ev.event_id().unwrap().to_owned(),
room_ev.event_id().unwrap().to_owned(),
],
)
.await
.unwrap();
assert_eq!(dups.len(), 1);
assert_eq!(dups[0].0, thread1_ev.event_id().unwrap());
// Loading all chunks operates based on the linked chunk id.
let all_chunks = self
.load_all_chunks(LinkedChunkId::Thread(
room_id,
thread_root2.event_id().unwrap().as_ref(),
))
.await
.unwrap();
assert_eq!(all_chunks.len(), 1);
assert_eq!(all_chunks[0].identifier, CId::new(0));
assert_let!(ChunkContent::Items(observed_items) = all_chunks[0].content.clone());
assert_eq!(observed_items.len(), 2);
assert_eq!(observed_items[0].event_id(), thread2_ev.event_id());
assert_eq!(observed_items[1].event_id(), thread2_ev2.event_id());
// Loading the metadata of all chunks operates based on the linked chunk
// id.
let metas = self
.load_all_chunks_metadata(LinkedChunkId::Thread(
room_id,
thread_root2.event_id().unwrap().as_ref(),
))
.await
.unwrap();
assert_eq!(metas.len(), 1);
assert_eq!(metas[0].identifier, CId::new(0));
assert_eq!(metas[0].num_items, 2);
// Loading the last chunk operates based on the linked chunk id.
let (last_chunk, _chunk_identifier_generator) = self
.load_last_chunk(LinkedChunkId::Thread(
room_id,
thread_root1.event_id().unwrap().as_ref(),
))
.await
.unwrap();
let last_chunk = last_chunk.unwrap();
assert_eq!(last_chunk.identifier, CId::new(0));
assert_let!(ChunkContent::Items(observed_items) = last_chunk.content);
assert_eq!(observed_items.len(), 1);
assert_eq!(observed_items[0].event_id(), thread1_ev.event_id());
}
}
@@ -1035,8 +1313,8 @@ impl EventCacheStoreIntegrationTests for DynEventCacheStore {
/// mod tests {
/// use super::{EventCacheStore, EventCacheStoreResult, MyStore};
///
/// async fn get_event_cache_store(
/// ) -> EventCacheStoreResult<impl EventCacheStore> {
/// async fn get_event_cache_store()
/// -> EventCacheStoreResult<impl EventCacheStore> {
/// Ok(MyStore::new())
/// }
///
@@ -1091,10 +1369,17 @@ macro_rules! event_cache_store_integration_tests {
}
#[async_test]
async fn test_clear_all_rooms_chunks() {
async fn test_load_all_chunks_metadata() {
let event_cache_store =
get_event_cache_store().await.unwrap().into_event_cache_store();
event_cache_store.test_clear_all_rooms_chunks().await;
event_cache_store.test_load_all_chunks_metadata().await;
}
#[async_test]
async fn test_clear_all_linked_chunks() {
let event_cache_store =
get_event_cache_store().await.unwrap().into_event_cache_store();
event_cache_store.test_clear_all_linked_chunks().await;
}
#[async_test]
@@ -1131,6 +1416,13 @@ macro_rules! event_cache_store_integration_tests {
get_event_cache_store().await.unwrap().into_event_cache_store();
event_cache_store.test_save_event().await;
}
#[async_test]
async fn test_thread_vs_room_linked_chunk() {
let event_cache_store =
get_event_cache_store().await.unwrap().into_event_cache_store();
event_cache_store.test_thread_vs_room_linked_chunk().await;
}
}
};
}
@@ -1141,11 +1433,14 @@ macro_rules! event_cache_store_integration_tests {
#[macro_export]
macro_rules! event_cache_store_integration_tests_time {
() => {
#[cfg(not(target_arch = "wasm32"))]
mod event_cache_store_integration_tests_time {
use std::time::Duration;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use gloo_timers::future::sleep;
use matrix_sdk_test::async_test;
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
use tokio::time::sleep;
use $crate::event_cache::store::IntoEventCacheStore;
use super::get_event_cache_store;
@@ -1174,26 +1469,26 @@ macro_rules! event_cache_store_integration_tests_time {
assert!(!acquired5);
// That's a nice test we got here, go take a little nap.
tokio::time::sleep(Duration::from_millis(50)).await;
sleep(Duration::from_millis(50)).await;
// Still too early.
let acquired55 = store.try_take_leased_lock(300, "key", "bob").await.unwrap();
assert!(!acquired55);
// Ok you can take another nap then.
tokio::time::sleep(Duration::from_millis(250)).await;
sleep(Duration::from_millis(250)).await;
// At some point, we do get the lock.
let acquired6 = store.try_take_leased_lock(0, "key", "bob").await.unwrap();
assert!(acquired6);
tokio::time::sleep(Duration::from_millis(1)).await;
sleep(Duration::from_millis(1)).await;
// The other gets it almost immediately too.
let acquired7 = store.try_take_leased_lock(0, "key", "alice").await.unwrap();
assert!(acquired7);
tokio::time::sleep(Duration::from_millis(1)).await;
sleep(Duration::from_millis(1)).await;
// But when we take a longer lease...
let acquired8 = store.try_take_leased_lock(300, "key", "bob").await.unwrap();
@@ -15,7 +15,6 @@
//! Trait and macro of integration tests for `EventCacheStoreMedia`
//! implementations.
use async_trait::async_trait;
use ruma::{
events::room::MediaSource,
mxc_uri, owned_mxc_uri,
@@ -23,7 +22,7 @@ use ruma::{
};
use super::{
media_service::IgnoreMediaRetentionPolicy, EventCacheStoreMedia, MediaRetentionPolicy,
EventCacheStoreMedia, MediaRetentionPolicy, media_service::IgnoreMediaRetentionPolicy,
};
use crate::media::{MediaFormat, MediaRequestParameters};
@@ -31,8 +30,7 @@ use crate::media::{MediaFormat, MediaRequestParameters};
///
/// This trait is not meant to be used directly, but will be used with the
/// `event_cache_store_media_integration_tests!` macro.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[allow(async_fn_in_trait)]
pub trait EventCacheStoreMediaIntegrationTests {
/// Test media retention policy storage.
async fn test_store_media_retention_policy(&self);
@@ -58,8 +56,6 @@ pub trait EventCacheStoreMediaIntegrationTests {
async fn test_store_last_media_cleanup_time(&self);
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<Store> EventCacheStoreMediaIntegrationTests for Store
where
Store: EventCacheStoreMedia + std::fmt::Debug,
@@ -16,11 +16,11 @@ use std::{fmt, sync::Arc};
use async_trait::async_trait;
use matrix_sdk_common::{
executor::{spawn, JoinHandle},
locks::Mutex,
AsyncTraitDeps, SendOutsideWasm, SyncOutsideWasm,
executor::{JoinHandle, spawn},
locks::Mutex,
};
use ruma::{time::SystemTime, MxcUri};
use ruma::{MxcUri, time::SystemTime};
use tokio::sync::Mutex as AsyncMutex;
use tracing::error;
@@ -356,8 +356,8 @@ where
/// [`MediaRetentionPolicy`] by wrapping this in a [`MediaService`], and to
/// simplify the implementation of tests by being able to have complete control
/// over the `SystemTime`s provided to the store.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
pub trait EventCacheStoreMedia: AsyncTraitDeps + Clone {
/// The error type used by this media cache store.
type Error: fmt::Debug + fmt::Display + Into<EventCacheStoreError>;
@@ -538,15 +538,15 @@ mod tests {
use matrix_sdk_common::locks::Mutex;
use matrix_sdk_test::async_test;
use ruma::{
MxcUri, OwnedMxcUri,
events::room::MediaSource,
mxc_uri,
time::{Duration, SystemTime},
MxcUri, OwnedMxcUri,
};
use super::{EventCacheStoreMedia, IgnoreMediaRetentionPolicy, MediaService, TimeProvider};
use crate::{
event_cache::store::{media::MediaRetentionPolicy, EventCacheStoreError},
event_cache::store::{EventCacheStoreError, media::MediaRetentionPolicy},
media::{MediaFormat, MediaRequestParameters, UniqueKey},
};
@@ -630,8 +630,8 @@ mod tests {
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl EventCacheStoreMedia for MockEventCacheStoreMedia {
type Error = MockEventCacheStoreMediaError;
@@ -21,23 +21,22 @@ use std::{
use async_trait::async_trait;
use matrix_sdk_common::{
linked_chunk::{
relational::RelationalLinkedChunk, ChunkIdentifier, ChunkIdentifierGenerator, Position,
RawChunk, Update,
ChunkIdentifier, ChunkIdentifierGenerator, ChunkMetadata, LinkedChunkId, Position,
RawChunk, Update, relational::RelationalLinkedChunk,
},
ring_buffer::RingBuffer,
store_locks::memory_store_helper::try_take_leased_lock,
};
use ruma::{
EventId, MxcUri, OwnedEventId, OwnedMxcUri, RoomId,
events::relation::RelationType,
time::{Instant, SystemTime},
EventId, MxcUri, OwnedEventId, OwnedMxcUri, RoomId,
};
use tracing::error;
use super::{
compute_filters_string, extract_event_relation,
EventCacheStore, EventCacheStoreError, Result, compute_filters_string, extract_event_relation,
media::{EventCacheStoreMedia, IgnoreMediaRetentionPolicy, MediaRetentionPolicy, MediaService},
EventCacheStore, EventCacheStoreError, Result,
};
use crate::{
event_cache::{Event, Gap},
@@ -110,8 +109,8 @@ impl MemoryStore {
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl EventCacheStore for MemoryStore {
type Error = EventCacheStoreError;
@@ -128,70 +127,81 @@ impl EventCacheStore for MemoryStore {
async fn handle_linked_chunk_updates(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
updates: Vec<Update<Event, Gap>>,
) -> Result<(), Self::Error> {
let mut inner = self.inner.write().unwrap();
inner.events.apply_updates(room_id, updates);
inner.events.apply_updates(linked_chunk_id, updates);
Ok(())
}
async fn load_all_chunks(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<Vec<RawChunk<Event, Gap>>, Self::Error> {
let inner = self.inner.read().unwrap();
inner
.events
.load_all_chunks(room_id)
.load_all_chunks(linked_chunk_id)
.map_err(|err| EventCacheStoreError::InvalidData { details: err })
}
async fn load_all_chunks_metadata(
&self,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<Vec<ChunkMetadata>, Self::Error> {
let inner = self.inner.read().unwrap();
inner
.events
.load_all_chunks_metadata(linked_chunk_id)
.map_err(|err| EventCacheStoreError::InvalidData { details: err })
}
async fn load_last_chunk(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<(Option<RawChunk<Event, Gap>>, ChunkIdentifierGenerator), Self::Error> {
let inner = self.inner.read().unwrap();
inner
.events
.load_last_chunk(room_id)
.load_last_chunk(linked_chunk_id)
.map_err(|err| EventCacheStoreError::InvalidData { details: err })
}
async fn load_previous_chunk(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
before_chunk_identifier: ChunkIdentifier,
) -> Result<Option<RawChunk<Event, Gap>>, Self::Error> {
let inner = self.inner.read().unwrap();
inner
.events
.load_previous_chunk(room_id, before_chunk_identifier)
.load_previous_chunk(linked_chunk_id, before_chunk_identifier)
.map_err(|err| EventCacheStoreError::InvalidData { details: err })
}
async fn clear_all_rooms_chunks(&self) -> Result<(), Self::Error> {
async fn clear_all_linked_chunks(&self) -> Result<(), Self::Error> {
self.inner.write().unwrap().events.clear();
Ok(())
}
async fn filter_duplicated_events(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
mut events: Vec<OwnedEventId>,
) -> Result<Vec<(OwnedEventId, Position)>, Self::Error> {
// Collect all duplicated events.
if events.is_empty() {
return Ok(Vec::new());
}
let inner = self.inner.read().unwrap();
let mut duplicated_events = Vec::new();
for (event, position) in inner.events.unordered_room_items(room_id) {
// If `events` is empty, we can short-circuit.
if events.is_empty() {
break;
}
for (event, position) in
inner.events.unordered_linked_chunk_items(&linked_chunk_id.to_owned())
{
if let Some(known_event_id) = event.event_id() {
// This event is a duplicate!
if let Some(index) =
@@ -212,9 +222,10 @@ impl EventCacheStore for MemoryStore {
) -> Result<Option<Event>, Self::Error> {
let inner = self.inner.read().unwrap();
let event = inner.events.items().find_map(|(event, this_room_id)| {
(room_id == this_room_id && event.event_id()? == event_id).then_some(event.clone())
});
let event = inner
.events
.items(room_id)
.find_map(|(event, _pos)| (event.event_id()? == event_id).then_some(event.clone()));
Ok(event)
}
@@ -224,20 +235,15 @@ impl EventCacheStore for MemoryStore {
room_id: &RoomId,
event_id: &EventId,
filters: Option<&[RelationType]>,
) -> Result<Vec<Event>, Self::Error> {
) -> Result<Vec<(Event, Option<Position>)>, Self::Error> {
let inner = self.inner.read().unwrap();
let filters = compute_filters_string(filters);
let related_events = inner
.events
.items()
.filter_map(|(event, this_room_id)| {
// Must be in the same room.
if room_id != this_room_id {
return None;
}
.items(room_id)
.filter_map(|(event, pos)| {
// Must have a relation.
let (related_to, rel_type) = extract_event_relation(event.raw())?;
@@ -248,9 +254,9 @@ impl EventCacheStore for MemoryStore {
// Must not be filtered out.
if let Some(filters) = &filters {
filters.contains(&rel_type).then_some(event.clone())
filters.contains(&rel_type).then_some((event.clone(), pos))
} else {
Some(event.clone())
Some((event.clone(), pos))
}
})
.collect();
@@ -364,8 +370,8 @@ impl EventCacheStore for MemoryStore {
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl EventCacheStoreMedia for MemoryStore {
type Error = EventCacheStoreError;
@@ -399,7 +405,7 @@ impl EventCacheStoreMedia for MemoryStore {
if !ignore_policy && policy.exceeds_max_file_size(data.len() as u64) {
// Do not store it.
return Ok(());
};
}
// Now, let's add it.
let mut inner = self.inner.write().unwrap();
@@ -33,9 +33,9 @@ use matrix_sdk_common::store_locks::{
};
pub use matrix_sdk_store_encryption::Error as StoreEncryptionError;
use ruma::{
events::{relation::RelationType, AnySyncTimelineEvent},
serde::Raw,
OwnedEventId,
events::{AnySyncTimelineEvent, relation::RelationType},
serde::Raw,
};
use tracing::trace;
@@ -43,7 +43,7 @@ use tracing::trace;
pub use self::integration_tests::EventCacheStoreIntegrationTests;
pub use self::{
memory_store::MemoryStore,
traits::{DynEventCacheStore, EventCacheStore, IntoEventCacheStore, DEFAULT_CHUNK_CAPACITY},
traits::{DEFAULT_CHUNK_CAPACITY, DynEventCacheStore, EventCacheStore, IntoEventCacheStore},
};
/// The high-level public type to represent an `EventCacheStore` lock.
@@ -185,8 +185,6 @@ pub type Result<T, E = EventCacheStoreError> = std::result::Result<T, E>;
#[derive(Clone, Debug)]
struct LockableEventCacheStore(Arc<DynEventCacheStore>);
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl BackingStore for LockableEventCacheStore {
type LockError = EventCacheStoreError;
@@ -238,11 +236,7 @@ pub fn compute_filters_string(filters: Option<&[RelationType]>) -> Option<Vec<St
filter
.iter()
.map(|f| {
if *f == RelationType::Replacement {
"m.replace".to_owned()
} else {
f.to_string()
}
if *f == RelationType::Replacement { "m.replace".to_owned() } else { f.to_string() }
})
.collect()
})
@@ -16,14 +16,17 @@ use std::{fmt, sync::Arc};
use async_trait::async_trait;
use matrix_sdk_common::{
linked_chunk::{ChunkIdentifier, ChunkIdentifierGenerator, Position, RawChunk, Update},
AsyncTraitDeps,
linked_chunk::{
ChunkIdentifier, ChunkIdentifierGenerator, ChunkMetadata, LinkedChunkId, Position,
RawChunk, Update,
},
};
use ruma::{events::relation::RelationType, EventId, MxcUri, OwnedEventId, RoomId};
use ruma::{EventId, MxcUri, OwnedEventId, RoomId, events::relation::RelationType};
use super::{
media::{IgnoreMediaRetentionPolicy, MediaRetentionPolicy},
EventCacheStoreError,
media::{IgnoreMediaRetentionPolicy, MediaRetentionPolicy},
};
use crate::{
event_cache::{Event, Gap},
@@ -37,8 +40,8 @@ pub const DEFAULT_CHUNK_CAPACITY: usize = 128;
/// An abstract trait that can be used to implement different store backends
/// for the event cache of the SDK.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
pub trait EventCacheStore: AsyncTraitDeps {
/// The error type used by this event cache store.
type Error: fmt::Debug + Into<EventCacheStoreError>;
@@ -56,7 +59,7 @@ pub trait EventCacheStore: AsyncTraitDeps {
/// in-memory. This method aims at forwarding this update inside this store.
async fn handle_linked_chunk_updates(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
updates: Vec<Update<Event, Gap>>,
) -> Result<(), Self::Error>;
@@ -64,7 +67,7 @@ pub trait EventCacheStore: AsyncTraitDeps {
async fn remove_room(&self, room_id: &RoomId) -> Result<(), Self::Error> {
// Right now, this means removing all the linked chunk. If implementations
// override this behavior, they should *also* include this code.
self.handle_linked_chunk_updates(room_id, vec![Update::Clear]).await
self.handle_linked_chunk_updates(LinkedChunkId::Room(room_id), vec![Update::Clear]).await
}
/// Return all the raw components of a linked chunk, so the caller may
@@ -72,16 +75,25 @@ pub trait EventCacheStore: AsyncTraitDeps {
#[doc(hidden)]
async fn load_all_chunks(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<Vec<RawChunk<Event, Gap>>, Self::Error>;
/// Load all of the chunks' metadata for the given [`LinkedChunkId`].
///
/// Chunks are unordered, and there's no guarantee that the chunks would
/// form a valid linked chunk after reconstruction.
async fn load_all_chunks_metadata(
&self,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<Vec<ChunkMetadata>, Self::Error>;
/// Load the last chunk of the `LinkedChunk` holding all events of the room
/// identified by `room_id`.
///
/// This is used to iteratively load events for the `EventCache`.
async fn load_last_chunk(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<(Option<RawChunk<Event, Gap>>, ChunkIdentifierGenerator), Self::Error>;
/// Load the chunk before the chunk identified by `before_chunk_identifier`
@@ -91,7 +103,7 @@ pub trait EventCacheStore: AsyncTraitDeps {
/// This is used to iteratively load events for the `EventCache`.
async fn load_previous_chunk(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
before_chunk_identifier: ChunkIdentifier,
) -> Result<Option<RawChunk<Event, Gap>>, Self::Error>;
@@ -105,33 +117,48 @@ pub trait EventCacheStore: AsyncTraitDeps {
/// ⚠ This is meant only for super specific use cases, where there shouldn't
/// be any live in-memory linked chunks. In general, prefer using
/// `EventCache::clear_all_rooms()` from the common SDK crate.
async fn clear_all_rooms_chunks(&self) -> Result<(), Self::Error>;
async fn clear_all_linked_chunks(&self) -> Result<(), Self::Error>;
/// Given a set of event IDs, return the duplicated events along with their
/// position if there are any.
async fn filter_duplicated_events(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
events: Vec<OwnedEventId>,
) -> Result<Vec<(OwnedEventId, Position)>, Self::Error>;
/// Find an event by its ID.
/// Find an event by its ID in a room.
///
/// This method must return events saved either in any linked chunks, *or*
/// events saved "out-of-band" with the [`Self::save_event`] method.
async fn find_event(
&self,
room_id: &RoomId,
event_id: &EventId,
) -> Result<Option<Event>, Self::Error>;
/// Find all the events that relate to a given event.
/// Find all the events (alongside their position in the room's linked
/// chunk, if available) that relate to a given event.
///
/// The only events which don't have a position are those which have been
/// saved out-of-band using [`Self::save_event`].
///
/// Note: it doesn't process relations recursively: for instance, if
/// requesting only thread events, it will NOT return the aggregated
/// events affecting the returned events. It is the responsibility of
/// the caller to do so, if needed.
///
/// An additional filter can be provided to only retrieve related events for
/// a certain relationship.
///
/// This method must return events saved either in any linked chunks, *or*
/// events saved "out-of-band" with the [`Self::save_event`] method.
async fn find_event_relations(
&self,
room_id: &RoomId,
event_id: &EventId,
filter: Option<&[RelationType]>,
) -> Result<Vec<Event>, Self::Error>;
) -> Result<Vec<(Event, Option<Position>)>, Self::Error>;
/// Save an event, that might or might not be part of an existing linked
/// chunk.
@@ -217,7 +244,7 @@ pub trait EventCacheStore: AsyncTraitDeps {
///
/// * `uri` - The `MxcUri` of the media file.
async fn get_media_content_for_uri(&self, uri: &MxcUri)
-> Result<Option<Vec<u8>>, Self::Error>;
-> Result<Option<Vec<u8>>, Self::Error>;
/// Remove all the media files' content associated to an `MxcUri` from the
/// media store.
@@ -277,8 +304,8 @@ impl<T: fmt::Debug> fmt::Debug for EraseEventCacheStoreError<T> {
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
impl<T: EventCacheStore> EventCacheStore for EraseEventCacheStoreError<T> {
type Error = EventCacheStoreError;
@@ -293,44 +320,54 @@ impl<T: EventCacheStore> EventCacheStore for EraseEventCacheStoreError<T> {
async fn handle_linked_chunk_updates(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
updates: Vec<Update<Event, Gap>>,
) -> Result<(), Self::Error> {
self.0.handle_linked_chunk_updates(room_id, updates).await.map_err(Into::into)
self.0.handle_linked_chunk_updates(linked_chunk_id, updates).await.map_err(Into::into)
}
async fn load_all_chunks(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<Vec<RawChunk<Event, Gap>>, Self::Error> {
self.0.load_all_chunks(room_id).await.map_err(Into::into)
self.0.load_all_chunks(linked_chunk_id).await.map_err(Into::into)
}
async fn load_all_chunks_metadata(
&self,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<Vec<ChunkMetadata>, Self::Error> {
self.0.load_all_chunks_metadata(linked_chunk_id).await.map_err(Into::into)
}
async fn load_last_chunk(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
) -> Result<(Option<RawChunk<Event, Gap>>, ChunkIdentifierGenerator), Self::Error> {
self.0.load_last_chunk(room_id).await.map_err(Into::into)
self.0.load_last_chunk(linked_chunk_id).await.map_err(Into::into)
}
async fn load_previous_chunk(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
before_chunk_identifier: ChunkIdentifier,
) -> Result<Option<RawChunk<Event, Gap>>, Self::Error> {
self.0.load_previous_chunk(room_id, before_chunk_identifier).await.map_err(Into::into)
self.0
.load_previous_chunk(linked_chunk_id, before_chunk_identifier)
.await
.map_err(Into::into)
}
async fn clear_all_rooms_chunks(&self) -> Result<(), Self::Error> {
self.0.clear_all_rooms_chunks().await.map_err(Into::into)
async fn clear_all_linked_chunks(&self) -> Result<(), Self::Error> {
self.0.clear_all_linked_chunks().await.map_err(Into::into)
}
async fn filter_duplicated_events(
&self,
room_id: &RoomId,
linked_chunk_id: LinkedChunkId<'_>,
events: Vec<OwnedEventId>,
) -> Result<Vec<(OwnedEventId, Position)>, Self::Error> {
self.0.filter_duplicated_events(room_id, events).await.map_err(Into::into)
self.0.filter_duplicated_events(linked_chunk_id, events).await.map_err(Into::into)
}
async fn find_event(
@@ -346,7 +383,7 @@ impl<T: EventCacheStore> EventCacheStore for EraseEventCacheStoreError<T> {
room_id: &RoomId,
event_id: &EventId,
filter: Option<&[RelationType]>,
) -> Result<Vec<Event>, Self::Error> {
) -> Result<Vec<(Event, Option<Position>)>, Self::Error> {
self.0.find_event_relations(room_id, event_id, filter).await.map_err(Into::into)
}
@@ -433,6 +470,12 @@ pub trait IntoEventCacheStore {
fn into_event_cache_store(self) -> Arc<DynEventCacheStore>;
}
impl IntoEventCacheStore for Arc<DynEventCacheStore> {
fn into_event_cache_store(self) -> Arc<DynEventCacheStore> {
self
}
}
impl<T> IntoEventCacheStore for T
where
T: EventCacheStore + Sized + 'static,
+67 -34
View File
@@ -2,9 +2,12 @@
//! use as a [crate::Room::latest_event].
use matrix_sdk_common::deserialized_responses::TimelineEvent;
use ruma::{MilliSecondsSinceUnixEpoch, MxcUri, OwnedEventId};
#[cfg(feature = "e2e-encryption")]
use ruma::{
UserId,
events::{
AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent,
call::{invite::SyncCallInviteEvent, notify::SyncCallNotifyEvent},
poll::unstable_start::SyncUnstablePollStartEvent,
relation::RelationType,
@@ -14,14 +17,43 @@ use ruma::{
power_levels::RoomPowerLevels,
},
sticker::SyncStickerEvent,
AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent,
},
UserId,
};
use ruma::{MxcUri, OwnedEventId};
use serde::{Deserialize, Serialize};
use crate::MinimalRoomMemberEvent;
use crate::{MinimalRoomMemberEvent, store::SerializableEventContent};
/// A latest event value!
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub enum LatestEventValue {
/// No value has been computed yet, or no candidate value was found.
#[default]
None,
/// The latest event represents a remote event.
Remote(RemoteLatestEventValue),
/// The latest event represents a local event that is sending.
LocalIsSending(LocalLatestEventValue),
/// The latest event represents a local event that cannot be sent, either
/// because a previous local event, or this local event cannot be sent.
LocalCannotBeSent(LocalLatestEventValue),
}
/// Represents the value for [`LatestEventValue::Remote`].
pub type RemoteLatestEventValue = TimelineEvent;
/// Represents the value for [`LatestEventValue::LocalIsSending`] and
/// [`LatestEventValue::LocalCannotBeSent`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalLatestEventValue {
/// The time where the event has been created (by this module).
pub timestamp: MilliSecondsSinceUnixEpoch,
/// The content of the local event.
pub content: SerializableEventContent,
}
/// Represents a decision about whether an event could be stored as the latest
/// event in a room. Variants starting with Yes indicate that this message could
@@ -125,21 +157,21 @@ pub fn is_suitable_for_latest_event<'a>(
AnySyncTimelineEvent::State(state) => {
// But we make an exception for knocked state events *if* the current user
// can either accept or decline them
if let AnySyncStateEvent::RoomMember(member) = state {
if matches!(member.membership(), MembershipState::Knock) {
let can_accept_or_decline_knocks = match power_levels_info {
Some((own_user_id, room_power_levels)) => {
room_power_levels.user_can_invite(own_user_id)
|| room_power_levels.user_can_kick(own_user_id)
}
_ => false,
};
// The current user can act on the knock changes, so they should be
// displayed
if can_accept_or_decline_knocks {
return PossibleLatestEvent::YesKnockedStateEvent(member);
if let AnySyncStateEvent::RoomMember(member) = state
&& matches!(member.membership(), MembershipState::Knock)
{
let can_accept_or_decline_knocks = match power_levels_info {
Some((own_user_id, room_power_levels)) => {
room_power_levels.user_can_invite(own_user_id)
|| room_power_levels.user_can_kick(own_user_id)
}
_ => false,
};
// The current user can act on the knock changes, so they should be
// displayed
if can_accept_or_decline_knocks {
return PossibleLatestEvent::YesKnockedStateEvent(member);
}
}
PossibleLatestEvent::NoUnsupportedEventType
@@ -227,9 +259,10 @@ impl<'de> Deserialize<'de> for LatestEvent {
Err(err) => variant_errors.push(err),
}
Err(serde::de::Error::custom(
format!("data did not match any variant of serialized LatestEvent (using serde_json). Observed errors: {variant_errors:?}")
))
Err(serde::de::Error::custom(format!(
"data did not match any variant of serialized LatestEvent (using serde_json). \
Observed errors: {variant_errors:?}"
)))
}
}
@@ -310,13 +343,17 @@ mod tests {
use ruma::serde::Raw;
#[cfg(feature = "e2e-encryption")]
use ruma::{
MilliSecondsSinceUnixEpoch, UInt, VoipVersionId,
events::{
AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent, EmptyStateKey,
Mentions, MessageLikeUnsigned, OriginalSyncMessageLikeEvent, OriginalSyncStateEvent,
RedactedSyncMessageLikeEvent, RedactedUnsigned, StateUnsigned, SyncMessageLikeEvent,
call::{
SessionDescription,
invite::{CallInviteEventContent, SyncCallInviteEvent},
notify::{
ApplicationType, CallNotifyEventContent, NotifyType, SyncCallNotifyEvent,
},
SessionDescription,
},
poll::{
unstable_response::{
@@ -329,6 +366,7 @@ mod tests {
},
relation::Replacement,
room::{
ImageInfo, MediaSource,
encrypted::{
EncryptedEventScheme, OlmV1Curve25519AesSha2Content, RoomEncryptedEventContent,
SyncRoomEncryptedEvent,
@@ -338,22 +376,16 @@ mod tests {
Relation, RoomMessageEventContent, SyncRoomMessageEvent,
},
topic::{RoomTopicEventContent, SyncRoomTopicEvent},
ImageInfo, MediaSource,
},
sticker::{StickerEventContent, SyncStickerEvent},
AnySyncMessageLikeEvent, AnySyncStateEvent, AnySyncTimelineEvent, EmptyStateKey,
Mentions, MessageLikeUnsigned, OriginalSyncMessageLikeEvent, OriginalSyncStateEvent,
RedactedSyncMessageLikeEvent, RedactedUnsigned, StateUnsigned, SyncMessageLikeEvent,
UnsignedRoomRedactionEvent,
},
owned_event_id, owned_mxc_uri, owned_user_id, MilliSecondsSinceUnixEpoch, UInt,
VoipVersionId,
owned_event_id, owned_mxc_uri, owned_user_id,
};
use serde_json::json;
use super::LatestEvent;
#[cfg(feature = "e2e-encryption")]
use super::{is_suitable_for_latest_event, PossibleLatestEvent};
use super::{PossibleLatestEvent, is_suitable_for_latest_event};
#[cfg(feature = "e2e-encryption")]
#[test]
@@ -500,7 +532,7 @@ mod tests {
#[test]
fn test_redacted_messages_are_suitable() {
// Ruma does not allow constructing UnsignedRoomRedactionEvent instances.
let room_redaction_event: UnsignedRoomRedactionEvent = serde_json::from_value(json!({
let room_redaction_event = serde_json::from_value(json!({
"content": {},
"event_id": "$redaction",
"sender": "@x:y.za",
@@ -629,7 +661,7 @@ mod tests {
latest_event: LatestEvent,
}
let event = TimelineEvent::new(
let event = TimelineEvent::from_plaintext(
Raw::from_json_string(json!({ "event_id": "$1" }).to_string()).unwrap(),
);
@@ -654,8 +686,9 @@ mod tests {
"event_id": "$1"
}
}
}
},
},
"thread_summary": "None",
}
}
})
);
+10 -10
View File
@@ -15,7 +15,7 @@
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(target_arch = "wasm32", allow(clippy::arc_with_non_send_sync))]
#![cfg_attr(target_family = "wasm", allow(clippy::arc_with_non_send_sync))]
#![warn(missing_docs, missing_debug_implementations)]
pub use matrix_sdk_common::*;
@@ -34,10 +34,9 @@ pub mod latest_event;
pub mod media;
pub mod notification_settings;
mod response_processors;
mod rooms;
mod room;
pub mod read_receipts;
pub use read_receipts::PreviousEventsProvider;
pub mod sliding_sync;
pub mod store;
@@ -49,27 +48,28 @@ mod utils;
#[cfg(feature = "uniffi")]
uniffi::setup_scaffolding!();
pub use client::BaseClient;
pub use client::{BaseClient, ThreadingSupport};
#[cfg(any(test, feature = "testing"))]
pub use http;
#[cfg(feature = "e2e-encryption")]
pub use matrix_sdk_crypto as crypto;
pub use once_cell;
pub use rooms::{
apply_redaction, EncryptionState, Room, RoomCreateWithCreatorEventContent, RoomDisplayName,
RoomHero, RoomInfo, RoomInfoNotableUpdate, RoomInfoNotableUpdateReasons, RoomMember,
RoomMembersUpdate, RoomMemberships, RoomState, RoomStateFilter,
pub use room::{
EncryptionState, InviteAcceptanceDetails, PredecessorRoom, Room,
RoomCreateWithCreatorEventContent, RoomDisplayName, RoomHero, RoomInfo, RoomInfoNotableUpdate,
RoomInfoNotableUpdateReasons, RoomMember, RoomMembersUpdate, RoomMemberships, RoomState,
RoomStateFilter, SuccessorRoom, apply_redaction,
};
pub use store::{
ComposerDraft, ComposerDraftType, QueueWedgeError, StateChanges, StateStore, StateStoreDataKey,
StateStoreDataValue, StoreError,
StateStoreDataValue, StoreError, ThreadSubscriptionCatchupToken,
};
pub use utils::{
MinimalRoomMemberEvent, MinimalStateEvent, OriginalMinimalStateEvent, RedactedMinimalStateEvent,
};
#[cfg(test)]
matrix_sdk_test::init_tracing_for_tests!();
matrix_sdk_test_utils::init_tracing_for_tests!();
/// The Matrix user session info.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
+2 -2
View File
@@ -1,18 +1,18 @@
//! Common types for [media content](https://matrix.org/docs/spec/client_server/r0.6.1#id66).
use ruma::{
MxcUri, UInt,
api::client::media::get_content_thumbnail::v3::Method,
events::{
room::{
MediaSource,
message::{
AudioMessageEventContent, FileMessageEventContent, ImageMessageEventContent,
LocationMessageEventContent, VideoMessageEventContent,
},
MediaSource,
},
sticker::StickerEventContent,
},
MxcUri, UInt,
};
use serde::{Deserialize, Serialize};
+197 -107
View File
@@ -122,22 +122,26 @@ use std::{
num::NonZeroUsize,
};
use eyeball_im::Vector;
use matrix_sdk_common::{deserialized_responses::TimelineEvent, ring_buffer::RingBuffer};
use matrix_sdk_common::{
deserialized_responses::TimelineEvent, ring_buffer::RingBuffer,
serde_helpers::extract_thread_root,
};
use ruma::{
EventId, OwnedEventId, OwnedUserId, RoomId, UserId,
events::{
AnySyncMessageLikeEvent, AnySyncTimelineEvent, OriginalSyncMessageLikeEvent,
SyncMessageLikeEvent,
poll::{start::PollStartEventContent, unstable_start::UnstablePollStartEventContent},
receipt::{ReceiptEventContent, ReceiptThread, ReceiptType},
room::message::Relation,
AnySyncMessageLikeEvent, AnySyncTimelineEvent, OriginalSyncMessageLikeEvent,
SyncMessageLikeEvent,
},
serde::Raw,
EventId, OwnedEventId, OwnedUserId, RoomId, UserId,
};
use serde::{Deserialize, Serialize};
use tracing::{debug, instrument, trace, warn};
use crate::ThreadingSupport;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
struct LatestReadReceipt {
/// The id of the event the read receipt is referring to. (Not the read
@@ -202,7 +206,18 @@ impl RoomReadReceipts {
///
/// Returns whether a new event triggered a new unread/notification/mention.
#[inline(always)]
fn process_event(&mut self, event: &TimelineEvent, user_id: &UserId) {
fn process_event(
&mut self,
event: &TimelineEvent,
user_id: &UserId,
threading_support: ThreadingSupport,
) {
if matches!(threading_support, ThreadingSupport::Enabled { .. })
&& extract_thread_root(event.raw()).is_some()
{
return;
}
if marks_as_unread(event.raw(), user_id) {
self.num_unread += 1;
}
@@ -210,7 +225,7 @@ impl RoomReadReceipts {
let mut has_notify = false;
let mut has_mention = false;
let Some(actions) = event.push_actions.as_ref() else {
let Some(actions) = event.push_actions() else {
return;
};
@@ -241,6 +256,7 @@ impl RoomReadReceipts {
receipt_event_id: &EventId,
user_id: &UserId,
events: impl IntoIterator<Item = &'a TimelineEvent>,
threading_support: ThreadingSupport,
) -> bool {
let mut counting_receipts = false;
@@ -248,19 +264,19 @@ impl RoomReadReceipts {
// Sliding sync sometimes sends the same event multiple times, so it can be at
// the beginning and end of a batch, for instance. In that case, just reset
// every time we see the event matching the receipt.
if let Some(event_id) = event.event_id() {
if event_id == receipt_event_id {
// Bingo! Switch over to the counting state, after resetting the
// previous counts.
trace!("Found the event the receipt was referring to! Starting to count.");
self.reset();
counting_receipts = true;
continue;
}
if let Some(event_id) = event.event_id()
&& event_id == receipt_event_id
{
// Bingo! Switch over to the counting state, after resetting the
// previous counts.
trace!("Found the event the receipt was referring to! Starting to count.");
self.reset();
counting_receipts = true;
continue;
}
if counting_receipts {
self.process_event(event, user_id);
self.process_event(event, user_id, threading_support);
}
}
@@ -268,19 +284,6 @@ impl RoomReadReceipts {
}
}
/// Provider for timeline events prior to the current sync.
pub trait PreviousEventsProvider: Send + Sync {
/// Returns the list of known timeline events, in sync order, for the given
/// room.
fn for_room(&self, room_id: &RoomId) -> Vector<TimelineEvent>;
}
impl PreviousEventsProvider for () {
fn for_room(&self, _: &RoomId) -> Vector<TimelineEvent> {
Vector::new()
}
}
/// Small helper to select the "best" receipt (that with the biggest sync
/// order).
struct ReceiptSelector {
@@ -294,10 +297,7 @@ struct ReceiptSelector {
}
impl ReceiptSelector {
fn new(
all_events: &Vector<TimelineEvent>,
latest_active_receipt_event: Option<&EventId>,
) -> Self {
fn new(all_events: &[TimelineEvent], latest_active_receipt_event: Option<&EventId>) -> Self {
let event_id_to_pos = Self::create_sync_index(all_events.iter());
let best_pos =
@@ -387,17 +387,17 @@ impl ReceiptSelector {
// Now consider new receipts.
for (event_id, receipts) in &receipt_event.0 {
for ty in [ReceiptType::Read, ReceiptType::ReadPrivate] {
if let Some(receipt) = receipts.get(&ty).and_then(|receipts| receipts.get(user_id))
if let Some(receipts) = receipts.get(&ty)
&& let Some(receipt) = receipts.get(user_id)
&& matches!(receipt.thread, ReceiptThread::Main | ReceiptThread::Unthreaded)
{
if matches!(receipt.thread, ReceiptThread::Main | ReceiptThread::Unthreaded) {
trace!(%event_id, "found new candidate");
if let Some(event_pos) = self.event_id_to_pos.get(event_id) {
self.try_select_later(event_id, *event_pos);
} else {
// It's a new pending receipt.
trace!(%event_id, "stashed as pending");
pending.push(event_id.clone());
}
trace!(%event_id, "found new candidate");
if let Some(event_pos) = self.event_id_to_pos.get(event_id) {
self.try_select_later(event_id, *event_pos);
} else {
// It's a new pending receipt.
trace!(%event_id, "stashed as pending");
pending.push(event_id.clone());
}
}
}
@@ -457,23 +457,23 @@ pub(crate) fn compute_unread_counts(
user_id: &UserId,
room_id: &RoomId,
receipt_event: Option<&ReceiptEventContent>,
previous_events: Vector<TimelineEvent>,
mut previous_events: Vec<TimelineEvent>,
new_events: &[TimelineEvent],
read_receipts: &mut RoomReadReceipts,
threading_support: ThreadingSupport,
) {
debug!(?read_receipts, "Starting.");
debug!(?read_receipts, "Starting");
let all_events = if events_intersects(previous_events.iter(), new_events) {
// The previous and new events sets can intersect, for instance if we restored
// previous events from the disk cache, or a timeline was limited. This
// means the old events will be cleared, because we don't reconcile
// timelines in sliding sync (yet). As a result, forget
// timelines in the event cache (yet). As a result, forget
// about the previous events.
Vector::from_iter(new_events.iter().cloned())
new_events.to_owned()
} else {
let mut all_events = previous_events;
all_events.extend(new_events.iter().cloned());
all_events
previous_events.extend(new_events.iter().cloned());
previous_events
};
let new_receipt = {
@@ -481,6 +481,7 @@ pub(crate) fn compute_unread_counts(
&all_events,
read_receipts.latest_active.as_ref().map(|receipt| &*receipt.event_id),
);
selector.try_match_implicit(user_id, new_events);
selector.handle_pending_receipts(&mut read_receipts.pending);
if let Some(receipt_event) = receipt_event {
@@ -506,7 +507,12 @@ pub(crate) fn compute_unread_counts(
// The event for the receipt is in `all_events`, so we'll find it and can count
// safely from here.
read_receipts.find_and_process_events(&event_id, user_id, all_events.iter());
read_receipts.find_and_process_events(
&event_id,
user_id,
all_events.iter(),
threading_support,
);
debug!(?read_receipts, "after finding a better receipt");
return;
@@ -520,7 +526,7 @@ pub(crate) fn compute_unread_counts(
// for the next receipt.
for event in new_events {
read_receipts.process_event(event, user_id);
read_receipts.process_event(event, user_id, threading_support);
}
debug!(?read_receipts, "no better receipt, {} new events", new_events.len());
@@ -622,22 +628,24 @@ fn marks_as_unread(event: &Raw<AnySyncTimelineEvent>, user_id: &UserId) -> bool
mod tests {
use std::{num::NonZeroUsize, ops::Not as _};
use eyeball_im::Vector;
use matrix_sdk_common::{deserialized_responses::TimelineEvent, ring_buffer::RingBuffer};
use matrix_sdk_test::event_factory::EventFactory;
use ruma::{
event_id,
EventId, UserId, event_id,
events::{
receipt::{ReceiptThread, ReceiptType},
room::{member::MembershipState, message::MessageType},
},
owned_event_id, owned_user_id,
push::Action,
room_id, user_id, EventId, UserId,
room_id, user_id,
};
use super::compute_unread_counts;
use crate::read_receipts::{marks_as_unread, ReceiptSelector, RoomReadReceipts};
use crate::{
ThreadingSupport,
read_receipts::{ReceiptSelector, RoomReadReceipts, marks_as_unread},
};
#[test]
fn test_room_message_marks_as_unread() {
@@ -729,7 +737,7 @@ mod tests {
.sender(user_id)
.event_id(event_id!("$ida"))
.into_event();
ev.push_actions = Some(push_actions);
ev.set_push_actions(push_actions);
ev
}
@@ -738,7 +746,7 @@ mod tests {
// An interesting event from oneself doesn't count as a new unread message.
let event = make_event(user_id, Vec::new());
let mut receipts = RoomReadReceipts::default();
receipts.process_event(&event, user_id);
receipts.process_event(&event, user_id, ThreadingSupport::Disabled);
assert_eq!(receipts.num_unread, 0);
assert_eq!(receipts.num_mentions, 0);
assert_eq!(receipts.num_notifications, 0);
@@ -746,7 +754,7 @@ mod tests {
// An interesting event from someone else does count as a new unread message.
let event = make_event(user_id!("@bob:example.org"), Vec::new());
let mut receipts = RoomReadReceipts::default();
receipts.process_event(&event, user_id);
receipts.process_event(&event, user_id, ThreadingSupport::Disabled);
assert_eq!(receipts.num_unread, 1);
assert_eq!(receipts.num_mentions, 0);
assert_eq!(receipts.num_notifications, 0);
@@ -754,7 +762,7 @@ mod tests {
// Push actions computed beforehand are respected.
let event = make_event(user_id!("@bob:example.org"), vec![Action::Notify]);
let mut receipts = RoomReadReceipts::default();
receipts.process_event(&event, user_id);
receipts.process_event(&event, user_id, ThreadingSupport::Disabled);
assert_eq!(receipts.num_unread, 1);
assert_eq!(receipts.num_mentions, 0);
assert_eq!(receipts.num_notifications, 1);
@@ -764,7 +772,7 @@ mod tests {
vec![Action::SetTweak(ruma::push::Tweak::Highlight(true))],
);
let mut receipts = RoomReadReceipts::default();
receipts.process_event(&event, user_id);
receipts.process_event(&event, user_id, ThreadingSupport::Disabled);
assert_eq!(receipts.num_unread, 1);
assert_eq!(receipts.num_mentions, 1);
assert_eq!(receipts.num_notifications, 0);
@@ -774,7 +782,7 @@ mod tests {
vec![Action::SetTweak(ruma::push::Tweak::Highlight(true)), Action::Notify],
);
let mut receipts = RoomReadReceipts::default();
receipts.process_event(&event, user_id);
receipts.process_event(&event, user_id, ThreadingSupport::Disabled);
assert_eq!(receipts.num_unread, 1);
assert_eq!(receipts.num_mentions, 1);
assert_eq!(receipts.num_notifications, 1);
@@ -783,7 +791,7 @@ mod tests {
// make sure to resist against it.
let event = make_event(user_id!("@bob:example.org"), vec![Action::Notify, Action::Notify]);
let mut receipts = RoomReadReceipts::default();
receipts.process_event(&event, user_id);
receipts.process_event(&event, user_id, ThreadingSupport::Disabled);
assert_eq!(receipts.num_unread, 1);
assert_eq!(receipts.num_mentions, 0);
assert_eq!(receipts.num_notifications, 1);
@@ -797,7 +805,9 @@ mod tests {
// When provided with no events, we report not finding the event to which the
// receipt relates.
let mut receipts = RoomReadReceipts::default();
assert!(receipts.find_and_process_events(ev0, user_id, &[]).not());
assert!(
receipts.find_and_process_events(ev0, user_id, &[], ThreadingSupport::Disabled).not()
);
assert_eq!(receipts.num_unread, 0);
assert_eq!(receipts.num_notifications, 0);
assert_eq!(receipts.num_mentions, 0);
@@ -818,9 +828,16 @@ mod tests {
num_mentions: 37,
..Default::default()
};
assert!(receipts
.find_and_process_events(ev0, user_id, &[make_event(event_id!("$1"))],)
.not());
assert!(
receipts
.find_and_process_events(
ev0,
user_id,
&[make_event(event_id!("$1"))],
ThreadingSupport::Disabled
)
.not()
);
assert_eq!(receipts.num_unread, 42);
assert_eq!(receipts.num_notifications, 13);
assert_eq!(receipts.num_mentions, 37);
@@ -834,7 +851,12 @@ mod tests {
num_mentions: 37,
..Default::default()
};
assert!(receipts.find_and_process_events(ev0, user_id, &[make_event(ev0)]));
assert!(receipts.find_and_process_events(
ev0,
user_id,
&[make_event(ev0)],
ThreadingSupport::Disabled
),);
assert_eq!(receipts.num_unread, 0);
assert_eq!(receipts.num_notifications, 0);
assert_eq!(receipts.num_mentions, 0);
@@ -847,17 +869,20 @@ mod tests {
num_mentions: 37,
..Default::default()
};
assert!(receipts
.find_and_process_events(
ev0,
user_id,
&[
make_event(event_id!("$1")),
make_event(event_id!("$2")),
make_event(event_id!("$3"))
],
)
.not());
assert!(
receipts
.find_and_process_events(
ev0,
user_id,
&[
make_event(event_id!("$1")),
make_event(event_id!("$2")),
make_event(event_id!("$3"))
],
ThreadingSupport::Disabled
)
.not()
);
assert_eq!(receipts.num_unread, 42);
assert_eq!(receipts.num_notifications, 13);
assert_eq!(receipts.num_mentions, 37);
@@ -879,6 +904,7 @@ mod tests {
make_event(event_id!("$2")),
make_event(event_id!("$3"))
],
ThreadingSupport::Disabled
));
assert_eq!(receipts.num_unread, 2);
assert_eq!(receipts.num_notifications, 0);
@@ -901,6 +927,7 @@ mod tests {
make_event(event_id!("$2")),
make_event(event_id!("$3"))
],
ThreadingSupport::Disabled
));
assert_eq!(receipts.num_unread, 2);
assert_eq!(receipts.num_notifications, 0);
@@ -915,7 +942,7 @@ mod tests {
let room_id = room_id!("!room:example.org");
let receipt_event_id = event_id!("$1");
let mut previous_events = Vector::new();
let mut previous_events = Vec::new();
let f = EventFactory::new();
let ev1 = f.text_msg("A").sender(other_user_id).event_id(receipt_event_id).into_event();
@@ -926,7 +953,7 @@ mod tests {
.add(receipt_event_id, user_id, ReceiptType::Read, ReceiptThread::Unthreaded)
.into_content();
let mut read_receipts = Default::default();
let mut read_receipts = RoomReadReceipts::default();
compute_unread_counts(
user_id,
room_id,
@@ -934,14 +961,15 @@ mod tests {
previous_events.clone(),
&[ev1.clone(), ev2.clone()],
&mut read_receipts,
ThreadingSupport::Disabled,
);
// It did find the receipt event (ev1).
assert_eq!(read_receipts.num_unread, 1);
// Receive the same receipt event, with a new sync event.
previous_events.push_back(ev1);
previous_events.push_back(ev2);
previous_events.push(ev1);
previous_events.push(ev2);
let new_event =
f.text_msg("A").sender(other_user_id).event_id(event_id!("$3")).into_event();
@@ -952,13 +980,14 @@ mod tests {
previous_events,
&[new_event],
&mut read_receipts,
ThreadingSupport::Disabled,
);
// Only the new event should be added.
assert_eq!(read_receipts.num_unread, 2);
}
fn make_test_events(user_id: &UserId) -> Vector<TimelineEvent> {
fn make_test_events(user_id: &UserId) -> Vec<TimelineEvent> {
let f = EventFactory::new().sender(user_id);
let ev1 = f.text_msg("With the lights out, it's less dangerous").event_id(event_id!("$1"));
let ev2 = f.text_msg("Here we are now, entertain us").event_id(event_id!("$2"));
@@ -976,7 +1005,7 @@ mod tests {
let room_id = room_id!("!room:example.org");
let all_events = make_test_events(user_id!("@bob:example.org"));
let head_events: Vector<_> = all_events.iter().take(2).cloned().collect();
let head_events: Vec<_> = all_events.iter().take(2).cloned().collect();
let tail_events: Vec<_> = all_events.iter().skip(2).cloned().collect();
// Given a receipt event marking events 1-3 as read using a combination of
@@ -1018,6 +1047,7 @@ mod tests {
all_events.clone(),
&[],
&mut read_receipts,
ThreadingSupport::Disabled,
);
assert!(
@@ -1039,6 +1069,7 @@ mod tests {
head_events.clone(),
&tail_events,
&mut read_receipts,
ThreadingSupport::Disabled,
);
assert!(
@@ -1083,6 +1114,7 @@ mod tests {
events,
&[], // no new events
&mut read_receipts,
ThreadingSupport::Disabled,
);
// Then there are no unread events,
@@ -1120,6 +1152,7 @@ mod tests {
events,
&[ev0], // duplicate event!
&mut read_receipts,
ThreadingSupport::Disabled,
);
// All events are unread, and there's no pending receipt.
@@ -1165,7 +1198,7 @@ mod tests {
{
// No initial active receipt, so the first receipt we get *will* win.
let mut selector = ReceiptSelector::new(&vec![].into(), None);
let mut selector = ReceiptSelector::new(&[], None);
selector.try_select_later(event_id!("$1"), 0);
let best_receipt = selector.select();
assert_eq!(best_receipt.unwrap().event_id, event_id!("$1"));
@@ -1203,11 +1236,11 @@ mod tests {
let f = EventFactory::new().sender(sender);
let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event();
let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event();
let events: Vector<_> = vec![ev1, ev2].into();
let events = &[ev1, ev2][..];
{
// No pending receipt => no better receipt.
let mut selector = ReceiptSelector::new(&events, None);
let mut selector = ReceiptSelector::new(events, None);
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
selector.handle_pending_receipts(&mut pending);
@@ -1221,7 +1254,7 @@ mod tests {
{
// No pending receipt, and there was an active last receipt => no better
// receipt.
let mut selector = ReceiptSelector::new(&events, Some(event_id!("$1")));
let mut selector = ReceiptSelector::new(events, Some(event_id!("$1")));
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
selector.handle_pending_receipts(&mut pending);
@@ -1239,11 +1272,11 @@ mod tests {
let f = EventFactory::new().sender(sender);
let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event();
let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event();
let events: Vector<_> = vec![ev1, ev2].into();
let events = &[ev1, ev2][..];
{
// A pending receipt for an event that is still missing => no better receipt.
let mut selector = ReceiptSelector::new(&events, None);
let mut selector = ReceiptSelector::new(events, None);
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
pending.push(owned_event_id!("$3"));
@@ -1257,7 +1290,7 @@ mod tests {
{
// Ditto but there was an active receipt => no better receipt.
let mut selector = ReceiptSelector::new(&events, Some(event_id!("$1")));
let mut selector = ReceiptSelector::new(events, Some(event_id!("$1")));
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
pending.push(owned_event_id!("$3"));
@@ -1276,11 +1309,11 @@ mod tests {
let f = EventFactory::new().sender(sender);
let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event();
let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event();
let events: Vector<_> = vec![ev1, ev2].into();
let events = &[ev1, ev2][..];
{
// A pending receipt for an event that is present => better receipt.
let mut selector = ReceiptSelector::new(&events, None);
let mut selector = ReceiptSelector::new(events, None);
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
pending.push(owned_event_id!("$2"));
@@ -1296,7 +1329,7 @@ mod tests {
{
// Mixed found and not found receipt => better receipt.
let mut selector = ReceiptSelector::new(&events, None);
let mut selector = ReceiptSelector::new(events, None);
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
pending.push(owned_event_id!("$1"));
@@ -1318,12 +1351,12 @@ mod tests {
let f = EventFactory::new().sender(sender);
let ev1 = f.text_msg("yo").event_id(event_id!("$1")).into_event();
let ev2 = f.text_msg("well?").event_id(event_id!("$2")).into_event();
let events: Vector<_> = vec![ev1, ev2].into();
let events = &[ev1, ev2][..];
{
// Same, and there was an initial receipt that was less good than the one we
// selected => better receipt.
let mut selector = ReceiptSelector::new(&events, Some(event_id!("$1")));
let mut selector = ReceiptSelector::new(events, Some(event_id!("$1")));
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
pending.push(owned_event_id!("$2"));
@@ -1339,7 +1372,7 @@ mod tests {
{
// Same, but the previous receipt was better => no better receipt.
let mut selector = ReceiptSelector::new(&events, Some(event_id!("$2")));
let mut selector = ReceiptSelector::new(events, Some(event_id!("$2")));
let mut pending = RingBuffer::new(NonZeroUsize::new(16).unwrap());
pending.push(owned_event_id!("$1"));
@@ -1484,26 +1517,26 @@ mod tests {
// When the selector sees only other users' events,
let mut selector = ReceiptSelector::new(&events, None);
// And I search for my implicit read receipt,
selector.try_match_implicit(&myself, &events.iter().cloned().collect::<Vec<_>>());
selector.try_match_implicit(&myself, &events);
// Then I don't find any.
let best_receipt = selector.select();
assert!(best_receipt.is_none());
// Now, if there are events I've written too...
let f = EventFactory::new();
events.push_back(
events.push(
f.text_msg("A mulatto, an albino")
.sender(&myself)
.event_id(event_id!("$6"))
.into_event(),
);
events.push_back(
events.push(
f.text_msg("A mosquito, my libido").sender(bob).event_id(event_id!("$7")).into_event(),
);
let mut selector = ReceiptSelector::new(&events, None);
// And I search for my implicit read receipt,
selector.try_match_implicit(&myself, &events.iter().cloned().collect::<Vec<_>>());
selector.try_match_implicit(&myself, &events);
// Then my last sent event counts as a read receipt.
let best_receipt = selector.select();
assert_eq!(best_receipt.unwrap().event_id, event_id!("$6"));
@@ -1520,7 +1553,7 @@ mod tests {
// One by me,
let f = EventFactory::new();
events.push_back(
events.push(
f.text_msg("A mulatto, an albino")
.sender(user_id)
.event_id(event_id!("$6"))
@@ -1528,10 +1561,10 @@ mod tests {
);
// And others by Bob,
events.push_back(
events.push(
f.text_msg("A mosquito, my libido").sender(bob).event_id(event_id!("$7")).into_event(),
);
events.push_back(
events.push(
f.text_msg("A denial, a denial").sender(bob).event_id(event_id!("$8")).into_event(),
);
@@ -1551,9 +1584,10 @@ mod tests {
user_id,
room_id,
Some(&receipt_event),
Vector::new(),
Vec::new(),
&events,
&mut read_receipts,
ThreadingSupport::Disabled,
);
// Only the last two events sent by Bob count as unread.
@@ -1565,4 +1599,60 @@ mod tests {
// And the active receipt is the implicit one on my event.
assert_eq!(read_receipts.latest_active.unwrap().event_id, event_id!("$6"));
}
#[test]
fn test_compute_unread_counts_with_threading_enabled() {
fn make_event(user_id: &UserId, thread_root: &EventId) -> TimelineEvent {
EventFactory::new()
.text_msg("A")
.sender(user_id)
.event_id(event_id!("$ida"))
.in_thread(thread_root, event_id!("$latest_event"))
.into_event()
}
let mut receipts = RoomReadReceipts::default();
let own_alice = user_id!("@alice:example.org");
let bob = user_id!("@bob:example.org");
// Threaded messages from myself or other users shouldn't change the
// unread counts.
receipts.process_event(
&make_event(own_alice, event_id!("$some_thread_root")),
own_alice,
ThreadingSupport::Enabled { with_subscriptions: false },
);
receipts.process_event(
&make_event(own_alice, event_id!("$some_other_thread_root")),
own_alice,
ThreadingSupport::Enabled { with_subscriptions: false },
);
receipts.process_event(
&make_event(bob, event_id!("$some_thread_root")),
own_alice,
ThreadingSupport::Enabled { with_subscriptions: false },
);
receipts.process_event(
&make_event(bob, event_id!("$some_other_thread_root")),
own_alice,
ThreadingSupport::Enabled { with_subscriptions: false },
);
assert_eq!(receipts.num_unread, 0);
assert_eq!(receipts.num_mentions, 0);
assert_eq!(receipts.num_notifications, 0);
// Processing an unthreaded message should still count as unread.
receipts.process_event(
&EventFactory::new().text_msg("A").sender(bob).event_id(event_id!("$ida")).into_event(),
own_alice,
ThreadingSupport::Enabled { with_subscriptions: false },
);
assert_eq!(receipts.num_unread, 1);
assert_eq!(receipts.num_mentions, 0);
assert_eq!(receipts.num_notifications, 0);
}
}
@@ -17,17 +17,18 @@ use std::{
mem,
};
use matrix_sdk_common::timer;
use ruma::{
RoomId,
events::{
direct::OwnedDirectUserIdentifier, AnyGlobalAccountDataEvent, GlobalAccountDataEventType,
AnyGlobalAccountDataEvent, GlobalAccountDataEventType, direct::OwnedDirectUserIdentifier,
},
serde::Raw,
RoomId,
};
use tracing::{debug, instrument, trace, warn};
use super::super::Context;
use crate::{store::BaseStateStore, RoomInfo, StateChanges};
use crate::{RoomInfo, StateChanges, store::BaseStateStore};
/// Create the [`Global`] account data processor.
pub fn global(events: &[Raw<AnyGlobalAccountDataEvent>]) -> Global {
@@ -43,6 +44,8 @@ pub struct Global {
impl Global {
/// Creates a new processor for global account data.
fn process(events: &[Raw<AnyGlobalAccountDataEvent>]) -> Self {
let _timer = timer!(tracing::Level::TRACE, "Global::process (global account data)");
let mut raw_by_type = BTreeMap::new();
let mut parsed_events = Vec::new();
@@ -102,10 +105,10 @@ impl Global {
// Update the direct targets of rooms if they changed.
for (room_id, new_direct_targets) in new_dms {
if let Some(old_direct_targets) = old_dms.remove(&room_id) {
if old_direct_targets == new_direct_targets {
continue;
}
if let Some(old_direct_targets) = old_dms.remove(&room_id)
&& old_direct_targets == new_direct_targets
{
continue;
}
trace!(?room_id, targets = ?new_direct_targets, "Marking room as direct room");
map_info(room_id, state_changes, state_store, |info| {
@@ -125,6 +128,8 @@ impl Global {
/// Applies the processed data to the state changes and the state store.
pub async fn apply(mut self, context: &mut Context, state_store: &BaseStateStore) {
let _timer = timer!(tracing::Level::TRACE, "Global::apply (global account data)");
// Fill in the content of `changes.account_data`.
mem::swap(&mut context.state_changes.account_data, &mut self.raw_by_type);
@@ -15,5 +15,5 @@
mod global;
mod room;
pub use global::{global, Global};
pub use global::{Global, global};
pub use room::for_room;
@@ -13,17 +13,20 @@
// limitations under the License.
use ruma::{
events::{marked_unread::MarkedUnreadEventContent, AnyRoomAccountDataEvent},
serde::Raw,
RoomId,
events::{AnyRoomAccountDataEvent, marked_unread::MarkedUnreadEventContent},
serde::Raw,
};
use tracing::{instrument, warn};
use super::super::{Context, RoomInfoNotableUpdates};
use crate::{store::BaseStateStore, RoomInfo, RoomInfoNotableUpdateReasons, StateChanges};
use crate::{
RoomInfo, RoomInfoNotableUpdateReasons, StateChanges, room::AccountDataSource,
store::BaseStateStore,
};
#[instrument(skip_all, fields(?room_id))]
pub async fn for_room(
pub fn for_room(
context: &mut Context,
room_id: &RoomId,
events: &[Raw<AnyRoomAccountDataEvent>],
@@ -49,6 +52,7 @@ pub async fn for_room(
on_unread_marker(
room_id,
&event.content,
AccountDataSource::Stable,
room_info,
&mut context.room_info_notable_updates,
);
@@ -64,6 +68,7 @@ pub async fn for_room(
on_unread_marker(
room_id,
&event.content.0,
AccountDataSource::Unstable,
room_info,
&mut context.room_info_notable_updates,
);
@@ -127,9 +132,17 @@ fn on_room_info<F>(
fn on_unread_marker(
room_id: &RoomId,
content: &MarkedUnreadEventContent,
source: AccountDataSource,
room_info: &mut RoomInfo,
room_info_notable_updates: &mut RoomInfoNotableUpdates,
) {
if room_info.base_info.is_marked_unread_source == AccountDataSource::Stable
&& source != AccountDataSource::Stable
{
// Ignore the unstable source if a stable source was used previously.
return;
}
if room_info.base_info.is_marked_unread != content.unread {
// Notify the room list about a manual read marker change if the
// value's changed.
@@ -140,4 +153,5 @@ fn on_unread_marker(
}
room_info.base_info.is_marked_unread = content.unread;
room_info.base_info.is_marked_unread_source = source;
}
@@ -13,18 +13,31 @@
// limitations under the License.
use eyeball::SharedObservable;
use matrix_sdk_common::timer;
use ruma::{
events::{ignored_user_list::IgnoredUserListEvent, GlobalAccountDataEventType},
events::{GlobalAccountDataEventType, ignored_user_list::IgnoredUserListEvent},
serde::Raw,
};
use tracing::{error, instrument, trace};
use super::Context;
use crate::{
store::{BaseStateStore, StateStoreExt as _},
Result,
store::{BaseStateStore, StateStoreExt as _},
};
/// Save the [`StateChanges`] from the [`Context`] inside the [`BaseStateStore`]
/// only! The changes aren't applied on the in-memory rooms.
#[instrument(skip_all)]
pub async fn save_only(context: Context, state_store: &BaseStateStore) -> Result<()> {
let _timer = timer!(tracing::Level::TRACE, "_method");
save_changes(&context, state_store, None).await?;
broadcast_room_info_notable_updates(&context, state_store);
Ok(())
}
/// Save the [`StateChanges`] from the [`Context`] inside the
/// [`BaseStateStore`], and apply them on the in-memory rooms.
#[instrument(skip_all)]
@@ -34,35 +47,45 @@ pub async fn save_and_apply(
ignore_user_list_changes: &SharedObservable<Vec<String>>,
sync_token: Option<String>,
) -> Result<()> {
let _timer = timer!(tracing::Level::TRACE, "_method");
trace!("ready to submit changes to store");
let previous_ignored_user_list =
state_store.get_account_data_event_static().await.ok().flatten();
state_store.save_changes(&context.state_changes).await?;
if let Some(sync_token) = sync_token {
*state_store.sync_token.write().await = Some(sync_token);
}
apply_changes(context, state_store, ignore_user_list_changes, previous_ignored_user_list);
save_changes(&context, state_store, sync_token).await?;
apply_changes(&context, ignore_user_list_changes, previous_ignored_user_list);
broadcast_room_info_notable_updates(&context, state_store);
trace!("applied changes");
Ok(())
}
fn apply_changes(
context: Context,
async fn save_changes(
context: &Context,
state_store: &BaseStateStore,
sync_token: Option<String>,
) -> Result<()> {
state_store.save_changes(&context.state_changes).await?;
if let Some(sync_token) = sync_token {
*state_store.sync_token.write().await = Some(sync_token);
}
Ok(())
}
fn apply_changes(
context: &Context,
ignore_user_list_changes: &SharedObservable<Vec<String>>,
previous_ignored_user_list: Option<Raw<IgnoredUserListEvent>>,
) {
let (state_changes, room_info_notable_updates) = context.into_parts();
if let Some(event) =
state_changes.account_data.get(&GlobalAccountDataEventType::IgnoredUserList)
context.state_changes.account_data.get(&GlobalAccountDataEventType::IgnoredUserList)
{
match event.deserialize_as::<IgnoredUserListEvent>() {
match event.deserialize_as_unchecked::<IgnoredUserListEvent>() {
Ok(event) => {
let user_ids: Vec<String> =
event.content.ignored_users.keys().map(|id| id.to_string()).collect();
@@ -93,11 +116,13 @@ fn apply_changes(
}
}
}
}
for (room_id, room_info) in &state_changes.room_infos {
fn broadcast_room_info_notable_updates(context: &Context, state_store: &BaseStateStore) {
for (room_id, room_info) in &context.state_changes.room_infos {
if let Some(room) = state_store.room(room_id) {
let room_info_notable_update_reasons =
room_info_notable_updates.get(room_id).copied().unwrap_or_default();
context.room_info_notable_updates.get(room_id).copied().unwrap_or_default();
room.set_room_info(room_info.clone(), room_info_notable_update_reasons)
}
@@ -13,12 +13,10 @@
// limitations under the License.
use matrix_sdk_common::deserialized_responses::TimelineEvent;
use matrix_sdk_crypto::{
DecryptionSettings, OlmMachine, RoomEventDecryptionResult, TrustRequirement,
};
use ruma::{events::AnySyncTimelineEvent, serde::Raw, RoomId};
use matrix_sdk_crypto::RoomEventDecryptionResult;
use ruma::{RoomId, events::AnySyncTimelineEvent, serde::Raw};
use super::super::{verification, Context};
use super::{super::verification, E2EE};
use crate::Result;
/// Attempt to decrypt the given raw event into a [`TimelineEvent`].
@@ -29,38 +27,29 @@ use crate::Result;
///
/// Returns `Ok(None)` if encryption is not configured.
pub async fn sync_timeline_event(
context: &mut Context,
olm_machine: Option<&OlmMachine>,
e2ee: E2EE<'_>,
event: &Raw<AnySyncTimelineEvent>,
room_id: &RoomId,
decryption_trust_requirement: TrustRequirement,
verification_is_allowed: bool,
) -> Result<Option<TimelineEvent>> {
let Some(olm) = olm_machine else { return Ok(None) };
let decryption_settings =
DecryptionSettings { sender_device_trust_requirement: decryption_trust_requirement };
let Some(olm) = e2ee.olm_machine else { return Ok(None) };
Ok(Some(
match olm.try_decrypt_room_event(event.cast_ref(), room_id, &decryption_settings).await? {
match olm
.try_decrypt_room_event(event.cast_ref_unchecked(), room_id, e2ee.decryption_settings)
.await?
{
RoomEventDecryptionResult::Decrypted(decrypted) => {
let timeline_event = TimelineEvent::from(decrypted);
// Note: the push actions are set by the caller.
let timeline_event = TimelineEvent::from_decrypted(decrypted, None);
if let Ok(sync_timeline_event) = timeline_event.raw().deserialize() {
verification::process_if_relevant(
context,
&sync_timeline_event,
verification_is_allowed,
olm_machine,
room_id,
)
.await?;
verification::process_if_relevant(&sync_timeline_event, e2ee, room_id).await?;
}
timeline_event
}
RoomEventDecryptionResult::UnableToDecrypt(utd_info) => {
TimelineEvent::new_utd_event(event.clone(), utd_info)
TimelineEvent::from_utd(event.clone(), utd_info)
}
},
))

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